diff --git a/db.py b/db.py
index 9ffd6cc..06257be 100644
--- a/db.py
+++ b/db.py
@@ -671,6 +671,37 @@ def replace_scoped_assistant(username: str, tab_id: str, message_id: int,
return cursor.rowcount == 1
+def get_scoped_norm_quote(username: str, tab_id: str, quote_id: int) -> dict | None:
+ """One saved finder result, never a quote from another user or dialog."""
+ import json
+
+ with _conn() as conn:
+ row = conn.execute(
+ "SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? "
+ "AND role='norm_quote'", (quote_id, username, tab_id),
+ ).fetchone()
+ if row is None:
+ return None
+ try:
+ data = json.loads(row["content"])
+ except (ValueError, TypeError):
+ return None
+ return {"raw": row["content"], "data": data}
+
+
+def replace_scoped_norm_quote(username: str, tab_id: str, quote_id: int,
+ old_content: str, new_content: str) -> bool:
+ """Compare and swap one finder result in the current dialog."""
+ with _conn() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ cursor = conn.execute(
+ "UPDATE messages SET content=? WHERE id=? AND username=? AND tab_id=? "
+ "AND role='norm_quote' AND content=?",
+ (new_content, quote_id, username, tab_id, old_content),
+ )
+ return cursor.rowcount == 1
+
+
def replace_linked_estimate(username: str, tab_id: str, estimate_id: int,
expected_revision: int, data: dict, answer: str) -> str:
"""Compare-and-swap answer and estimate in one SQLite transaction."""
diff --git a/docs/verification/norm-finder-compare.png b/docs/verification/norm-finder-compare.png
new file mode 100644
index 0000000..c023298
Binary files /dev/null and b/docs/verification/norm-finder-compare.png differ
diff --git a/docs/verification/norm-finder-desktop.png b/docs/verification/norm-finder-desktop.png
new file mode 100644
index 0000000..3a4df60
Binary files /dev/null and b/docs/verification/norm-finder-desktop.png differ
diff --git a/docs/verification/norm-finder-mobile.png b/docs/verification/norm-finder-mobile.png
new file mode 100644
index 0000000..917cb7a
Binary files /dev/null and b/docs/verification/norm-finder-mobile.png differ
diff --git a/fsnb_ref.py b/fsnb_ref.py
index 84b9101..a93a187 100644
--- a/fsnb_ref.py
+++ b/fsnb_ref.py
@@ -398,12 +398,14 @@ def find_works(*, query: str, base: str | None = None,
"не найдено. Код и норму бери только из данных — уточни "
"наименование или шифр.")}
diverse = _diverse_works(rows, limit)
+ srcs = _sources_map(con)
out = [{"code": r["code"], "name": r["name"], "unit": r["unit"],
"base": r["base"], "base_type": r["base_type"],
"price_level": r["price_level"], "section_path": r["section_path"],
"content": r["content"],
"cost": r["cost"], "salary": r["salary"],
- "machines": r["machines"], "materials": r["materials"]}
+ "machines": r["machines"], "materials": r["materials"],
+ "provenance": _provenance(srcs.get(r["source_id"]))}
for r in diverse]
return {"status": "ok", "works": out, "total": len(rows)}
except sqlite3.Error as e:
diff --git a/main.py b/main.py
index 4d5860b..655ec2b 100644
--- a/main.py
+++ b/main.py
@@ -1079,6 +1079,12 @@ async def index(request: Request):
)
+@app.get("/podbor", response_class=HTMLResponse)
+async def norm_finder_page():
+ return FileResponse("static/norm-finder.html", media_type="text/html",
+ headers={"Cache-Control": "no-store"})
+
+
@app.get("/api/version")
async def version():
"""Public — single source of UI version (stamped into .app-version on the front)."""
@@ -2368,6 +2374,132 @@ async def sessions(request: Request):
return list_sessions(user)
+@app.get("/api/norm-finder/catalog")
+async def norm_finder_catalog(request: Request):
+ _get_user(request)
+ import norm_finder
+ import engine_prices
+ bases = await asyncio.to_thread(norm_finder.catalog)
+ price_catalog = await asyncio.to_thread(engine_prices.load_catalog) or {}
+ subjects = {}
+ for row in price_catalog.get("zones") or []:
+ sid = row.get("subject_id")
+ if isinstance(sid, int) and not isinstance(sid, bool):
+ subjects[sid] = row.get("subject_name") or f"Субъект {sid}"
+ return {"bases": bases, "subjects": [{"id": sid, "name": name}
+ for sid, name in sorted(subjects.items(), key=lambda x: x[1])]}
+
+
+@app.get("/api/norm-finder/search")
+async def norm_finder_search(request: Request, q: str = "", base: str = "2022", limit: int = 12):
+ _get_user(request)
+ import norm_finder
+ try:
+ found = 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":
+ raise HTTPException(503, found.get("message"))
+ return found
+
+
+@app.get("/api/norm-finder/detail")
+async def norm_finder_detail(request: Request, base: str = "", base_type: str = "",
+ code: str = ""):
+ _get_user(request)
+ import norm_finder
+ try:
+ return await asyncio.to_thread(norm_finder.detail, base, base_type, code)
+ except ValueError as exc:
+ raise HTTPException(400, str(exc)) from exc
+
+
+@app.get("/api/norm-finder/prices")
+async def norm_finder_prices(request: Request, subject_id: int):
+ _get_user(request)
+ import engine_prices
+ if subject_id < 1:
+ raise HTTPException(400, "Укажите субъект")
+ return {"zones": await asyncio.to_thread(engine_prices.basis_options, subject_id)}
+
+
+async def _finder_calculation(body: dict, base: str, base_type: str, code: str) -> dict:
+ import engine_prices
+ import estimate_interactive
+ import norm_finder
+ sid, zid, pid = (body.get(key) for key in ("subject_id", "zone_id", "period_id"))
+ qty, unit = body.get("quantity"), body.get("unit")
+ if (any(not isinstance(v, int) or isinstance(v, bool) or v < 1 for v in (sid, zid, pid))
+ or not isinstance(qty, (int, float)) or isinstance(qty, bool)
+ or not 0.000001 <= qty <= 1_000_000 or not math.isfinite(qty)
+ or not isinstance(unit, str) or not 1 <= len(unit) <= 60):
+ raise HTTPException(400, "Укажите доступную зону, квартал, объём и его единицу")
+ zones = await asyncio.to_thread(engine_prices.basis_options, sid)
+ selected = estimate_interactive.selected_form(zones, zid, pid)
+ if selected is None:
+ raise HTTPException(400, "Выбранной ценовой формы нет в каталоге")
+ zone, period = selected
+ try:
+ result = await asyncio.to_thread(norm_finder.calculate, base, base_type, code,
+ qty, unit, zone["name"], period["name"])
+ except ValueError as exc:
+ raise HTTPException(400, str(exc)) from exc
+ return {"selection": {"base": base, "base_type": base_type, "code": code,
+ "quantity": qty, "unit": unit, "subject_id": sid,
+ "zone_id": zid, "period_id": pid}, "result": result}
+
+
+@app.post("/api/norm-finder/calculate")
+async def norm_finder_calculate(request: Request):
+ user, tab_id = _get_user(request), _get_tab(request)
+ body = await _тело(request)
+ base, base_type, code = (body.get(key) for key in ("base", "base_type", "code"))
+ if not all(isinstance(value, str) for value in (base, base_type, code)):
+ raise HTTPException(400, "Укажите норму из каталога")
+ _check_rate_limit(user)
+ data = await _finder_calculation(body, base, base_type, code)
+ data["revision"] = 0
+ quote_id = await asyncio.to_thread(save_message, user, tab_id, "norm_quote",
+ json.dumps(data, ensure_ascii=False))
+ log_action(user, "norm_finder", "POST", "/api/norm-finder/calculate",
+ f"quote={quote_id}; code={code}", _client_ip(request) or None, 200)
+ return {"id": quote_id, **data}
+
+
+@app.get("/api/norm-finder/quotes/{quote_id}")
+async def norm_finder_quote(quote_id: int, request: Request):
+ user, tab_id = _get_user(request), _get_tab(request)
+ saved = await asyncio.to_thread(db.get_scoped_norm_quote, user, tab_id, quote_id)
+ if saved is None:
+ raise HTTPException(404, "Расчёт этого диалога не найден")
+ return {"id": quote_id, **saved["data"]}
+
+
+@app.post("/api/norm-finder/quotes/{quote_id}")
+async def norm_finder_recalculate(quote_id: int, request: Request):
+ user, tab_id = _get_user(request), _get_tab(request)
+ body = await _тело(request)
+ saved = await asyncio.to_thread(db.get_scoped_norm_quote, user, tab_id, quote_id)
+ if saved is None:
+ raise HTTPException(404, "Расчёт этого диалога не найден")
+ current = saved["data"]
+ revision = body.get("revision")
+ if not isinstance(revision, int) or isinstance(revision, bool) or revision != current.get("revision"):
+ raise HTTPException(409, "Расчёт изменён в другой вкладке — обновите страницу")
+ selection = current.get("selection") or {}
+ _check_rate_limit(user)
+ updated = await _finder_calculation(body, selection.get("base"),
+ selection.get("base_type"), selection.get("code"))
+ updated["revision"] = revision + 1
+ changed = await asyncio.to_thread(db.replace_scoped_norm_quote, user, tab_id, quote_id,
+ saved["raw"], json.dumps(updated, ensure_ascii=False))
+ if not changed:
+ raise HTTPException(409, "Расчёт изменён в другой вкладке — обновите страницу")
+ log_action(user, "norm_finder", "POST", f"/api/norm-finder/quotes/{quote_id}",
+ f"quote={quote_id}; revision={updated['revision']}", _client_ip(request) or None, 200)
+ return {"id": quote_id, **updated}
+
+
@app.post("/api/recalc")
async def recalc(request: Request):
"""Пересчитать смету движком по правкам объёмов (срез 6.2). Числа — из движка, не из JS.
diff --git a/norm_finder.py b/norm_finder.py
new file mode 100644
index 0000000..ca7545e
--- /dev/null
+++ b/norm_finder.py
@@ -0,0 +1,183 @@
+"""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}
diff --git a/static/chat.html b/static/chat.html
index 4988699..a308548 100644
--- a/static/chat.html
+++ b/static/chat.html
@@ -805,6 +805,7 @@ html { color-scheme: light; }
+