DIK-7: страница «Вся база» со всеми заведениями
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 10s
deploy / deploy (pull_request) Successful in 20s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Peppa 2026-11-16 13:53:19 +05:00
parent a84f7afb2e
commit 50a079fafe
16 changed files with 133 additions and 5 deletions

View File

@ -11,6 +11,7 @@
- База заведений — data/venues.csv + data/districts.csv (CSV «;», UTF-8 BOM, русские заголовки), сайт читает её через src/venues.js; правила колонок и источники — docs/venues-base.md; data/mock-venues.json удалён (DIK-2)
- Скрытие устаревшего (DIK-3): свежесть считается в src/lib.js (isStale/offerStatus, 14 дней), правка владельцем — /admin (Basic, ADMIN_PASSWORD), пишет data/venues.csv в DATA_DIR (том в compose); тесты server/fresh используют createHandler({dataDir,password})
- Экран списка: пустой ответ с фильтром клиент перепроверяет без фильтра (далеко vs нет предложений); геолокация с тайм-аутом 10 с; новые тексты — сразу в ru/kk/en (DIK-4)
- Страница «Вся база» (DIK-7): /base + /api/base (store.all, без скрытия устаревшего), public/base.html+base.js; новые колонки/тексты — в ru/kk/en
## Грабли
- 2ГИС отдаёт данные только через WebFetch (curl — пустая оболочка); в карточке есть «Ланч от N ₸» и «Ланч ЧЧ:ММ-ЧЧ:ММ» на /tab/info, дней недели нет; часть левого берега — район Нура, а пр. Абая/Республики — Байконур и Сарыарка, не Алматы

View File

@ -0,0 +1,4 @@
## Решения
- Отдельная статическая страница base.html + base.js: таблица читает /api/base, работает в любом браузере.
- /api/base не скрывает устаревшие записи (в отличие от списка рядом) — это «вся база как есть»; свежесть гарантирует `npm run venues:fresh`.
- Нет ланча — «бизнес-ланча нет», нет акции — «нет»; даты ДД.ММ.ГГГГ.

View File

@ -0,0 +1,7 @@
## Why
Владельцу нужно видеть всю стартовую базу заведений целиком, без специальных программ.
## What Changes
- Страница `/base`: таблица всех заведений (название, район, адрес, координаты, ланч, акция, дата проверки).
- `GET /api/base` отдаёт всю базу без скрытия устаревшего; ссылка «Вся база» в меню.
- Тексты на ru/kk/en.

View File

@ -0,0 +1,15 @@
## ADDED Requirements
### Requirement: Страница со всей базой
Сервис SHALL показывать на странице `/base` таблицу всех заведений базы: название, район, адрес, координаты, время и цену бизнес-ланча в тенге, акцию и дату проверки в формате ДД.ММ.ГГГГ. Если бизнес-ланча нет, SHALL быть написано «бизнес-ланча нет», если нет акции — «нет».
#### Scenario: Открытие таблицы
- **GIVEN** в базе 29 заведений
- **WHEN** пользователь открывает страницу «Вся база»
- **THEN** он видит 29 строк без дублей
- **AND** у каждой есть название, адрес, координаты и дата проверки
#### Scenario: Нет ланча и акции
- **GIVEN** у заведения нет бизнес-ланча и акции
- **WHEN** пользователь смотрит его строку
- **THEN** в колонке ланча написано «бизнес-ланча нет», в колонке акции — «нет»

View File

@ -0,0 +1,4 @@
## 1. Реализация
- [x] 1.1 /api/base и store.all()
- [x] 1.2 Страница /base, ссылка в меню, переводы ru/kk/en
- [x] 1.3 Тест сценария и проверки (lint, test, build, venues:fresh)

View File

