DIK-26: понятная цена и акция в карточке и на странице «Вся база»
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
af3506358d
commit
bd82861858
@ -1,11 +1,11 @@
|
|||||||
## 1. Логика
|
## 1. Логика
|
||||||
- [ ] 1.1 `buildList`: поля `price`, `promoState`, `lunchHours`; `unconfirmed` = цена не подтверждена
|
- [x] 1.1 `buildList`: поля `price`, `promoState`, `lunchHours`; `unconfirmed` = цена не подтверждена
|
||||||
- [ ] 1.2 Тесты сценариев в `test/fresh.test.js`, поправить `server.test.js`
|
- [x] 1.2 Тесты сценариев в `test/fresh.test.js`, поправить `server.test.js`
|
||||||
|
|
||||||
## 2. Экран
|
## 2. Экран
|
||||||
- [ ] 2.1 `public/app.js`: строка цены и строка акции всегда; `fmt` без `undefined`
|
- [x] 2.1 `public/app.js`: строка цены и строка акции всегда; `fmt` без `undefined`
|
||||||
- [ ] 2.2 `public/base.js`: закончившаяся акция, нет даты проверки, нет источника
|
- [x] 2.2 `public/base.js`: закончившаяся акция, нет даты проверки, нет источника
|
||||||
- [ ] 2.3 Тексты ru/kk/en, проверка ключей в `client.test.js`
|
- [x] 2.3 Тексты ru/kk/en, проверка ключей в `client.test.js`
|
||||||
|
|
||||||
## 3. Завершение
|
## 3. Завершение
|
||||||
- [ ] 3.1 Проверки (lint/test/build), просмотр экрана, сверка текстов со словарём
|
- [ ] 3.1 Проверки (lint/test/build), просмотр экрана, сверка текстов со словарём
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
let t = {}, pos = null, lastMsg = null, lastNote = null;
|
let t = {}, pos = null, lastMsg = null, lastNote = null;
|
||||||
const $ = (id) => document.getElementById(id);
|
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] ?? ""); // без undefined на экране
|
||||||
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 walk = (w) => fmt(w.approx ? t.walkApprox : t.walkExact, { dist: dist(w.m), min: w.min });
|
||||||
@ -76,13 +76,12 @@ async function show() {
|
|||||||
desc.textContent = v.description || t.noDescription;
|
desc.textContent = v.description || t.noDescription;
|
||||||
body.append(top, m, desc);
|
body.append(top, m, desc);
|
||||||
c.append(photo(v), body);
|
c.append(photo(v), body);
|
||||||
|
// Цена и акция: действующие — плашкой, иначе понятной фразой, а не пустым местом (DIK-26)
|
||||||
if (v.lunch) body.append(tag(fmt(t.lunch, { price: v.lunch.price, from: v.lunch.from, to: v.lunch.to }), "lunch"));
|
if (v.lunch) body.append(tag(fmt(t.lunch, { price: v.lunch.price, from: v.lunch.from, to: v.lunch.to }), "lunch"));
|
||||||
|
else body.append(meta(v.lunchHours ? fmt(t.lunchLater, v.lunchHours) : t.notConfirmed, "offer-none"));
|
||||||
if (v.promo) body.append(tag(fmt(v.promo.until ? t.promo : t.promoOpen, { text: ptext(v.promo.text), until: v.promo.until && ruDate(v.promo.until) }), "promo"));
|
if (v.promo) body.append(tag(fmt(v.promo.until ? t.promo : t.promoOpen, { text: ptext(v.promo.text), until: v.promo.until && ruDate(v.promo.until) }), "promo"));
|
||||||
if ((v.lunch || v.promo) && v.checked) {
|
else body.append(meta(v.promoState === "ended" ? t.promoEnded : t.promoNone, "offer-none"));
|
||||||
const n = document.createElement("div"); n.className = "meta"; n.textContent = fmt(t.checkedOn, { date: ruDate(v.checked) }); body.append(n);
|
if ((v.lunch || v.promo) && v.checked) body.append(meta(fmt(t.checkedOn, { date: ruDate(v.checked) })));
|
||||||
} else if (v.unconfirmed) {
|
|
||||||
const n = document.createElement("div"); n.className = "meta"; n.textContent = t.notConfirmed; body.append(n);
|
|
||||||
}
|
|
||||||
out.append(c);
|
out.append(c);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -95,6 +94,7 @@ function photo(v) {
|
|||||||
img.onerror = () => { img.remove(); stub(); };
|
img.onerror = () => { img.remove(); stub(); };
|
||||||
box.append(img); return box;
|
box.append(img); return box;
|
||||||
}
|
}
|
||||||
|
function meta(s, cls) { const d = document.createElement("div"); d.className = "meta" + (cls ? " " + cls : ""); d.textContent = s; return d; }
|
||||||
function tag(s, cls) { const d = document.createElement("span"); d.className = "badge " + cls; d.textContent = s; return d; }
|
function tag(s, cls) { const d = document.createElement("span"); d.className = "badge " + cls; d.textContent = s; return d; }
|
||||||
|
|
||||||
// Места нет: объясняем причину, даём ввести адрес и показываем весь список
|
// Места нет: объясняем причину, даём ввести адрес и показываем весь список
|
||||||
|
|||||||
@ -2,8 +2,9 @@ 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; } };
|
||||||
const lang = LANGS.includes(saved()) ? saved() : "ru";
|
const lang = LANGS.includes(saved()) ? saved() : "ru";
|
||||||
const t = await (await fetch(`i18n/${lang}.json`)).json();
|
const t = await (await fetch(`i18n/${lang}.json`)).json();
|
||||||
const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k]);
|
const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k] ?? ""); // без undefined на экране
|
||||||
const date = (iso) => (iso ? iso.split("-").reverse().join(".") : "");
|
const date = (iso) => (iso ? iso.split("-").reverse().join(".") : "");
|
||||||
|
const today = new Date(Date.now() + 5 * 3600000).toISOString().slice(0, 10); // Астана UTC+5
|
||||||
document.documentElement.lang = lang;
|
document.documentElement.lang = lang;
|
||||||
document.title = t.baseTitle;
|
document.title = t.baseTitle;
|
||||||
document.querySelectorAll("[data-i]").forEach((e) => (e.textContent = t[e.dataset.i]));
|
document.querySelectorAll("[data-i]").forEach((e) => (e.textContent = t[e.dataset.i]));
|
||||||
@ -44,8 +45,8 @@ function valueCell(text, src, web) {
|
|||||||
const d = document.createElement("div"); d.className = "srcnote";
|
const d = document.createElement("div"); d.className = "srcnote";
|
||||||
d.append(t.srcLabel + " ");
|
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); }
|
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);
|
else d.append(src.name || t.baseNoSource);
|
||||||
d.append(", " + fmt(t.checkedOn, { date: src.date }).toLowerCase());
|
d.append(", " + (src.date ? fmt(t.checkedOn, { date: src.date }).toLowerCase() : t.baseNotChecked)); // без пустых значений (DIK-26)
|
||||||
td.append(d);
|
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); }
|
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;
|
return td;
|
||||||
@ -58,7 +59,10 @@ try {
|
|||||||
const body = document.getElementById("rows");
|
const body = document.getElementById("rows");
|
||||||
if (!list.length) { const e = document.getElementById("err"); e.textContent = t.listPreparing; e.hidden = false; }
|
if (!list.length) { const e = document.getElementById("err"); e.textContent = t.listPreparing; e.hidden = false; }
|
||||||
for (const v of list) {
|
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 ptext = v.promo && (t.promoTexts?.[v.promo.text] || v.promo.text);
|
||||||
|
// акция с прошедшим сроком не выглядит действующей; пустых ячеек нет (DIK-26)
|
||||||
|
const promo = !v.promo ? t.noPromo : 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 ? fmt(t.baseLunch, v.lunch) : t.noLunch;
|
const lunch = v.lunch ? fmt(t.baseLunch, v.lunch) : t.noLunch;
|
||||||
const tr = document.createElement("tr");
|
const tr = document.createElement("tr");
|
||||||
const src = sources(v);
|
const src = sources(v);
|
||||||
@ -66,11 +70,11 @@ try {
|
|||||||
const td = document.createElement("td"); td.textContent = s; tr.append(td);
|
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));
|
tr.append(valueCell(lunch, src.lunch, v.web), valueCell(promo, src.promo, v.web));
|
||||||
{ const td = document.createElement("td"); td.textContent = date(v.checked); tr.append(td); }
|
{ 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));
|
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");
|
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; srcTd.append(a); }
|
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 || "";
|
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"];
|
const web = document.createElement("div"); web.className = "web"; web.textContent = t[v.web === "обновлено" ? "webUpdated" : v.web === "нет данных" ? "webNone" : "webNot"];
|
||||||
srcTd.append(web);
|
srcTd.append(web);
|
||||||
tr.append(srcTd);
|
tr.append(srcTd);
|
||||||
|
|||||||
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
11
src/lib.js
11
src/lib.js
@ -47,6 +47,15 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Что писать в карточке вместо пустого места (DIK-26):
|
||||||
|
// price active|later|unconfirmed, promoState active|ended|none; unconfirmed = цена не подтверждена
|
||||||
|
export function offerState(v, t) {
|
||||||
|
const stale = isStale(v, t);
|
||||||
|
const price = activeLunch(v, t) ? "active" : v.lunch && !stale ? "later" : "unconfirmed";
|
||||||
|
const promoState = activePromo(v, t) ? "active" : v.promo && v.promo.until && v.promo.until < t.date ? "ended" : "none";
|
||||||
|
return { price, promoState, unconfirmed: price === "unconfirmed", lunchHours: price === "later" ? { from: v.lunch.from, to: v.lunch.to } : null };
|
||||||
|
}
|
||||||
|
|
||||||
// заведения в радиусе покрытия — для них просим маршрут
|
// заведения в радиусе покрытия — для них просим маршрут
|
||||||
export const nearVenues = (venues, lat, lng) => venues.filter((v) => distanceM(lat, lng, v.lat, v.lng) <= MAX_KM * 1000);
|
export const nearVenues = (venues, lat, lng) => venues.filter((v) => distanceM(lat, lng, v.lat, v.lng) <= MAX_KM * 1000);
|
||||||
|
|
||||||
@ -58,7 +67,7 @@ export function buildList(venues, lat, lng, { only = false, maxKm = null, maxPri
|
|||||||
distance: noPlace ? null : distanceM(lat, lng, v.lat, v.lng),
|
distance: noPlace ? null : distanceM(lat, lng, v.lat, v.lng),
|
||||||
lunch: activeLunch(v, t), promo: activePromo(v, t), checked: v.checked || null,
|
lunch: activeLunch(v, t), promo: activePromo(v, t), checked: v.checked || null,
|
||||||
photo: v.photo || null, description: v.description || null,
|
photo: v.photo || null, description: v.description || null,
|
||||||
unconfirmed: isStale(v, t) || !v.lunch && !v.promo,
|
...offerState(v, t),
|
||||||
}));
|
}));
|
||||||
if (!noPlace) {
|
if (!noPlace) {
|
||||||
if (!list.some((v) => v.distance <= MAX_KM * 1000)) return [];
|
if (!list.some((v) => v.distance <= MAX_KM * 1000)) return [];
|
||||||
|
|||||||
@ -108,3 +108,18 @@ test("Сценарий: кнопка ☰ подписана словом «Ме
|
|||||||
assert.match(html, /<button id="burger"[^>]*>.*<span data-i="menuLabel">Меню<\/span><\/button>/);
|
assert.match(html, /<button id="burger"[^>]*>.*<span data-i="menuLabel">Меню<\/span><\/button>/);
|
||||||
assert.match(html, /<nav id="menu"[^>]*>\s*<h2 data-i="menuLabel">Меню<\/h2>/);
|
assert.match(html, /<nav id="menu"[^>]*>\s*<h2 data-i="menuLabel">Меню<\/h2>/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("Сценарий: вместо пустого места — «Цена не подтверждена», «Акции сейчас нет», «Акция закончилась» на трёх языках (DIK-26)", () => {
|
||||||
|
const base = fs.readFileSync("public/base.js", "utf8");
|
||||||
|
for (const k of ["notConfirmed", "lunchLater", "promoNone", "promoEnded"]) assert.match(app, new RegExp(`t\\.${k}\\b`), k);
|
||||||
|
for (const k of ["basePromoEnded", "baseNotChecked", "baseNoSource"]) assert.match(base, new RegExp(`t\\.${k}\\b`), k);
|
||||||
|
// подстановка не выводит undefined/null
|
||||||
|
for (const src of [app, base]) assert.match(src, /o\[k\] \?\? ""/);
|
||||||
|
for (const l of ["ru", "kk", "en"]) {
|
||||||
|
const d = JSON.parse(fs.readFileSync(`public/i18n/${l}.json`, "utf8"));
|
||||||
|
for (const k of ["notConfirmed", "lunchLater", "promoNone", "promoEnded", "basePromoEnded", "baseNotChecked", "baseNoSource"]) {
|
||||||
|
assert.ok(d[k], `${l}.${k}`);
|
||||||
|
assert.doesNotMatch(d[k], /null|undefined/i, `${l}.${k}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
@ -152,3 +152,34 @@ test("описание и фото владельца проверяются (DI
|
|||||||
assert.equal(store.update(id, { description: "я".repeat(301) }).error, "bad_description");
|
assert.equal(store.update(id, { description: "я".repeat(301) }).error, "bad_description");
|
||||||
assert.equal(store.update(id, { photo: "javascript:alert(1)" }).error, "bad_photo");
|
assert.equal(store.update(id, { photo: "javascript:alert(1)" }).error, "bad_photo");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("Сценарий: ланч вечером или в выходной — «в другое время» с часами (DIK-26)", () => {
|
||||||
|
const v = buildList([venue({ checked: "2026-11-20" })], 51.1283, 71.4305, { now: new Date("2026-11-21T08:00:00Z") })[0]; // суббота 13:00
|
||||||
|
assert.equal(v.lunch, null);
|
||||||
|
assert.equal(v.price, "later");
|
||||||
|
assert.deepEqual(v.lunchHours, { from: "12:00", to: "15:00" });
|
||||||
|
assert.equal(v.unconfirmed, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Сценарий: нет данных о цене — «Цена не подтверждена», акция показана (DIK-26)", () => {
|
||||||
|
const v = one(venue({ lunch: null, promo: { text: "Кофе в подарок", until: null } }));
|
||||||
|
assert.equal(v.price, "unconfirmed"); assert.equal(v.unconfirmed, true);
|
||||||
|
assert.equal(v.promoState, "active"); assert.equal(v.promo.text, "Кофе в подарок");
|
||||||
|
assert.equal(v.lunchHours, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Сценарий: давние данные — цена не подтверждена, акции сейчас нет (DIK-26)", () => {
|
||||||
|
const v = one(venue({ checked: "2026-11-01" }));
|
||||||
|
assert.equal(v.price, "unconfirmed"); assert.equal(v.promoState, "none"); assert.equal(v.promo, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Сценарий: акция закончилась — не показана как действующая (DIK-26)", () => {
|
||||||
|
const v = one(venue({ promo: { text: "Кофе", until: "2026-11-17" } }));
|
||||||
|
assert.equal(v.promo, null); assert.equal(v.promoState, "ended");
|
||||||
|
assert.equal(one(venue({ promo: { text: "Кофе", until: "2026-11-01" }, checked: "2026-11-01" })).promoState, "ended");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Сценарий: акции нет — «Акции сейчас нет», без пустых значений (DIK-26)", () => {
|
||||||
|
const v = one(venue({ promo: null }));
|
||||||
|
assert.equal(v.promoState, "none"); assert.equal(v.price, "active");
|
||||||
|
});
|
||||||
|
|||||||
@ -114,7 +114,9 @@ test("Сценарий: список от выбранного места — п
|
|||||||
assert.ok(all.length > 0);
|
assert.ok(all.length > 0);
|
||||||
for (const v of all) {
|
for (const v of all) {
|
||||||
if (v.promo && v.promo.until) assert.ok(v.promo.until >= today, v.name);
|
if (v.promo && v.promo.until) assert.ok(v.promo.until >= today, v.name);
|
||||||
if (v.unconfirmed) assert.ok(!v.lunch && !v.promo, v.name);
|
if (v.unconfirmed) assert.ok(!v.lunch, v.name);
|
||||||
|
assert.ok(["active", "later", "unconfirmed"].includes(v.price) && ["active", "ended", "none"].includes(v.promoState), v.name);
|
||||||
|
if (v.promoState !== "active") assert.equal(v.promo, null, v.name);
|
||||||
}
|
}
|
||||||
assert.ok(only.length <= all.length && only.every((v) => v.lunch || v.promo));
|
assert.ok(only.length <= all.length && only.every((v) => v.lunch || v.promo));
|
||||||
assert.deepEqual(far, []);
|
assert.deepEqual(far, []);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user