dika/src/lib.js
Peppa fb2d6c473c
All checks were successful
peppa/lint lint: success за 1с
peppa/test test: success за 0с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 5s
deploy / deploy (pull_request) Successful in 13s
DIK-44: районы убраны из продукта, без места показывается весь список
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 15:34:26 +05:00

82 lines
4.1 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.

import { approxWalk } from "./route.js";
export const MAX_KM = 5;
const TZ_OFFSET_H = 5; // Астана, UTC+5
export function distanceM(aLat, aLng, bLat, bLng) {
const R = 6371000, rad = (d) => (d * Math.PI) / 180;
const dLat = rad(bLat - aLat), dLng = rad(bLng - aLng);
const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(aLat)) * Math.cos(rad(bLat)) * Math.sin(dLng / 2) ** 2;
return Math.round(2 * R * Math.asin(Math.sqrt(h)));
}
// now → { day: 1..7 (пн..вс), minutes, date: YYYY-MM-DD } по времени Астаны
export function astanaTime(now = new Date()) {
const t = new Date(now.getTime() + TZ_OFFSET_H * 3600000);
return { day: t.getUTCDay() || 7, minutes: t.getUTCHours() * 60 + t.getUTCMinutes(), date: t.toISOString().slice(0, 10) };
}
const toMin = (s) => { const [h, m] = s.split(":").map(Number); return h * 60 + m; };
export const MAX_AGE_DAYS = 14;
const dayNum = (iso) => Math.floor(new Date(iso + "T00:00:00Z").getTime() / 86400000);
// Данные заведения проверяли больше MAX_AGE_DAYS дней назад? Нет даты — не считаем устаревшими.
export function isStale(v, t) {
return Boolean(v.checked) && dayNum(t.date) - dayNum(v.checked) > MAX_AGE_DAYS;
}
// Что сейчас с записями заведения (для владельца): ланч none|active|stale, акция none|active|expired|stale
export function offerStatus(v, t) {
const stale = isStale(v, t);
return {
lunch: !v.lunch ? "none" : stale ? "stale" : "active",
promo: !v.promo ? "none" : v.promo.until && v.promo.until < t.date ? "expired" : stale ? "stale" : "active",
};
}
export function activeLunch(v, t) {
const l = v.lunch;
if (!l || isStale(v, t) || !l.days.includes(t.day)) return null;
if (t.minutes < toMin(l.from) || t.minutes >= toMin(l.to)) return null;
return { price: l.price, from: l.from, to: l.to };
}
export function activePromo(v, t) {
// 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 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 noPlace = lat == null || lng == null; // места нет — весь список, без расстояний и маршрутов
let list = venues.map((v) => ({
id: v.id, name: v.name, address: v.address,
distance: noPlace ? null : distanceM(lat, lng, v.lat, v.lng),
lunch: activeLunch(v, t), promo: activePromo(v, t), checked: v.checked || null,
photo: v.photo || null, description: v.description || null,
unconfirmed: isStale(v, t) || !v.lunch && !v.promo,
}));
if (!noPlace) {
if (!list.some((v) => v.distance <= MAX_KM * 1000)) return [];
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 (maxKm && !noPlace) list = list.filter((v) => v.distance <= maxKm * 1000);
// цена ланча: остаются только места с действующим ланчем не дороже порога
if (maxPrice) list = list.filter((v) => v.lunch && v.lunch.price <= maxPrice);
if (noPlace) return list.sort((a, b) => a.name.localeCompare(b.name, "ru"));
return list.sort((a, b) => a.walk.min - b.walk.min || a.walk.m - b.walk.m);
}
export function findAddress(venues, q) {
const s = q.trim().toLowerCase();
if (s.length < 3) return null;
return venues.find((v) => v.address.toLowerCase().includes(s)) || null;
}