@ -89,3 +89,17 @@
- **GIVEN** у заведения район «Нура», которого нет в таблице районов
- **WHEN** запускается проверка базы
- **THEN** проверка завершается ошибкой «района «Нура» нет в data/districts.csv»
### Requirement: Страница со всей базой
Сервис SHALL показывать на странице `/base` таблицу всех заведений базы: название, район, адрес, координаты, время и цену бизнес-ланча в тенге, акцию и дату проверки в формате ДД.ММ.ГГГГ. Если бизнес-ланча нет, SHALL быть написано «бизнес-ланча нет», если нет акции — «нет».
#### Scenario: Открытие таблицы
- **GIVEN** в базе 29 заведений
- **WHEN** пользователь открывает страницу «Вся база»
- **THEN** он видит 29 строк без дублей
- **AND** у каждой есть название, адрес, координаты и дата проверки
#### Scenario: Нет ланча и акции
- **GIVEN** у заведения нет бизнес-ланча и акции
- **WHEN** пользователь смотрит его строку
- **THEN** в колонке ланча написано «бизнес-ланча нет», в колонке акции — «нет»

View File

@ -5,7 +5,7 @@
"type": "module",
"scripts": {
"start": "node src/index.js",
"lint": "node --check src/index.js && node --check src/lib.js && node --check src/venues.js && node --check src/admin.js && node --check scripts/check-venues.js && node --check public/app.js",
"lint": "node --check src/index.js && node --check src/lib.js && node --check src/venues.js && node --check src/admin.js && node --check scripts/check-venues.js && node --check public/app.js && node --check public/base.js",
"test": "node --test test/*.test.js",
"build": "node scripts/check-i18n.js && node scripts/check-venues.js",
"venues:fresh": "node scripts/check-venues.js --fresh"

28
public/base.html Normal file
View File

@ -0,0 +1,28 @@
<!doctype html>
<html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="theme-color" content="#e8590c">
<title>Все заведения</title>
<style>
:root{--bg:#fff8f0;--ink:#2b2118;--mute:#7a6a5c;--accent:#e8590c;--card:#fff;--line:#f1e3d3}
@media (prefers-color-scheme:dark){:root{--bg:#1d1712;--ink:#f6ece2;--mute:#b3a293;--card:#2a2119;--line:#3b2f24}}
*{box-sizing:border-box}
body{font:15px/1.4 system-ui,sans-serif;margin:0;background:var(--bg);color:var(--ink)}
header{display:flex;align-items:center;gap:12px;padding:12px 16px;background:var(--accent);color:#fff}
header h1{font-size:19px;margin:0;flex:1}
header a{color:#fff;font-weight:600}
main{padding:16px}
p{color:var(--mute);margin:0 0 8px}
.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:12px;background:var(--card)}
table{border-collapse:collapse;width:100%;min-width:900px}
th,td{padding:8px 10px;text-align:left;vertical-align:top;border-bottom:1px solid var(--line)}
th{position:sticky;top:0;background:var(--card);font-size:13px;color:var(--mute)}
.msg{padding:12px;background:#fff3bf;color:#4a3b00;border-radius:12px}
</style></head><body>
<header><h1 data-i="baseTitle"></h1><a href="/" data-i="backHome"></a></header>
<main>
<p data-i="baseIntro"></p><p id="count"></p>
<div class="wrap"><table><thead><tr id="head"></tr></thead><tbody id="rows"></tbody></table></div>
<div id="err" class="msg" hidden></div>
</main>
<script src="base.js" type="module"></script>
</body></html>

30
public/base.js Normal file
View File

@ -0,0 +1,30 @@
const LANGS = ["ru", "kk", "en"];
const saved = () => { try { return localStorage.getItem("lang"); } catch { return null; } };
const nav = (navigator.language || "").slice(0, 2);
const lang = LANGS.includes(saved()) ? saved() : LANGS.includes(nav) ? nav : "ru";
const t = await (await fetch(`i18n/${lang}.json`)).json();
const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k]);
const date = (iso) => (iso ? iso.split("-").reverse().join(".") : "");
document.documentElement.lang = lang;
document.title = t.baseTitle;
document.querySelectorAll("[data-i]").forEach((e) => (e.textContent = t[e.dataset.i]));
const COLS = ["colName", "colDistrict", "colAddress", "colCoords", "colLunch", "colPromo", "colChecked"];
document.getElementById("head").replaceChildren(...COLS.map((k) => { const th = document.createElement("th"); th.textContent = t[k]; return th; }));
try {
const r = await fetch("/api/base");
if (!r.ok) throw new Error();
const list = await r.json();
document.getElementById("count").textContent = fmt(t.baseCount, { n: list.length });
const body = document.getElementById("rows");
for (const v of list) {
const promo = v.promo ? (t.promoTexts?.[v.promo.text] || v.promo.text) + (v.promo.until ? ` (${date(v.promo.until)})` : "") : t.noPromo;
const lunch = v.lunch ? fmt(t.baseLunch, v.lunch) : t.noLunch;
const tr = document.createElement("tr");
for (const s of [v.name, t["district_" + v.district] || v.district, v.address, `${v.lat}, ${v.lng}`, lunch, promo, date(v.checked)]) {
const td = document.createElement("td"); td.textContent = s; tr.append(td);
}
body.append(tr);
}
} catch {
const e = document.getElementById("err"); e.textContent = t.baseError; e.hidden = false;
}

View File

@ -1 +1 @@
{"title": "Lunch nearby", "subtitle": "Nearest lunch places in Astana with business lunches and promotions. Two districts are covered so far: Esil and Almaty.", "useLocation": "Show places near me", "manualHint": "We could not find where you are. Choose a district or enter an address.", "addressPlaceholder": "Address, e.g. Dostyk St, 13", "findAddress": "Find by address", "onlyOffers": "Only with a business lunch or promotion", "lunch": "Business lunch {price} ₸, {from}–{to}", "promo": "Promotion: {text} (until {until})", "m": "m", "km": "km", "noneNearby": "There are no places from our list near you. We only cover the Esil and Almaty districts so far — choose a district manually.", "noOffers": "No places nearby have a business lunch or promotion right now. Turn the switch off to see all places.", "geoDenied": "We cannot access your location. Choose a district or enter an address below.", "addrNotFound": "We do not have this address. Please choose a district from the list.", "error": "The list did not load. Please try again in a moment.", "menuNearby": "Near me", "menuAbout": "About", "aboutText": "We show the nearest lunch places in Astana and mark where a business lunch or promotion is available right now. Distance is measured in a straight line. Two districts of the city are covered so far: Esil and Almaty.", "promoOpen": "Promotion: {text}", "admTitle": "Edit data", "admIntro": "Here you change business lunch prices, deals, end dates and the check date. Entries not checked for more than 14 days, and deals past their end date, are hidden on the site. To bring an entry back, set a new check date or end date.", "admName": "Place", "admPrice": "Lunch price, ₸", "admPromo": "Deal (empty — no deal)", "admUntil": "Deal ends", "admChecked": "Check date", "admToday": "Today", "admSave": "Save", "admStatus": "On the site", "admActive": "Shown", "admHiddenStale": "Hidden: not checked for more than 14 days", "admHiddenExpired": "Hidden: the deal has ended", "admNoLunch": "No business lunch", "admNoPromo": "No deal", "admLunchLabel": "Business lunch", "admPromoLabel": "Deal", "admOnlyHidden": "Hidden entries only", "admHiddenCount": "Hidden entries: {n}", "admSaved": "Saved. The changes are already on the site.", "admErrPrice": "The price is not valid. Enter a whole number of tenge, for example 3500.", "admErrDate": "The date is not valid. Pick the check date in the calendar.", "admErrFuture": "The check date is in the future. Pick today or an earlier day.", "admErrOther": "Could not save. Check the fields and try again.", "admLoadError": "Could not load the table. Refresh the page.", "admBack": "To the site", "searching": "Looking for places near you…", "menuOpen": "Open menu", "menuLabel": "Menu", "districtLabel": "District", "districtPlaceholder": "Choose a district", "addressLabel": "Address", "district_esil": "Esil", "district_almaty": "Almaty", "promoTexts": {"1 кг сазана + 1 л напитка в подарок": "1 kg of carp + 1 l of a drink as a gift", "KUDAFEST: сет из нескольких блюд, десерта и напитка за 4000 ₸, ежедневно 11:00–21:00": "KUDAFEST: a set of several dishes, a dessert and a drink for 4000 ₸, daily 11:00–21:00", "KUDAFEST: сет из нескольких блюд, десерта и напитка за 4000 ₸, ежедневно 15:00–22:30, кроме среды": "KUDAFEST: a set of several dishes, a dessert and a drink for 4000 ₸, daily 15:00–22:30 except Wednesday"}}
{"title": "Lunch nearby", "subtitle": "Nearest lunch places in Astana with business lunches and promotions. Two districts are covered so far: Esil and Almaty.", "useLocation": "Show places near me", "manualHint": "We could not find where you are. Choose a district or enter an address.", "addressPlaceholder": "Address, e.g. Dostyk St, 13", "findAddress": "Find by address", "onlyOffers": "Only with a business lunch or promotion", "lunch": "Business lunch {price} ₸, {from}–{to}", "promo": "Promotion: {text} (until {until})", "m": "m", "km": "km", "noneNearby": "There are no places from our list near you. We only cover the Esil and Almaty districts so far — choose a district manually.", "noOffers": "No places nearby have a business lunch or promotion right now. Turn the switch off to see all places.", "geoDenied": "We cannot access your location. Choose a district or enter an address below.", "addrNotFound": "We do not have this address. Please choose a district from the list.", "error": "The list did not load. Please try again in a moment.", "menuNearby": "Near me", "menuAbout": "About", "aboutText": "We show the nearest lunch places in Astana and mark where a business lunch or promotion is available right now. Distance is measured in a straight line. Two districts of the city are covered so far: Esil and Almaty.", "promoOpen": "Promotion: {text}", "admTitle": "Edit data", "admIntro": "Here you change business lunch prices, deals, end dates and the check date. Entries not checked for more than 14 days, and deals past their end date, are hidden on the site. To bring an entry back, set a new check date or end date.", "admName": "Place", "admPrice": "Lunch price, ₸", "admPromo": "Deal (empty — no deal)", "admUntil": "Deal ends", "admChecked": "Check date", "admToday": "Today", "admSave": "Save", "admStatus": "On the site", "admActive": "Shown", "admHiddenStale": "Hidden: not checked for more than 14 days", "admHiddenExpired": "Hidden: the deal has ended", "admNoLunch": "No business lunch", "admNoPromo": "No deal", "admLunchLabel": "Business lunch", "admPromoLabel": "Deal", "admOnlyHidden": "Hidden entries only", "admHiddenCount": "Hidden entries: {n}", "admSaved": "Saved. The changes are already on the site.", "admErrPrice": "The price is not valid. Enter a whole number of tenge, for example 3500.", "admErrDate": "The date is not valid. Pick the check date in the calendar.", "admErrFuture": "The check date is in the future. Pick today or an earlier day.", "admErrOther": "Could not save. Check the fields and try again.", "admLoadError": "Could not load the table. Refresh the page.", "admBack": "To the site", "searching": "Looking for places near you…", "menuOpen": "Open menu", "menuLabel": "Menu", "districtLabel": "District", "districtPlaceholder": "Choose a district", "addressLabel": "Address", "district_esil": "Esil", "district_almaty": "Almaty", "promoTexts": {"1 кг сазана + 1 л напитка в подарок": "1 kg of carp + 1 l of a drink as a gift", "KUDAFEST: сет из нескольких блюд, десерта и напитка за 4000 ₸, ежедневно 11:00–21:00": "KUDAFEST: a set of several dishes, a dessert and a drink for 4000 ₸, daily 11:00–21:00", "KUDAFEST: сет из нескольких блюд, десерта и напитка за 4000 ₸, ежедневно 15:00–22:30, кроме среды": "KUDAFEST: a set of several dishes, a dessert and a drink for 4000 ₸, daily 15:00–22:30 except Wednesday"}, "menuBase": "Full list", "baseTitle": "All places", "baseIntro": "All places in our list: address, business lunch, offer and the date we last checked.", "baseCount": "Places: {n}", "colName": "Name", "colDistrict": "District", "colAddress": "Address", "colCoords": "Coordinates", "colLunch": "Business lunch", "colPromo": "Offer", "colChecked": "Checked", "noLunch": "no business lunch", "noPromo": "none", "baseLunch": "{price} ₸, {from}–{to}", "baseError": "We could not load the places. Please refresh the page.", "backHome": "Back to nearby search"}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -42,6 +42,7 @@ section{display:none}section.on{display:block}
<nav id="menu" data-al="menuLabel">
<a href="#nearby" data-i="menuNearby"></a>
<a href="#about" data-i="menuAbout"></a>
<a href="/base" data-i="menuBase"></a>
<div class="langs"><button data-l="ru" aria-label="Русский">RU</button><button data-l="kk" aria-label="Қазақша">KK</button><button data-l="en" aria-label="English">EN</button></div>
</nav>
<main>

View File

@ -13,6 +13,15 @@ export function createStore(dataDir, seedDir = dataDir) {
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, district: v.district, 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 };
});
},
// Строки для страницы правки: поля + статус «действует / скрыта»
list(now = new Date()) {
const t = astanaTime(now);

View File

@ -53,6 +53,7 @@ function handle(req, res, store, password) {
const json = (code, body) => { res.writeHead(code, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
if (url.pathname === "/admin" || url.pathname.startsWith("/admin/")) return admin(req, res, url, store, password, json);
if (url.pathname === "/healthz") return json(200, { ok: true });
if (url.pathname === "/api/base") return json(200, store.all());
if (url.pathname === "/api/districts") return json(200, db.districts);
if (url.pathname === "/api/locate") {
const v = findAddress(db.venues, url.searchParams.get("q") || "");
@ -63,7 +64,7 @@ function handle(req, res, store, password) {
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return json(400, { error: "bad_coords" });
return json(200, buildList(db.venues, lat, lng, { only: url.searchParams.get("only") === "1" }));
}
const rel = url.pathname === "/" ? "index.html" : url.pathname.slice(1);
const rel = url.pathname === "/" ? "index.html" : url.pathname === "/base" ? "base.html" : url.pathname.slice(1);
const file = path.normalize(path.join(root, "public", rel));
if (!file.startsWith(path.join(root, "public")) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
res.writeHead(404); return res.end("Not found");

View File

@ -14,3 +14,17 @@ test("healthz и API", async () => {
assert.equal((await fetch(base + "/")).status, 200);
s.close();
});
test("Сценарий: страница «Вся база» показывает все заведения", async () => {
const s = http.createServer(createHandler()).listen(0);
const base = `http://127.0.0.1:${s.address().port}`;
assert.equal((await fetch(base + "/base")).status, 200);
const list = await (await fetch(base + "/api/base")).json();
assert.ok(list.length >= 20);
assert.equal(new Set(list.map((v) => v.name + v.address)).size, list.length);
for (const v of list) {
assert.ok(v.name && v.address && Number.isFinite(v.lat) && Number.isFinite(v.lng) && /^\d{4}-\d{2}-\d{2}$/.test(v.checked));
}
assert.ok(list.some((v) => v.lunch === null) || list.every((v) => v.lunch));
s.close();
});