"""Source-backed norm finder and conservative current-price preview.""" from __future__ import annotations import math import re from functools import lru_cache import fsnb_ref BASES = {"2022": "ГЭСН-2022", "2020": "ФЕР-2020"} TYPES = {"ГЭСН", "ГЭСНм", "ГЭСНмр", "ГЭСНп", "ГЭСНр", "ФЕР", "ФЕРм", "ФЕРмр", "ФЕРп", "ФЕРр"} _WORDS = re.compile(r"[а-яa-z0-9]+") def _interpreted_query(query: str) -> str: """Only source-checked spelling and terminology variants, never a guessed norm.""" words = query.split() fixed = [] for word in words: value = re.sub(r"извешател", "извещател", word, flags=re.IGNORECASE) value = re.sub(r"стяшк", "стяжк", value, flags=re.IGNORECASE) fixed.append(value) normalized = " ".join(fixed) normalized = re.sub(r"\bбордюрного\s+камня\b", "бортовых камней", normalized, flags=re.IGNORECASE) return normalized def _search_terms(query: str) -> list[str]: return [word for word in _WORDS.findall(fsnb_ref.norm_text(query)) if len(word) >= 3 and not fsnb_ref._is_generic_term(word)] def _word_match(term: str, words: list[str]) -> bool: stem = fsnb_ref._stem(term) root = stem[:4] if len(stem) >= 5 else stem[:3] return any(word.startswith(root) for word in words) def _search_rank(row: dict, terms: list[str]) -> tuple[int, int, str, str]: words = _WORDS.findall(fsnb_ref.norm_text(str(row.get("name") or ""))) section = _WORDS.findall(fsnb_ref.norm_text(str(row.get("section_path") or ""))) named = sum(_word_match(term, words) for term in terms) in_section = sum(_word_match(term, section) for term in terms) score = 16 * named + 2 * in_section if terms and words and _word_match(terms[-1], words[:2]): score += 12 # actual subject of the norm, rather than an accessory "for" it elif terms and _word_match(terms[-1], words): score += 8 if terms and named == len(terms): score += 8 if "для" in words and terms and _word_match(terms[-1], words[words.index("для") + 1:]): score -= 20 if words and words[0] in {"ремонт", "разборка", "добавлять", "добавление"}: score -= 9 return (-score, len(str(row.get("name") or "")), str(row.get("base_type") or ""), str(row.get("code") or "")) def _diverse_families(rows: list[dict], limit: int) -> list[dict]: """Show distinct technologies before filling the page with one table's sizes.""" first, rest, seen = [], [], set() for row in rows: family = (row.get("base_type"), str(row.get("code") or "").rsplit("-", 1)[0]) if family in seen: rest.append(row) else: first.append(row) seen.add(family) return (first + rest)[:limit] def catalog() -> list[dict]: """List only norm families actually present in the deployed read-only index.""" con = fsnb_ref._connect() if con is None: return [] try: rows = con.execute("SELECT base, base_type, COUNT(*) AS n FROM works " "GROUP BY base, base_type ORDER BY base, base_type").fetchall() return [{"base": row["base"], "base_type": row["base_type"], "count": row["n"]} for row in rows if row["base"] in BASES.values()] finally: con.close() def rate_catalog() -> list[dict]: """НР/СП by explicit work type from the project's loaded source tables.""" try: import estimate_contract # noqa: F401 — registers the sibling package path from smeta_railway.data.nr_sp_tables import NR_TABLE, SP_TABLE except ImportError: return [] shared = sorted(NR_TABLE.keys() & SP_TABLE.keys(), key=lambda key: (tuple(int(part) for part in re.findall(r"\d+", key)), key)) return [{"id": key, "name": NR_TABLE[key][0], "nr_code": f"812/пр, п.{key}", "nr_pct": NR_TABLE[key][1], "sp_code": f"774/пр, п.{key}", "sp_pct": SP_TABLE[key][1]} for key in shared] @lru_cache(maxsize=32) 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], 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() 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("Раздел не найден в выбранном сборнике") 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("Нормативная база недоступна") 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,salary,machines,salary_mach,materials," "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) 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) # 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=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) for index, term in enumerate(terms) if len(term) >= 4] usable = [item for item in counts if item[0] > 0] if usable: anchor = min(usable)[2] if anchor != interpreted: 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)) 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) if query == row.get("code"): row["match_reason"] = "Точный шифр" row["match_score"] = 100 else: words = _WORDS.findall(fsnb_ref.norm_text(str(row.get("name") or ""))) matched = [term for term in terms if _word_match(term, words)] row["match_score"] = min(95, round(85 * len(matched) / len(terms))) if terms else 0 row["match_reason"] = ("Совпали слова: " + ", ".join(matched) if matched else "Похожее название — проверьте состав") items.append(row) return {"status": "ok", "items": items, "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, "base": BASES[base]} def detail(base: str, base_type: str, code: str) -> dict: if (base not in BASES or base_type not in TYPES or not isinstance(code, str) or not fsnb_ref.WORK_CODE_RE.fullmatch(code) or len(code) > 24): raise ValueError("Укажите существующий шифр, тип сборника и базу") found = fsnb_ref.find_gesn_composition(query=code, base=base, limit=30) rows = [row for row in found.get("results") or [] if row.get("base") == BASES[base] and row.get("base_type") == base_type and row.get("code") == code] if len(rows) != 1: raise ValueError("Норма в выбранной базе не найдена однозначно") work = dict(rows[0]) limitation = "" if base != "2022" or not base_type.startswith("ГЭСН"): limitation = "Для этой базы доступна базисная цена; текущие цены по зоне не рассчитываются" else: try: _norm_from_work(work) except ValueError as exc: limitation = str(exc) work["current_price_supported"] = not limitation work["calculation_limitation"] = limitation return work def _norm_from_work(work: dict): """Build only compositions supported without guessing machine payroll or project consumption.""" import estimate_contract # noqa: F401 — registers the sibling smeta_railway package path from smeta_railway.models import LaborResource, MaterialResource, NormResources if not work.get("unit") or not work.get("resources"): raise ValueError("Измеритель или ресурсный состав нормы отсутствует") labor = None materials = [] for row in work["resources"]: code = str(row.get("code") or "") quantity = row.get("quantity") if (not isinstance(quantity, (int, float)) or isinstance(quantity, bool) or not math.isfinite(quantity) or quantity < 0 or row.get("quantity_note")): raise ValueError("Расход одного из ресурсов не задан числом") if re.fullmatch(r"1-100-\d{2}", code): if labor is not None: raise ValueError("Оплата труда в норме не определяется однозначно") labor = LaborResource(razryad=int(code[-2:]) / 10, chel_hours=quantity) elif re.fullmatch(r"\d{2}\.\S+", code) and not code.startswith("91."): materials.append(MaterialResource(code=code, name=row.get("name") or code, unit=row.get("unit") or "", qty=quantity)) else: raise ValueError("Расчёт этой нормы пока не поддерживается: машины, машинисты или неизвестный ресурс") norm_code = work["base_type"] + " " + work["code"] return NormResources(norm_code=norm_code, norm_name=work.get("name"), unit=work["unit"], ozp=labor, materials=materials) def calculate(base: str, base_type: str, code: str, quantity: float, unit: str, zone: str, period: str) -> dict: if (not isinstance(quantity, (int, float)) or isinstance(quantity, bool) or not 0.000001 <= quantity <= 1_000_000 or not math.isfinite(quantity) or not isinstance(unit, str) or not 1 <= len(unit) <= 60): raise ValueError("Укажите положительный объём и его единицу измерения") work = detail(base, base_type, code) if base != "2022" or not base_type.startswith("ГЭСН"): raise ValueError("Расчёт текущих цен для этой базы не поддерживается") norm = _norm_from_work(work) import engine_prices import estimate_contract as ec meta = {"region": zone, "zone": zone, "price_level": period} basis = engine_prices.resolve(meta) if basis.get("status") != "ok": return {"status": "unavailable", "complete": False, "message": basis.get("message") or "Ценовая форма недоступна"} resource_key = ec._code_key(norm.norm_code) resources = {resource_key: norm} positions, refusal = ec._positions_in_measures( [{"code": norm.norm_code, "name": work.get("name") or code, "qty": quantity, "unit": unit}], resources) if refusal: raise ValueError(refusal.get("message") or "Единица объёма не совпадает с измерителем") try: prices = engine_prices.load_lookup(basis["entry"]) except (OSError, ValueError): return {"status": "unavailable", "complete": False, "message": "Форма цен зоны не читается"} draft = ec.EstimateDraft(meta=ec.DraftMeta(**meta), positions=[ec.DraftPosition(**position) for position in positions]) result = ec.build_and_calc(draft, resources, prices, basis) amount = result.get("grand_total") complete = (result.get("status") == "ok" and bool(result.get("ok")) and not result.get("missing") and not result.get("unpriced") and isinstance(amount, (int, float)) and math.isfinite(amount)) return {"status": result.get("status"), "complete": complete, "total": amount if complete else None, "accounted": amount if result.get("status") == "ok" and not complete and isinstance(amount, (int, float)) and math.isfinite(amount) and amount > 0 else None, "missing": result.get("missing") or [], "unpriced": result.get("unpriced") or [], "message": result.get("message") or "", "limits_note": ec.LIMITS_NOTE, "base": work["base"], "base_type": base_type, "code": code, "name": work.get("name"), "quantity": quantity, "unit": unit, "zone": zone, "period": period}