From 03953110566cb8bf03ed01d9895acbeea2b0a489 Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 4 Dec 2026 06:02:57 +1000 Subject: [PATCH] Page norm matches and finish finder release --- docs/PLAN_2026-12-04_norm_finder_v2.md | 7 ++++++ main.py | 14 +++++++----- norm_finder.py | 20 +++++++++++------ static/changelog.json | 16 +++++++------- static/norm-finder.html | 3 ++- static/norm-finder.js | 27 +++++++++++++++++------ tests/test_norm_finder.py | 23 +++++++++++++++++++- tests/test_norm_finder_ui.py | 30 ++++++++++++++++++++++++++ 8 files changed, 111 insertions(+), 29 deletions(-) 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 @@
- +