DIK-45: пеший маршрут и время в карточке, сортировка по времени, «примерно» по прямой

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Peppa 2026-11-16 15:26:04 +05:00
parent f7e96509ac
commit b2e774aa10
12 changed files with 106 additions and 15 deletions

View File

@ -0,0 +1,5 @@
## Решения
- Маршруты считает сервер одним запросом к OSRM (`table`, профиль foot), адрес — `ROUTE_URL` (по умолчанию routing.openstreetmap.de/routed-foot; `off` — выключено, для тестов). Тайм-аут 4 с.
- Любая ошибка или отсутствие пути у заведения — запасной расчёт по прямой: 80 м/мин, поле `walk.approx = true`; клиент пишет «примерно».
- API `/api/venues` отдаёт `walk: {m, min, approx}`; поле `distance` (по прямой) остаётся. Радиус покрытия 5 км — по прямой.
- Без места список не строится; объяснение — в подсказке стартового экрана (`startHint`).

View File

@ -0,0 +1,7 @@
## Why
Пользователь выбирает, куда пойти пообедать, и ему важно знать, сколько идти пешком, а не расстояние по прямой.
## What Changes
- В карточке: расстояние по пешеходному маршруту и минуты («650 м, 9 мин пешком»).
- Список сортируется по времени в пути.
- Маршрут не посчитан — «примерно», по прямой.
- Места нет — расстояние не показывается, подсказка объясняет почему.

View File

@ -0,0 +1,35 @@
## MODIFIED Requirements
### Requirement: Список ближайших заведений
Система SHALL показывать заведения базы от ближайшего к дальнему по времени пешего пути, с названием, расстоянием по пешеходному маршруту, временем в минутах и адресом.
#### Scenario: Расстояние и время пешком
- **GIVEN** пользователь на Достык, 13, маршрут до «Кафе А» — 650 м, 9 минут
- **WHEN** он открывает список
- **THEN** в карточке «Кафе А» написано «650 м, 9 мин пешком»
#### Scenario: Сортировка по времени
- **GIVEN** «Кафе А» по прямой дальше, но идти до него 9 минут, а до «Кафе Б» — 25 минут
- **WHEN** пользователь открывает список
- **THEN** «Кафе А» стоит выше «Кафе Б»
#### Scenario: Маршрут посчитать не удалось
- **GIVEN** сервис маршрутов недоступен
- **WHEN** пользователь открывает список
- **THEN** в карточке написано «примерно 800 м, 10 мин пешком»
- **AND** над списком объяснено, что расстояние взято по прямой
#### Scenario: Места пользователя нет
- **GIVEN** пользователь ещё не указал, где он
- **WHEN** он открывает страницу
- **THEN** расстояние нигде не показано
- **AND** подсказка говорит, что расстояние и время появятся, когда мы узнаем, где он
#### Scenario: Тексты на трёх языках
- **WHEN** пользователь выбирает русский, казахский или английский
- **THEN** подпись про пеший путь показана на выбранном языке
#### Scenario: Рядом нет заведений
- **GIVEN** пользователь находится дальше 5 км от любого заведения базы
- **WHEN** он открывает список
- **THEN** вместо списка показано сообщение, что рядом нет заведений из базы

View File

@ -0,0 +1,4 @@
- [x] 1. src/route.js: запрос маршрутов и запасной расчёт
- [x] 2. buildList: walk и сортировка по времени
- [x] 3. Карточка и тексты ru/kk/en
- [x] 4. Тесты

View File

@ -5,8 +5,8 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"start": "node src/index.js", "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 src/page.js && node --check scripts/check-venues.js && node --check public/app.js && node --check public/base.js", "lint": "node --check src/index.js && node --check src/lib.js && node --check src/venues.js && node --check src/admin.js && node --check src/page.js && node --check src/route.js && node --check scripts/check-venues.js && node --check public/app.js && node --check public/base.js",
"test": "node --test test/*.test.js", "test": "ROUTE_URL=off node --test test/*.test.js",
"build": "node scripts/check-i18n.js && node scripts/check-venues.js", "build": "node scripts/check-i18n.js && node scripts/check-venues.js",
"venues:fresh": "node scripts/check-venues.js --fresh" "venues:fresh": "node scripts/check-venues.js --fresh"
} }

View File

