From 6520ce93573526d0d02e7be4f1220f5738dc973f Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 4 Dec 2026 15:46:19 +1000 Subject: [PATCH] Build browsable norm table with inline composition --- fsnb_ref.py | 1 + main.py | 30 +++++- norm_finder.py | 61 ++++++++++++ static/norm-finder.html | 69 +++++++++++-- static/norm-finder.js | 185 +++++++++++++++++++++++++++++------ tests/test_norm_finder.py | 50 ++++++++++ tests/test_norm_finder_ui.py | 46 ++++++++- 7 files changed, 403 insertions(+), 39 deletions(-) diff --git a/fsnb_ref.py b/fsnb_ref.py index a93a187..82d0fd0 100644 --- a/fsnb_ref.py +++ b/fsnb_ref.py @@ -152,6 +152,7 @@ def _provenance(src: dict | None) -> dict: if not src: return {} return {"decree": src["decree"], "file": src["file"], "dataset": src["dataset"], + "url": src.get("url"), "base": src["base"], "zip_sha256": src["zip_sha256"], "fetched_at": src["fetched_at"]} diff --git a/main.py b/main.py index 3dc81d6..6f83956 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-04e" +APP_VERSION = "2026-12-04f" # Audit: path → action name mapping _AUDIT_MAP = [ @@ -2452,6 +2452,34 @@ async def public_norm_finder_catalog(request: Request): return {"bases": await asyncio.to_thread(norm_finder.catalog)} +@app.get("/api/public/norm-finder/browse") +async def public_norm_finder_browse(request: Request, base: str = "2022", base_type: str = "ГЭСН", + path: str = "", limit: int = 20, offset: int = 0): + _check_public_finder_rate(request) + if limit > 20: + raise HTTPException(400, "Публичный каталог показывает до 20 норм за запрос") + import norm_finder + try: + return await asyncio.to_thread(norm_finder.browse, base, base_type, path, limit, offset) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + except RuntimeError as exc: + raise HTTPException(503, str(exc)) from exc + + +@app.get("/api/norm-finder/browse") +async def norm_finder_browse(request: Request, base: str = "2022", base_type: str = "ГЭСН", + path: str = "", limit: int = 40, offset: int = 0): + _get_user(request) + import norm_finder + try: + return await asyncio.to_thread(norm_finder.browse, base, base_type, path, limit, offset) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + except RuntimeError as exc: + raise HTTPException(503, str(exc)) from exc + + @app.get("/api/public/norm-finder/search") async def public_norm_finder_search(request: Request, q: str = "", base: str = "2022", limit: int = 8, offset: int = 0): diff --git a/norm_finder.py b/norm_finder.py index 5dd9aa2..f6a9c56 100644 --- a/norm_finder.py +++ b/norm_finder.py @@ -3,6 +3,7 @@ from __future__ import annotations import math import re +from functools import lru_cache import fsnb_ref @@ -85,6 +86,66 @@ def catalog() -> list[dict]: con.close() +@lru_cache(maxsize=32) +def _section_paths(db_key: tuple[str, int, int], base: str, base_type: str) -> tuple[str, ...]: + """Cache the section index; a rebuilt SQLite file gets a new cache key.""" + con = fsnb_ref._connect() + if con is None: + raise RuntimeError("Нормативная база недоступна") + try: + return tuple(row[0] for row in con.execute( + "SELECT DISTINCT section_path FROM works WHERE base=? AND base_type=? " + "AND section_path IS NOT NULL AND section_path != '' ORDER BY section_path", + (base, base_type))) + finally: + con.close() + + +def browse(base: str, base_type: str, path: str = "", limit: int = 40, + offset: int = 0) -> dict: + """Browse one source-backed section and a bounded page of its norms.""" + if (base not in BASES or base_type not in TYPES + or not base_type.startswith("ГЭСН" if base == "2022" else "ФЕР") + or not isinstance(path, str) or len(path) > 800 + or not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 50 + or not isinstance(offset, int) or isinstance(offset, bool) or not 0 <= offset <= 5000): + raise ValueError("Укажите существующий раздел, базу, тип и страницу до 50 норм") + db = fsnb_ref.db_path() + try: + stat = db.stat() + except OSError as exc: + raise RuntimeError("Нормативная база недоступна") from exc + paths = _section_paths((str(db), stat.st_mtime_ns, stat.st_size), BASES[base], base_type) + prefix = path + " > " if path else "" + if path and not any(p == path or p.startswith(prefix) for p in paths): + raise ValueError("Раздел не найден в выбранном сборнике") + children = sorted({p[len(prefix):].split(" > ", 1)[0] for p in paths + if p.startswith(prefix) and p != path}) + con = fsnb_ref._connect() + if con is None: + raise RuntimeError("Нормативная база недоступна") + try: + if path: + # Escape LIKE metacharacters even when they occur in a real section name. + escaped = path.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + clause = "AND (section_path=? OR section_path LIKE ? ESCAPE '\\')" + params = (BASES[base], base_type, path, escaped + " > %") + else: + clause = "" + params = (BASES[base], base_type) + rows = con.execute( + "SELECT code,name,unit,cost,price_level,section_path FROM works " + f"WHERE base=? AND base_type=? {clause} ORDER BY code,name LIMIT ? OFFSET ?", + (*params, limit + 1, offset)).fetchall() + finally: + con.close() + return {"base": BASES[base], "base_type": base_type, "path": path, + "children": [{"name": name, "path": prefix + name} for name in children], + "items": [dict(row) | {"base": BASES[base], "base_type": base_type} + for row in rows[:limit]], + "offset": offset, "has_more": len(rows) > limit} + + 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) diff --git a/static/norm-finder.html b/static/norm-finder.html index 9f4b500..a4dc4a7 100644 --- a/static/norm-finder.html +++ b/static/norm-finder.html @@ -13,7 +13,7 @@ button { cursor:pointer; } :focus-visible { outline:3px solid #65aba4; outline-offset:2px; } a { color:var(--accent); } - .wrap { max-width:1240px; margin:auto; padding:24px clamp(16px,3vw,40px) 64px; } + .wrap { max-width:1600px; margin:auto; padding:24px clamp(16px,3vw,40px) 64px; } header { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:32px; } .brand { font-weight:750; font-size:1.15rem; text-decoration:none; color:var(--text); } h1 { font-size:clamp(2rem,4vw,3rem); line-height:1.1; margin:0 0 12px; } @@ -71,23 +71,72 @@ .draft-row input { width:110px; } .quote-controls label { min-width:140px; } .quote-controls #qty { width:125px; } + .workspace { display:grid; grid-template-columns:minmax(230px,280px) minmax(0,1fr); gap:16px; align-items:start; } + .catalog-tree { max-height:72vh; overflow:auto; position:sticky; top:12px; } + .catalog-tree h2 { font-size:1.05rem; } + .tree-list { list-style:none; margin:0; padding:0 0 0 12px; border-left:1px solid var(--line); } + .tree-list button { width:100%; text-align:left; border:0; border-radius:5px; background:transparent; + padding:6px; color:var(--text); font-size:.84rem; line-height:1.3; } + .tree-list button:hover,.tree-list button[aria-current="true"] { background:#e9f4f1; color:var(--accent); } + .table-panel { min-width:0; } + .table-panel h2 { margin:0; } + .table-heading { display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:12px; } + .norm-scroll { max-width:100%; overflow-x:auto; } + .norm-table { min-width:680px; } + .norm-table th { background:#f6f7f4; position:sticky; top:0; z-index:1; } + .norm-table .norm-row:hover { background:#f8faf8; } + .norm-table .norm-row button { min-height:32px; } + .norm-table .norm-name { min-width:240px; } + .norm-table .inline-cell { padding:0; background:#f8faf8; } + .inline-content { padding:16px; border-left:3px solid var(--accent); } + .inline-content .detail-grid { grid-template-columns:minmax(0,1fr); } + .inline-content .panel { border:0; padding:12px 0; background:transparent; } + .inline-content #quote-panel { border-top:1px solid var(--line); } + .inline-actions { display:flex; align-items:center; flex-wrap:wrap; gap:6px; } + .inline-actions .secondary { min-height:32px; } + .breadcrumb { color:var(--muted); font-size:.84rem; overflow-wrap:anywhere; } + .catalog-mobile { display:none; } [hidden] { display:none !important; } @media (max-width:760px) { .wrap { padding:18px 14px 40px; } header { margin-bottom:24px; } .detail-grid,.comparison { grid-template-columns:minmax(0,1fr); } .panel,.card { padding:15px; } .search-row > *, .controls > label { flex:1 1 100%; } .search-row button { width:100%; } - .quote-controls label { min-width:0; } } + .quote-controls label { min-width:0; } .workspace { display:block; } + .catalog-mobile { display:block; margin-bottom:10px; } + .catalog-tree { position:static; max-height:45vh; margin-bottom:12px; } + .catalog-tree[hidden] { display:none !important; } + .norm-scroll { overflow:visible; } + .norm-table,.norm-table > tbody,.norm-table > tbody > .norm-detail-row, + .norm-table > tbody > .norm-detail-row > td { display:block; min-width:0; width:100%; } + .norm-table thead { display:none; } + .norm-table .norm-row { display:grid; grid-template-columns:minmax(0,1fr) auto; + gap:5px 12px; padding:13px 0; border-top:1px solid var(--line); } + .norm-table .norm-row td { border:0; padding:0; min-width:0; } + .norm-table .norm-row td:nth-child(1) { grid-column:1 / -1; } + .norm-table .norm-row td:nth-child(2) { grid-column:1 / -1; overflow-wrap:anywhere; } + .norm-table .norm-row td:nth-child(3) { grid-column:1; } + .norm-table .norm-row td:nth-child(4) { grid-column:2; } + .norm-table .norm-row td:nth-child(5) { grid-column:1 / -1; } + .norm-table .norm-row .inline-actions { gap:6px; } + .norm-table .norm-row .inline-actions button { flex:1 1 auto; } + .inline-content { padding:12px 10px; } + .inline-content #detail-title { font-size:1.05rem; overflow-wrap:anywhere; } + .inline-content .scroll { overflow-x:auto; } + .inline-content .scroll table { min-width:560px; } + .inline-content .detail-grid { display:block; } + }
ИНФОСМЕТАВернуться в чат

Подбор норм

-

Найдите работу по названию или шифру, проверьте состав и измеритель, сравните варианты. Цены считаются только по доступной форме выбранной зоны и квартала.

+

Выберите сборник и раздел или найдите норму по шифру и названию. Раскройте строку, чтобы увидеть состав работ, ресурсы и источник.

+
Примеры: @@ -95,8 +144,16 @@
- + +
+ +
+

Нормы сборника

+ +
ШифрНаименованиеЕд. изм.Базисная стоимостьДействия
+
+
+
- + diff --git a/static/norm-finder.js b/static/norm-finder.js index 195054c..055cf9a 100644 --- a/static/norm-finder.js +++ b/static/norm-finder.js @@ -19,6 +19,12 @@ let savedQuote = null; let draft = null; let searchPage = null; + let browsePage = null; + let catalogRows = []; + let requestSeq = 0; + let detailSeq = 0; + let openedRow = null; + let rowSeq = 0; let subjects = []; let priceZones = []; const compared = new Map(); @@ -99,18 +105,33 @@ } catch (e) { status(e.message, true); } } + function detachDetail() { + $('detail-section').hidden = true; + document.querySelector('.workspace').after($('detail-section')); + if (openedRow) openedRow.hidden = true; + openedRow = null; + } function renderSearchItem(item) { - const card = node('article', null, 'card'); - const head = node('div', null, 'card-head'); - head.append(node('span', item.code, 'code'), node('span', item.base_type, 'badge')); - card.append(head, node('h3', item.name || 'Без наименования'), - node('p', (item.base || '') + ' · измеритель: ' + (item.unit || 'не указан'), 'meta')); - if (item.section_path) card.append(node('p', item.section_path, 'hint')); - if (item.match_reason) card.append(node('p', item.match_reason, 'hint')); - if (item.provenance?.decree) card.append(node('p', 'Источник: ' + item.provenance.decree, 'hint')); - const actions = node('div', null, 'actions'); + const fragment = document.createDocumentFragment(); + const row = node('tr', null, 'norm-row'); + const detailRow = node('tr', null, 'norm-detail-row'); + detailRow.hidden = true; + const detailCell = node('td', null, 'inline-cell'); + detailCell.colSpan = 5; + const inline = node('div', null, 'inline-content'); + const variantList = node('div', null, 'variant-list'); variantList.hidden = true; + inline.append(variantList); detailCell.append(inline); detailRow.append(detailCell); + const controlId = 'norm-detail-' + (++rowSeq); + detailRow.id = controlId; + row.append(node('td', item.code, 'code'), node('td', item.name || 'Без наименования', 'norm-name'), + node('td', item.unit || '—'), + node('td', item.cost != null ? money(item.cost) : '—', 'num')); + const actionsCell = node('td'); + const actions = node('div', null, 'inline-actions'); const open = node('button', 'Открыть состав', 'primary small'); - open.type = 'button'; open.addEventListener('click', () => openDetail(item)); + open.type = 'button'; open.setAttribute('aria-controls', controlId); + open.setAttribute('aria-expanded', 'false'); + open.addEventListener('click', () => openDetail(item, detailRow)); const compare = node('button', compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить', 'secondary small'); compare.type = 'button'; compare.dataset.compareKey = key(item); @@ -119,11 +140,11 @@ const variants = node('button', 'Варианты таблицы', 'secondary small'); variants.type = 'button'; variants.setAttribute('aria-expanded', 'false'); - const variantList = node('div', null, 'variant-list'); - variantList.hidden = true; variants.addEventListener('click', async () => { if (variants.getAttribute('aria-expanded') === 'true') { - variantList.hidden = true; variants.setAttribute('aria-expanded', 'false'); return; + variantList.hidden = true; variants.setAttribute('aria-expanded', 'false'); + if ($('detail-section').parentElement !== inline) detailRow.hidden = true; + return; } variants.disabled = true; try { @@ -137,7 +158,7 @@ const line = node('div', null, 'variant-row'); const button = node('button', row.code + ' — ' + row.name + ' · ' + (row.unit || 'измеритель не указан'), 'variant-option'); - button.type = 'button'; button.addEventListener('click', () => openDetail(row)); + button.type = 'button'; button.addEventListener('click', () => openDetail(row, detailRow)); const compareVariant = node('button', compared.has(key(row)) ? 'Убрать из сравнения' : 'Сравнить', 'secondary small'); compareVariant.type = 'button'; @@ -145,12 +166,71 @@ compareVariant.addEventListener('click', () => toggleCompare(row)); line.append(button, compareVariant); variantList.append(line); } - variantList.hidden = false; variants.setAttribute('aria-expanded', 'true'); + variantList.hidden = false; detailRow.hidden = false; + variants.setAttribute('aria-expanded', 'true'); } catch (e) { status(e.message, true); } finally { variants.disabled = false; } }); - actions.append(open, compare, variants); card.append(actions, variantList); - return card; + actions.append(open, compare, variants); actionsCell.append(actions); row.append(actionsCell); + fragment.append(row, detailRow); + return fragment; + } + function showRows(items, append=false) { + if (!append) { detachDetail(); $('results').replaceChildren(); } + $('results').append(...items.map(renderSearchItem)); + } + function fillBaseTypes() { + const base = $('base').value === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022'; + const types = catalogRows.filter(row => row.base === base && row.base_type) + .map(row => ({id:row.base_type,name:row.base_type + ' · ' + row.count + ' норм'})); + if (!types.length) types.push({id:base === 'ФЕР-2020' ? 'ФЕР' : 'ГЭСН',name:'Основной сборник'}); + fillSelect($('base-type'), types, 'id', 'name', 'Выберите сборник'); + $('base-type').selectedIndex = 1; + } + function treeNode(child) { + const li = node('li'); + const button = node('button', child.name); button.type = 'button'; + button.setAttribute('aria-expanded', 'false'); + button.addEventListener('click', () => loadBrowse(child.path, li)); + li.append(button); + return li; + } + async function loadBrowse(path='', treeItem=null, nextPage=false) { + const base = $('base').value, baseType = $('base-type').value; + if (!base || !baseType) return; + const offset = nextPage ? browsePage?.offset || 0 : 0; + const seq = ++requestSeq; + status('Загружаю нормы сборника…'); + $('more-results').disabled = true; + try { + const data = await api(readPath('browse') + '?' + new URLSearchParams({ + base,base_type:baseType,path,limit:publicMode ? '20' : '40',offset:String(offset)})); + if (seq !== requestSeq) return; + if (!nextPage) { + searchPage = null; + showRows(data.items || []); + $('results-title').textContent = path ? path.split(' > ').at(-1) : baseType + ' · все нормы'; + $('breadcrumb').textContent = [baseType,path].filter(Boolean).join(' › '); + } else showRows(data.items || [], true); + browsePage = {base,baseType,path,offset:offset + (data.items || []).length}; + $('result-count').textContent = 'Показано ' + browsePage.offset; + $('more-results').hidden = !data.has_more; + if (treeItem) { + const button = treeItem.querySelector('button'); + button.setAttribute('aria-expanded', 'true'); + document.querySelectorAll('#tree-root button[aria-current]').forEach(x => x.removeAttribute('aria-current')); + button.setAttribute('aria-current', 'true'); + let list = treeItem.querySelector(':scope > ul'); + if (!list) { list = node('ul', null, 'tree-list'); treeItem.append(list); } + list.replaceChildren(...(data.children || []).map(treeNode)); + } else if (!path) { + const list = node('ul', null, 'tree-list'); + list.replaceChildren(...(data.children || []).map(treeNode)); + $('tree-root').replaceChildren(list); + } + status('Откройте строку для состава работ и ресурсов.'); + } catch (e) { if (seq === requestSeq) status(e.message, true); } + finally { $('more-results').disabled = false; } } async function search(event, nextPage=false) { event?.preventDefault(); @@ -159,20 +239,23 @@ const offset = nextPage ? searchPage?.offset || 0 : 0; if (q.length < 2) { status('Введите хотя бы два символа', true); return; } status('Ищу нормы…'); + const seq = ++requestSeq; 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',offset:String(offset)})); + if (seq !== requestSeq) return; const items = data.items || []; - if (nextPage) $('results').append(...items.map(renderSearchItem)); - else $('results').replaceChildren(...items.map(renderSearchItem)); - $('results-section').hidden = !$('results').children.length; + showRows(items, nextPage); + browsePage = null; + $('results-title').textContent = 'Результаты поиска'; + $('breadcrumb').textContent = q; searchPage = {q, base, offset:offset + items.length}; + $('result-count').textContent = 'Показано ' + searchPage.offset; $('more-results').hidden = !data.has_more || !items.length; const correction = data.interpreted_query && data.interpreted_query !== q ? 'Поиск по уточнённой формулировке: «' + data.interpreted_query + '». ' : ''; @@ -208,20 +291,45 @@ table.append(tbody); scroll.append(table); root.append(scroll); const provenance = item.provenance || {}; const source = [provenance.decree, provenance.file].filter(Boolean).join(' · '); - root.append(node('p', source ? 'Источник: ' + source : 'Источник в индексе не указан', 'hint')); + const sourcePanel = node('details'); + sourcePanel.append(node('summary', 'Источник нормы')); + sourcePanel.append(node('p', source || 'Источник в индексе не указан', 'hint')); + if (provenance.dataset) sourcePanel.append(node('p', 'Набор данных: ' + provenance.dataset, 'hint')); + if (provenance.url) { + try { + const url = new URL(provenance.url); + if (url.protocol === 'https:' && url.hostname === 'fgiscs.minstroyrf.ru') { + const link = node('a', 'Открыть официальный набор данных'); + link.href = url.href; link.target = '_blank'; link.rel = 'noopener noreferrer'; + sourcePanel.append(link); + } + } catch {} + } + root.append(sourcePanel); if (item.prices?.cost != null) root.append(node('p', 'Базисная стоимость: ' + money(item.prices.cost) + ' (уровень ' + (item.price_level || 'не указан') + '). Это не цена выбранного квартала.', 'notice')); } - async function openDetail(item) { + async function openDetail(item, targetRow=null) { + const seq = ++detailSeq; + const listing = requestSeq; status('Загружаю состав нормы…'); try { - active = await detailFor(item); savedQuote = null; + const loaded = await detailFor(item); + if (seq !== detailSeq || listing !== requestSeq || (targetRow && !targetRow.isConnected)) return; + active = loaded; savedQuote = null; $('quote').replaceChildren(); renderDetail(active); setUnits(active.unit); $('calc').disabled = !active.current_price_supported; if (active.calculation_limitation) $('quote').append(node('p', active.calculation_limitation, 'notice')); + if (targetRow) { + if (openedRow && openedRow !== targetRow) openedRow.hidden = true; + targetRow.querySelector('.inline-content').append($('detail-section')); + targetRow.hidden = false; openedRow = targetRow; + document.querySelectorAll('.norm-row button[aria-controls]').forEach(button => + button.setAttribute('aria-expanded', String(button.getAttribute('aria-controls') === targetRow.id))); + } $('detail-section').hidden = false; - $('detail-section').scrollIntoView({behavior:'smooth', block:'start'}); + if (targetRow) targetRow.scrollIntoView({behavior:'smooth', block:'nearest'}); status('Состав нормы загружен. Сверьте измеритель и ресурсы.'); } catch (e) { status(e.message, true); } } @@ -401,8 +509,12 @@ draft = await api('/api/norm-finder/drafts/' + id); renderDraft(); const first = draft.positions?.[0]; - if (first) await openDetail({base:first.base === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022', - base_type:first.base_type,code:first.code}); + if (first) { + const row = {base:first.base === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022', + base_type:first.base_type,code:first.code,name:first.name,unit:first.unit}; + showRows([row]); + await openDetail(row, $('results').querySelector('.norm-detail-row')); + } if (first) { $('qty').value = String(first.quantity); $('unit').value = first.unit; } const selection = draft.price_selection || {}; if (selection.subject_id) { @@ -426,6 +538,11 @@ const selection = data.selection || {}; active = await detailFor({base:selection.base === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022', base_type:selection.base_type, code:selection.code}); + showRows([active]); + const target = $('results').querySelector('.norm-detail-row'); + target.querySelector('.inline-content').append($('detail-section')); + target.hidden = false; openedRow = target; + $('results').querySelector('button[aria-controls]').setAttribute('aria-expanded', 'true'); renderDetail(active); $('detail-section').hidden = false; $('calc').disabled = !active.current_price_supported; $('qty').value = String(selection.quantity); setUnits(active.unit); $('unit').value = selection.unit; @@ -443,14 +560,26 @@ fillSelect($('base'), bases.map(b => ({id:b === 'ФЕР-2020' ? '2020' : '2022',name:b})), 'id', 'name', 'Выберите базу'); if (bases.length) $('base').selectedIndex = 1; + catalogRows = data.bases || []; + fillBaseTypes(); subjects = data.subjects || []; if (!publicMode) fillSelect($('subject'), subjects, 'id', 'name', 'Выберите регион'); if (!bases.length) status('Нормативная база пока недоступна', true); + await loadBrowse(); if (!publicMode && !(await restoreDraft())) await restoreQuote(); } catch (e) { status(e.message, true); } } $('search-form').addEventListener('submit', search); - $('more-results').addEventListener('click', event => search(event, true)); + $('more-results').addEventListener('click', event => browsePage + ? loadBrowse(browsePage.path, null, true) : search(event, true)); + $('base').addEventListener('change', () => { fillBaseTypes(); loadBrowse(); }); + $('base-type').addEventListener('change', () => loadBrowse()); + $('catalog-mobile').addEventListener('click', () => { + const tree = $('catalog-tree'); + tree.hidden = !tree.hidden; + $('catalog-mobile').setAttribute('aria-expanded', String(!tree.hidden)); + }); + if (matchMedia('(max-width:760px)').matches) $('catalog-tree').hidden = 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 789c22f..5be97e9 100644 --- a/tests/test_norm_finder.py +++ b/tests/test_norm_finder.py @@ -1,9 +1,41 @@ """Source-backed norm search and price preview.""" import pytest import importlib +import sqlite3 from fastapi.testclient import TestClient +def test_browse_keeps_sections_and_base_types_separate(tmp_path, monkeypatch): + import norm_finder + import fsnb_ref + db = tmp_path / "fsnb.sqlite" + with sqlite3.connect(db) as con: + con.execute("CREATE TABLE sources (source_id INTEGER)") + con.execute("CREATE TABLE works (base TEXT, base_type TEXT, code TEXT, name TEXT, " + "unit TEXT, cost REAL, price_level TEXT, section_path TEXT)") + con.executemany("INSERT INTO works VALUES (?,?,?,?,?,?,?,?)", [ + ("ГЭСН-2022", "ГЭСН", "01-01-001-01", "Разработка грунта", "1000 м3", None, + "норма", "Земляные работы > Раздел 1 > Таблица 1"), + ("ГЭСН-2022", "ГЭСН", "01-01-001-02", "Разработка грунта 2", "1000 м3", None, + "норма", "Земляные работы > Раздел 1 > Таблица 1"), + ("ГЭСН-2022", "ГЭСНм", "01-01-001-01", "Монтаж", "шт", None, + "норма", "Оборудование > Раздел 1"), + ]) + monkeypatch.setattr(fsnb_ref, "db_path", lambda: db) + root = norm_finder.browse("2022", "ГЭСН", "") + assert [row["name"] for row in root["children"]] == ["Земляные работы"] + section = norm_finder.browse("2022", "ГЭСН", "Земляные работы") + assert [row["name"] for row in section["children"]] == ["Раздел 1"] + leaf = norm_finder.browse("2022", "ГЭСН", "Земляные работы > Раздел 1 > Таблица 1", limit=1) + assert [row["code"] for row in leaf["items"]] == ["01-01-001-01"] + assert leaf["has_more"] is True + assert norm_finder.browse("2022", "ГЭСН", leaf["path"], limit=1, offset=1)["items"][0]["code"] == "01-01-001-02" + with pytest.raises(ValueError): + norm_finder.browse("2022", "ГЭСН", "Земляные работы > Несуществующий") + with pytest.raises(ValueError): + norm_finder.browse("2022", "ГЭСН", "%") + + def test_search_rejects_empty_query_and_uses_existing_fsnb(monkeypatch): import fsnb_ref import norm_finder @@ -254,6 +286,24 @@ def test_finder_page_is_reachable_from_site(api): assert client.get("/static/norm-finder.js").headers["Cache-Control"] == "no-cache, must-revalidate" +def test_browse_routes_bound_public_pages_and_require_auth(api, monkeypatch): + import norm_finder + client, headers, _ = api + calls = [] + def fake_browse(base, base_type, path, limit, offset): + calls.append((base, base_type, path, limit, offset)) + return {"children": [], "items": [{"code": "01-01-001-01"}], "has_more": False} + monkeypatch.setattr(norm_finder, "browse", fake_browse) + url = "/api/public/norm-finder/browse?base=2022&base_type=ГЭСН&path=Земляные работы&limit=20" + response = client.get(url) + assert response.status_code == 200 + assert response.json()["items"][0]["code"] == "01-01-001-01" + assert calls == [("2022", "ГЭСН", "Земляные работы", 20, 0)] + assert client.get(url.replace("limit=20", "limit=21")).status_code == 400 + assert client.get("/api/norm-finder/browse").status_code == 401 + assert client.get("/api/norm-finder/browse", headers=headers).status_code == 200 + + def test_finder_draft_is_scoped_revisioned_and_never_totals_missing_costs(api, monkeypatch): import auth import engine_prices diff --git a/tests/test_norm_finder_ui.py b/tests/test_norm_finder_ui.py index eaee485..f1ef495 100644 --- a/tests/test_norm_finder_ui.py +++ b/tests/test_norm_finder_ui.py @@ -79,6 +79,43 @@ def test_family_variants_can_be_opened_and_compared_on_phone(browser, site): page.close() +def test_catalog_tree_opens_norm_composition_in_the_same_table(browser, site): + page = browser.new_page(viewport={"width": 1360, "height": 800}) + page.add_init_script("""(() => { + const base = {base:'ГЭСН-2022',base_type:'ГЭСН',code:'01-01-001-01', + name:'Разработка грунта',unit:'1000 м3',section_path:'Земляные работы > Раздел 1'}; + window.fetch = async url => { + const u = new URL(url, location.href); + let value = {}; + if (u.pathname.endsWith('/catalog')) value={bases:[{base:'ГЭСН-2022',base_type:'ГЭСН',count:1}]}; + if (u.pathname.endsWith('/browse')) { + const path=u.searchParams.get('path'); + value={items:[base],children:path==='Земляные работы' + ? [{name:'Раздел 1',path:'Земляные работы > Раздел 1'}] + : path ? [] : [{name:'Земляные работы',path:'Земляные работы'}],has_more:false}; + } + if (u.pathname.endsWith('/detail')) value={...base,content:['Разработка грунта экскаватором'], + resources:[{code:'91.01.01-001',name:'Экскаватор',unit:'маш.-ч',quantity:1}], + provenance:{decree:'Официальный сборник',file:'ГЭСН.xml'},current_price_supported:false}; + return new Response(JSON.stringify(value),{status:200,headers:{'Content-Type':'application/json'}}); + }; + })()""") + page.goto(site) + page.locator('#tree-root button', has_text='Земляные работы').click() + page.locator('#tree-root button', has_text='Раздел 1').wait_for() + row = page.locator('#results .norm-row').first + row.locator('button', has_text='Открыть состав').click() + detail = page.locator('#results .norm-detail-row').first + detail.wait_for(state='visible') + assert 'Разработка грунта экскаватором' in detail.inner_text() + assert 'Экскаватор' in detail.inner_text() + detail.locator('summary', has_text='Источник нормы').click() + assert 'ГЭСН.xml' in detail.inner_text() + assert row.locator('button', has_text='Открыть состав').get_attribute('aria-expanded') == 'true' + assert page.locator('#results .norm-row').count() == 1 + page.close() + + def test_saved_multi_position_draft_survives_reload_and_marks_incomplete_price(browser, site): state = {"draft": None} first = {"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": "11-01-011-01", @@ -211,7 +248,8 @@ def test_guest_can_open_next_page_without_losing_first_results(browser, site): else: from urllib.parse import parse_qs offset = int(parse_qs(url.query).get("offset", ["0"])[0]) - offsets.append(offset) + if url.path.endswith('/search'): + 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} @@ -221,10 +259,10 @@ def test_guest_can_open_next_page_without_losing_first_results(browser, site): 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('#results .norm-row').nth(7).wait_for() page.locator('#more-results').click() - page.locator('#results .card').nth(15).wait_for() + page.locator('#results .norm-row').nth(15).wait_for() assert offsets == [0, 8] - assert page.locator('#results .card').count() == 16 + assert page.locator('#results .norm-row').count() == 16 assert page.locator('#more-results').is_hidden() page.close()