diff --git a/docs/PLAN_2026-12-04_norm_finder_v2.md b/docs/PLAN_2026-12-04_norm_finder_v2.md index f2cbede..60e3c17 100644 --- a/docs/PLAN_2026-12-04_norm_finder_v2.md +++ b/docs/PLAN_2026-12-04_norm_finder_v2.md @@ -102,6 +102,13 @@ - Поиск и детали норм доступны гостю через отдельные read-only маршруты с лимитом 8 результатов и 30 запросов в минуту с одного IP. Цены, сохранение подборки и расчёт остаются авторизованными. Гостевой путь проверен в Chromium. +- Результаты выдаются устойчивыми страницами из одинакового окна кандидатов; + кнопка «Показать ещё нормы» добавляет следующую страницу, не сбрасывая первую. + Доступно до 60 кандидатов на запрос; это ограничение явно задано в API. + +После добавления страниц эталон на реальном индексе сохранил 5/5 точных +шифров и 24/25 словесных запросов в top-5; p95 — 1,087 с. Целевые API и +браузерные проверки: 30 зелёных, отдельная проверка страницы выдачи — 4 зелёных. До выпуска: полный проектный гейт, визуальная сверка на реальной ФСНБ и ценовой форме, ревью безопасности/UX, синхронизация с последним `main` и дев-стенд 8106. diff --git a/main.py b/main.py index af3761b..bb33825 100644 --- a/main.py +++ b/main.py @@ -555,7 +555,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-12-04a" +APP_VERSION = "2026-12-04b" # Audit: path → action name mapping _AUDIT_MAP = [ @@ -2451,13 +2451,15 @@ async def public_norm_finder_catalog(request: Request): @app.get("/api/public/norm-finder/search") -async def public_norm_finder_search(request: Request, q: str = "", base: str = "2022", limit: int = 8): +async def public_norm_finder_search(request: Request, q: str = "", base: str = "2022", limit: int = 8, + offset: int = 0): _check_public_finder_rate(request) if not 1 <= limit <= 8: raise HTTPException(400, "Публичный поиск показывает до 8 результатов") import norm_finder try: - found = await asyncio.to_thread(norm_finder.search, q, base, limit) + found = await asyncio.to_thread(norm_finder.search, q, base, limit, offset) if offset else \ + await asyncio.to_thread(norm_finder.search, q, base, limit) except ValueError as exc: raise HTTPException(400, str(exc)) from exc if found.get("status") == "db_unavailable": @@ -2477,11 +2479,13 @@ async def public_norm_finder_detail(request: Request, base: str = "", base_type: @app.get("/api/norm-finder/search") -async def norm_finder_search(request: Request, q: str = "", base: str = "2022", limit: int = 12): +async def norm_finder_search(request: Request, q: str = "", base: str = "2022", limit: int = 12, + offset: int = 0): _get_user(request) import norm_finder try: - found = await asyncio.to_thread(norm_finder.search, q, base, limit) + found = await asyncio.to_thread(norm_finder.search, q, base, limit, offset) if offset else \ + await asyncio.to_thread(norm_finder.search, q, base, limit) except ValueError as exc: raise HTTPException(400, str(exc)) from exc if found.get("status") == "db_unavailable": diff --git a/norm_finder.py b/norm_finder.py index 7b00aed..5dd9aa2 100644 --- a/norm_finder.py +++ b/norm_finder.py @@ -85,17 +85,20 @@ def catalog() -> list[dict]: con.close() -def search(query: str, base: str, limit: int = 12) -> dict: +def search(query: str, base: str, limit: int = 12, offset: int = 0) -> dict: query = query.strip() if isinstance(query, str) else "" - if not 2 <= len(query) <= 160 or base not in BASES or not isinstance(limit, int) or not 1 <= limit <= 30: + if (not 2 <= len(query) <= 160 or base not in BASES or not isinstance(limit, int) + or not 1 <= limit <= 30 or not isinstance(offset, int) or isinstance(offset, bool) + or not 0 <= offset < 60 or offset + limit > 60): raise ValueError("Укажите запрос 2–160 символов, доступную базу и число результатов до 30") interpreted = _interpreted_query(query) exact_code = fsnb_ref._extract_code(query) is not None terms = _search_terms(interpreted) - result = fsnb_ref.find_works(query=query, base=base, limit=limit if len(terms) < 2 else max(60, limit * 5)) + # Fixed candidate window keeps page boundaries stable across repeated requests. + result = fsnb_ref.find_works(query=query, base=base, limit=60 if len(terms) >= 2 else max(60, limit)) candidates = list(result.get("works") or []) if not exact_code and interpreted != query: - corrected = fsnb_ref.find_works(query=interpreted, base=base, limit=max(60, limit * 5)) + corrected = fsnb_ref.find_works(query=interpreted, base=base, limit=60) candidates.extend(corrected.get("works") or []) if not exact_code and (len(terms) >= 2 or not candidates): counts = [(fsnb_ref.count_works(term), -index, term) @@ -104,14 +107,15 @@ def search(query: str, base: str, limit: int = 12) -> dict: if usable: anchor = min(usable)[2] if anchor != interpreted: - fallback = fsnb_ref.find_works(query=anchor, base=base, limit=max(80, limit * 8)) + fallback = fsnb_ref.find_works(query=anchor, base=base, limit=80) candidates.extend(fallback.get("works") or []) if candidates: unique = {} for row in candidates: unique.setdefault((row.get("base"), row.get("base_type"), row.get("code")), row) ranked = sorted(unique.values(), key=lambda row: _search_rank(row, terms)) - candidates = _diverse_families(ranked, limit) if not exact_code else ranked[:limit] + ordered = _diverse_families(ranked, 60) if not exact_code else ranked[:60] + candidates = ordered[offset:offset + limit] items = [] for original in candidates: row = dict(original) @@ -126,7 +130,9 @@ def search(query: str, base: str, limit: int = 12) -> dict: if matched else "Похожее название — проверьте состав") items.append(row) return {"status": "ok", "items": items, - "shown": len(items), "query": query, "interpreted_query": interpreted, + "shown": len(items), "offset": offset, + "has_more": offset + limit < len(ordered), + "query": query, "interpreted_query": interpreted, "base": BASES[base]} return {"status": result.get("status") or "unavailable", "items": [], "message": result.get("message") or "Поиск не выполнен", "query": query, diff --git a/static/changelog.json b/static/changelog.json index a117de7..c9af8e8 100644 --- a/static/changelog.json +++ b/static/changelog.json @@ -1,4 +1,12 @@ [ + { + "version": "2026-12-04b", + "date": "2026-12-04", + "changes": [ + "Подбор норм открыт без входа: поиск по работе и шифру, варианты таблиц и сравнение состава", + "Несколько норм можно сохранить в подборку и пересчитать по зоне и кварталу; неполные цены отмечаются отдельно" + ] + }, { "version": "2026-12-04a", "date": "2026-12-04", @@ -26,13 +34,5 @@ "changes": [ "После локальной сметы ассистент задаёт вопрос об отдельном расчёте дополнительных затрат, даже если исходных данных не хватило для полного итога" ] - }, - { - "version": "2026-12-02b", - "date": "2026-12-02", - "changes": [ - "Локальная смета больше не начисляет зимние и временные затраты, резерв и НДС без отдельного расчёта", - "Последние обновления нормативного корпуса на главной сгруппированы по источнику и дате" - ] } ] diff --git a/static/norm-finder.html b/static/norm-finder.html index 0bfaa6f..d005389 100644 --- a/static/norm-finder.html +++ b/static/norm-finder.html @@ -92,7 +92,8 @@
-Объём вводится в выбранной единице. Недостающие цены и затраты будут отмечены.
diff --git a/static/norm-finder.js b/static/norm-finder.js index ee29e3d..195054c 100644 --- a/static/norm-finder.js +++ b/static/norm-finder.js @@ -18,6 +18,7 @@ let active = null; let savedQuote = null; let draft = null; + let searchPage = null; let subjects = []; let priceZones = []; const compared = new Map(); @@ -151,23 +152,34 @@ actions.append(open, compare, variants); card.append(actions, variantList); return card; } - async function search(event) { + async function search(event, nextPage=false) { event?.preventDefault(); - const q = $('query').value.trim(), base = $('base').value; + const q = nextPage ? searchPage?.q : $('query').value.trim(); + const base = nextPage ? searchPage?.base : $('base').value; + const offset = nextPage ? searchPage?.offset || 0 : 0; if (q.length < 2) { status('Введите хотя бы два символа', true); return; } status('Ищу нормы…'); - $('results-section').hidden = true; $('detail-section').hidden = true; + if (!nextPage) { + searchPage = null; + $('results-section').hidden = true; $('detail-section').hidden = true; + $('more-results').hidden = true; + } + $('more-results').disabled = true; try { const data = await api(readPath('search') + '?' + - new URLSearchParams({q,base,limit:publicMode ? '8' : '12'})); + new URLSearchParams({q,base,limit:publicMode ? '8' : '12',offset:String(offset)})); const items = data.items || []; - $('results').replaceChildren(...items.map(renderSearchItem)); - $('results-section').hidden = !items.length; + if (nextPage) $('results').append(...items.map(renderSearchItem)); + else $('results').replaceChildren(...items.map(renderSearchItem)); + $('results-section').hidden = !$('results').children.length; + searchPage = {q, base, offset:offset + items.length}; + $('more-results').hidden = !data.has_more || !items.length; const correction = data.interpreted_query && data.interpreted_query !== q ? 'Поиск по уточнённой формулировке: «' + data.interpreted_query + '». ' : ''; - status(items.length ? correction + 'Показано ' + items.length + ' подходящих норм. Проверьте состав работ перед расчётом.' + status(items.length ? correction + 'Показано ' + searchPage.offset + ' подходящих норм. Проверьте состав работ перед расчётом.' : (data.message || 'Нормы не найдены. Уточните работу или шифр.')); } catch (e) { status(e.message, true); } + finally { $('more-results').disabled = false; } } function renderDetail(item) { $('detail-title').textContent = item.code + ' — ' + (item.name || 'Норма'); @@ -438,6 +450,7 @@ } catch (e) { status(e.message, true); } } $('search-form').addEventListener('submit', search); + $('more-results').addEventListener('click', event => search(event, true)); document.querySelectorAll('[data-query]').forEach(button => button.addEventListener('click', () => { $('query').value = button.dataset.query; $('search-form').requestSubmit(); })); diff --git a/tests/test_norm_finder.py b/tests/test_norm_finder.py index 96b187f..1090144 100644 --- a/tests/test_norm_finder.py +++ b/tests/test_norm_finder.py @@ -19,7 +19,28 @@ def test_search_rejects_empty_query_and_uses_existing_fsnb(monkeypatch): found = norm_finder.search("извещатель", "2022", 12) assert found["items"][0]["code"] == "10-08-002-02" assert found["items"][0]["match_reason"].startswith("Совпали слова") - assert seen == [("извещатель", "2022", 12)] + assert seen == [("извещатель", "2022", 60)] + + +def test_search_pages_keep_the_same_ranked_window(monkeypatch): + import fsnb_ref + import norm_finder + calls = [] + def find(*, query, base, limit): + calls.append(limit) + return {"status": "ok", "works": [ + {"code": f"11-01-{i:03d}-01", "name": f"Стяжка пола {i}", + "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "100 м2"} + for i in range(20)]} + monkeypatch.setattr(fsnb_ref, "find_works", find) + monkeypatch.setattr(fsnb_ref, "count_works", lambda term: 0) + first = norm_finder.search("стяжка", "2022", 8, 0) + second = norm_finder.search("стяжка", "2022", 8, 8) + assert first["has_more"] is True + assert len({row["code"] for row in first["items"] + second["items"]}) == 16 + assert calls == [60, 60] + with pytest.raises(ValueError): + norm_finder.search("стяжка", "2022", 8, 60) def test_search_falls_back_to_subject_term_and_ranks_relevant_work(monkeypatch): diff --git a/tests/test_norm_finder_ui.py b/tests/test_norm_finder_ui.py index c94af02..4aff705 100644 --- a/tests/test_norm_finder_ui.py +++ b/tests/test_norm_finder_ui.py @@ -194,3 +194,33 @@ def test_guest_can_search_and_read_norm_but_not_see_price_controls(browser, site if screenshot_dir: page.screenshot(path=str(Path(screenshot_dir) / 'norm-finder-guest-mobile.png'), full_page=True) page.close() + + +def test_guest_can_open_next_page_without_losing_first_results(browser, site): + page = browser.new_page(viewport={"width": 390, "height": 844}) + offsets = [] + + def handle(route): + url = urlsplit(route.request.url) + if url.path.endswith("/catalog"): + data = {"bases": [{"base": "ГЭСН-2022", "count": 56192}]} + else: + from urllib.parse import parse_qs + offset = int(parse_qs(url.query).get("offset", ["0"])[0]) + offsets.append(offset) + data = {"items": [{"base": "ГЭСН-2022", "base_type": "ГЭСН", + "code": f"11-01-{offset + i:03d}-01", "name": f"Стяжка {offset + i}", + "unit": "100 м2"} for i in range(8)], "has_more": offset == 0} + route.fulfill(status=200, content_type="application/json", body=json.dumps(data, ensure_ascii=False)) + + page.route("**/api/public/norm-finder/**", handle) + page.goto(site) + page.locator('#query').fill('стяжка') + page.locator('#search-form button[type="submit"]').click() + page.locator('#results .card').nth(7).wait_for() + page.locator('#more-results').click() + page.locator('#results .card').nth(15).wait_for() + assert offsets == [0, 8] + assert page.locator('#results .card').count() == 16 + assert page.locator('#more-results').is_hidden() + page.close()