@ -3,6 +3,7 @@ const $ = (id) => document.getElementById(id);
const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k]); const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k]);
const ruDate = (iso) => iso.split("-").reverse().join("."); const ruDate = (iso) => iso.split("-").reverse().join(".");
const dist = (m) => (m < 1000 ? m + " " + t.m : (m / 1000).toFixed(1) + " " + t.km); const dist = (m) => (m < 1000 ? m + " " + t.m : (m / 1000).toFixed(1) + " " + t.km);
const walk = (w) => fmt(w.approx ? t.walkApprox : t.walkExact, { dist: dist(w.m), min: w.min });
const LANGS = ["ru", "kk", "en"]; const LANGS = ["ru", "kk", "en"];
const saved = () => { try { return localStorage.getItem("lang"); } catch { return null; } }; const saved = () => { try { return localStorage.getItem("lang"); } catch { return null; } };
@ -74,12 +75,15 @@ async function show() {
const out = $("out"); out.textContent = ""; const out = $("out"); out.textContent = "";
const sum = document.createElement("div"); sum.className = "msg note"; sum.id = "summary"; const sum = document.createElement("div"); sum.className = "msg note"; sum.id = "summary";
sum.textContent = fmt($("only").checked ? t.resultsOffers : t.resultsAll, { n: list.length }); out.append(sum); sum.textContent = fmt($("only").checked ? t.resultsOffers : t.resultsAll, { n: list.length }); out.append(sum);
if (list.some((v) => v.walk.approx)) {
const n = document.createElement("div"); n.className = "msg note"; n.textContent = t.walkApproxNote; out.append(n);
}
for (const v of list) { for (const v of list) {
const c = document.createElement("div"); c.className = "card"; const c = document.createElement("div"); c.className = "card";
const body = document.createElement("div"); body.className = "body"; const body = document.createElement("div"); body.className = "body";
const top = document.createElement("div"); top.className = "top"; const top = document.createElement("div"); top.className = "top";
const h = document.createElement("h2"); h.textContent = v.name; const h = document.createElement("h2"); h.textContent = v.name;
const d = document.createElement("span"); d.className = "dist"; d.textContent = dist(v.distance); const d = document.createElement("span"); d.className = "dist"; d.textContent = walk(v.walk);
top.append(h, d); top.append(h, d);
const m = document.createElement("div"); m.className = "meta"; m.textContent = v.address; const m = document.createElement("div"); m.className = "meta"; m.textContent = v.address;
const desc = document.createElement("p"); desc.className = "desc" + (v.description ? "" : " empty"); const desc = document.createElement("p"); desc.className = "desc" + (v.description ? "" : " empty");

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -2,17 +2,18 @@ import http from "node:http";
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { buildList, findAddress } from "./lib.js"; import { buildList, findAddress, nearVenues } from "./lib.js";
import { createStore, checkPassword } from "./admin.js"; import { createStore, checkPassword } from "./admin.js";
import { walkRoutes } from "./route.js";
import { renderPage } from "./page.js"; import { renderPage } from "./page.js";
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), ".."); const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
const types = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" }; const types = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" };
// dataDir — где лежит живая база (по умолчанию data/ рядом с кодом), password — пароль владельца базы. // dataDir — где лежит живая база (по умолчанию data/ рядом с кодом), password — пароль владельца базы.
export function createHandler({ dataDir = path.join(root, "data"), seedDir = path.join(root, "data"), password = "" } = {}) { export function createHandler({ dataDir = path.join(root, "data"), seedDir = path.join(root, "data"), password = "", route = {} } = {}) {
const store = createStore(dataDir, seedDir); const store = createStore(dataDir, seedDir);
return (req, res) => handle(req, res, store, password); return (req, res) => handle(req, res, store, password, route);
} }
const defaultHandler = () => createHandler({ const defaultHandler = () => createHandler({
@ -48,7 +49,7 @@ function admin(req, res, url, store, password, json) {
return json(404, { error: "not_found" }); return json(404, { error: "not_found" });
} }
function handle(req, res, store, password) { function handle(req, res, store, password, route) {
const db = store.db; const db = store.db;
const url = new URL(req.url, "http://x"); const url = new URL(req.url, "http://x");
const json = (code, body) => { res.writeHead(code, { "content-type": "application/json" }); res.end(JSON.stringify(body)); }; const json = (code, body) => { res.writeHead(code, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
@ -64,9 +65,11 @@ function handle(req, res, store, password) {
const lat = Number(url.searchParams.get("lat")), lng = Number(url.searchParams.get("lng")); const lat = Number(url.searchParams.get("lat")), lng = Number(url.searchParams.get("lng"));
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return json(400, { error: "bad_coords" }); if (!Number.isFinite(lat) || !Number.isFinite(lng)) return json(400, { error: "bad_coords" });
const num = (k, allowed) => { const n = Number(url.searchParams.get(k)); return allowed.includes(n) ? n : null; }; const num = (k, allowed) => { const n = Number(url.searchParams.get(k)); return allowed.includes(n) ? n : null; };
return json(200, buildList(db.venues, lat, lng, { const opts = { only: url.searchParams.get("only") === "1", maxKm: num("maxKm", [1, 2, 5]), maxPrice: num("maxPrice", [2000, 3000, 4000]) };
only: url.searchParams.get("only") === "1", maxKm: num("maxKm", [1, 2, 5]), maxPrice: num("maxPrice", [2000, 3000, 4000]), walkRoutes(lat, lng, nearVenues(db.venues, lat, lng), route).then(
})); (routes) => json(200, buildList(db.venues, lat, lng, { ...opts, routes })),
() => json(200, buildList(db.venues, lat, lng, opts)));
return;
} }
const rel = url.pathname === "/" ? "index.html" : url.pathname === "/base" ? "base.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)); const file = path.normalize(path.join(root, "public", rel));

View File

@ -1,3 +1,5 @@
import { approxWalk } from "./route.js";
export const MAX_KM = 5; export const MAX_KM = 5;
const TZ_OFFSET_H = 5; // Астана, UTC+5 const TZ_OFFSET_H = 5; // Астана, UTC+5
@ -45,7 +47,10 @@ export function activePromo(v, t) {
return v.promo && !isStale(v, t) && (!v.promo.until || v.promo.until >= t.date) ? { text: v.promo.text, until: v.promo.until } : null; return v.promo && !isStale(v, t) && (!v.promo.until || v.promo.until >= t.date) ? { text: v.promo.text, until: v.promo.until } : null;
} }
export function buildList(venues, lat, lng, { only = false, maxKm = null, maxPrice = null, now = new Date() } = {}) { // заведения в радиусе покрытия — для них просим маршрут
export const nearVenues = (venues, lat, lng) => venues.filter((v) => distanceM(lat, lng, v.lat, v.lng) <= MAX_KM * 1000);
export function buildList(venues, lat, lng, { only = false, maxKm = null, maxPrice = null, now = new Date(), routes = new Map() } = {}) {
const t = astanaTime(now); const t = astanaTime(now);
let list = venues.map((v) => ({ let list = venues.map((v) => ({
id: v.id, name: v.name, address: v.address, id: v.id, name: v.name, address: v.address,
@ -56,11 +61,13 @@ export function buildList(venues, lat, lng, { only = false, maxKm = null, maxPri
})); }));
if (!list.some((v) => v.distance <= MAX_KM * 1000)) return []; if (!list.some((v) => v.distance <= MAX_KM * 1000)) return [];
list = list.filter((v) => v.distance <= MAX_KM * 1000); list = list.filter((v) => v.distance <= MAX_KM * 1000);
// пеший маршрут: настоящий, если посчитали, иначе по прямой с пометкой approx
for (const v of list) { v.walk = routes.get(v.id) || approxWalk(v.distance); }
if (only) list = list.filter((v) => v.lunch || v.promo); if (only) list = list.filter((v) => v.lunch || v.promo);
if (maxKm) list = list.filter((v) => v.distance <= maxKm * 1000); if (maxKm) list = list.filter((v) => v.distance <= maxKm * 1000);
// цена ланча: остаются только места с действующим ланчем не дороже порога // цена ланча: остаются только места с действующим ланчем не дороже порога
if (maxPrice) list = list.filter((v) => v.lunch && v.lunch.price <= maxPrice); if (maxPrice) list = list.filter((v) => v.lunch && v.lunch.price <= maxPrice);
return list.sort((a, b) => a.distance - b.distance); return list.sort((a, b) => a.walk.min - b.walk.min || a.walk.m - b.walk.m);
} }
export function findAddress(venues, q) { export function findAddress(venues, q) {

26
src/route.js Normal file
View File

@ -0,0 +1,26 @@
// Пеший маршрут от пользователя до заведений (DIK-45).
// Источник — OSRM (профиль «пешком»), адрес меняется переменной ROUTE_URL. Один запрос на весь список.
// Не вышло (сеть, тайм-аут, нет пути) — вызывающий код считает по прямой и пишет «примерно».
export const WALK_M_PER_MIN = 80; // ~4,8 км/ч — для расчёта по прямой
const DEFAULT_URL = "https://routing.openstreetmap.de/routed-foot";
export const approxWalk = (straightM) => ({ m: straightM, min: Math.max(1, Math.round(straightM / WALK_M_PER_MIN)), approx: true });
// → Map<id, {m, min, approx:false}>; заведения без маршрута в Map нет
export async function walkRoutes(lat, lng, venues, { fetchFn = fetch, baseUrl = process.env.ROUTE_URL || DEFAULT_URL, timeoutMs = 4000 } = {}) {
const out = new Map();
if (!venues.length || baseUrl === "off") return out;
try {
const pts = [[lng, lat], ...venues.map((v) => [v.lng, v.lat])].map((p) => p.join(",")).join(";");
const r = await fetchFn(`${baseUrl}/table/v1/foot/${pts}?sources=0&annotations=distance,duration`, { signal: AbortSignal.timeout(timeoutMs) });
if (!r.ok) return out;
const j = await r.json();
if (j.code !== "Ok") return out;
const dist = j.distances?.[0], dur = j.durations?.[0];
venues.forEach((v, i) => {
const m = dist?.[i + 1], s = dur?.[i + 1];
if (Number.isFinite(m) && Number.isFinite(s)) out.set(v.id, { m: Math.round(m), min: Math.max(1, Math.round(s / 60)), approx: false });
});
} catch { /* маршрут не посчитан — будет «примерно» */ }
return out;
}