From 4bb95e757f47310b91d8f3e4ff7b180159bacf58 Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 4 Dec 2026 20:04:44 +1000 Subject: [PATCH] Order norm finder collections by source code --- norm_finder.py | 22 ++++++++++++++-------- tests/test_norm_finder.py | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/norm_finder.py b/norm_finder.py index f6a9c56..0f1e6c6 100644 --- a/norm_finder.py +++ b/norm_finder.py @@ -87,15 +87,16 @@ def catalog() -> list[dict]: @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.""" +def _section_paths(db_key: tuple[str, int, int], base: str, base_type: str) -> tuple[tuple[str, str], ...]: + """Cache section paths and their first norm codes; a rebuilt DB gets a new 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", + return tuple((row[0], row[1]) for row in con.execute( + "SELECT section_path, MIN(code) FROM works WHERE base=? AND base_type=? " + "AND section_path IS NOT NULL AND section_path != '' " + "GROUP BY section_path ORDER BY section_path", (base, base_type))) finally: con.close() @@ -117,10 +118,15 @@ def browse(base: str, base_type: str, path: str = "", limit: int = 40, 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): + 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}) + child_codes = {} + for section, code in paths: + if section.startswith(prefix) and section != path: + name = section[len(prefix):].split(" > ", 1)[0] + if name not in child_codes or code < child_codes[name]: + child_codes[name] = code + children = sorted(child_codes, key=lambda name: (child_codes[name], name)) con = fsnb_ref._connect() if con is None: raise RuntimeError("Нормативная база недоступна") diff --git a/tests/test_norm_finder.py b/tests/test_norm_finder.py index 5be97e9..1e4d1ef 100644 --- a/tests/test_norm_finder.py +++ b/tests/test_norm_finder.py @@ -36,6 +36,32 @@ def test_browse_keeps_sections_and_base_types_separate(tmp_path, monkeypatch): norm_finder.browse("2022", "ГЭСН", "%") +def test_browse_orders_collections_and_sections_by_norm_code(tmp_path, monkeypatch): + import norm_finder + import fsnb_ref + db = tmp_path / "ordered_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", "ГЭСН", "06-01-001-01", "Бетон", "м3", None, + "норма", "Бетонные работы > Раздел 1"), + ("ГЭСН-2022", "ГЭСН", "02-01-001-01", "Горные работы", "м3", None, + "норма", "Горные работы > Раздел 1"), + ("ГЭСН-2022", "ГЭСН", "01-10-001-01", "Земляные работы 10", "м3", None, + "норма", "Земляные работы > Раздел 10"), + ("ГЭСН-2022", "ГЭСН", "01-02-001-01", "Земляные работы 2", "м3", None, + "норма", "Земляные работы > Раздел 2"), + ]) + monkeypatch.setattr(fsnb_ref, "db_path", lambda: db) + root = norm_finder.browse("2022", "ГЭСН") + assert [row["name"] for row in root["children"]] == [ + "Земляные работы", "Горные работы", "Бетонные работы"] + sections = norm_finder.browse("2022", "ГЭСН", "Земляные работы") + assert [row["name"] for row in sections["children"]] == ["Раздел 2", "Раздел 10"] + + def test_search_rejects_empty_query_and_uses_existing_fsnb(monkeypatch): import fsnb_ref import norm_finder