Files
smeta-web/norm_finder.py

184 lines
10 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Source-backed norm finder and conservative current-price preview."""
from __future__ import annotations
import math
import re
import fsnb_ref
BASES = {"2022": "ГЭСН-2022", "2020": "ФЕР-2020"}
TYPES = {"ГЭСН", "ГЭСНм", "ГЭСНмр", "ГЭСНп", "ГЭСНр",
"ФЕР", "ФЕРм", "ФЕРмр", "ФЕРп", "ФЕРр"}
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 search(query: str, base: str, limit: int = 12) -> 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:
raise ValueError("Укажите запрос 2–160 символов, доступную базу и число результатов до 30")
result = fsnb_ref.find_works(query=query, base=base, limit=limit)
if result.get("status") == "not_found" and not fsnb_ref._extract_code(query):
terms = [term for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query))
if len(term) >= 4 and not fsnb_ref._is_generic_term(term)]
counts = [(fsnb_ref.count_works(term), term) for term in terms]
usable = [(count, term) for count, term in counts if count > 0]
if usable:
anchor = min(usable)[1]
fallback = fsnb_ref.find_works(query=anchor, base=base, limit=max(60, limit * 5))
if fallback.get("status") == "ok":
def rank(row):
name = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(str(row.get("name") or "")))
section = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(str(row.get("section_path") or "")))
score = 0
for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query)):
if len(term) < 3:
continue
stem = fsnb_ref._stem(term)
root = stem[:4] if len(stem) >= 5 else stem[:3]
score += (3 if any(word.startswith(root) for word in name) else 0)
score += (2 if any(word.startswith(root) for word in section) else 0)
return score
rows = sorted(fallback.get("works") or [], key=rank, reverse=True)
result = {"status": "ok", "works": rows[:limit]}
if result.get("status") == "ok":
terms = [term for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query))
if len(term) >= 3 and not fsnb_ref._is_generic_term(term)]
items = []
for original in result.get("works") or []:
row = dict(original)
if query == row.get("code"):
row["match_reason"] = "Точный шифр"
row["match_score"] = 100
else:
words = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(
str(row.get("name") or "") + " " + str(row.get("section_path") or "")))
matched = []
for term in terms:
stem = fsnb_ref._stem(term)
root = stem[:4] if len(stem) >= 5 else stem[:3]
if any(word.startswith(root) for word in words):
matched.append(term)
row["match_score"] = round(100 * 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), "query": query, "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}