Implement source-backed norm finder and saved price previews
This commit is contained in:
@@ -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."""
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 40 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 86 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
+3
-1
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
+183
@@ -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}
|
||||
@@ -805,6 +805,7 @@ html { color-scheme: light; }
|
||||
<div class="account-menu-email" id="account-menu-email"></div>
|
||||
<button type="button" role="menuitem" onclick="closeAccountMenu(); location.href='/stats'">Статистика</button>
|
||||
<button type="button" role="menuitem" onclick="closeAccountMenu(); listFiles()">Файлы</button>
|
||||
<button type="button" role="menuitem" onclick="closeAccountMenu(); location.href='/podbor'">Подбор норм</button>
|
||||
<button type="button" role="menuitem" id="btn-invite" aria-expanded="false" aria-controls="invite-panel"
|
||||
onclick="closeAccountMenu(); toggleInvitePanel()">Пригласить коллегу</button>
|
||||
<button type="button" role="menuitem" id="btn-device"
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Подбор норм — Инфосмета</title>
|
||||
<style>
|
||||
:root { color-scheme: light; --bg:#f4f2ee; --card:#fff; --text:#272824; --muted:#626760;
|
||||
--line:#d8d9d2; --accent:#176c63; --bad:#a83c31; --warn:#fff5da; }
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; background:var(--bg); color:var(--text); font:16px/1.48 system-ui,-apple-system,Arial,sans-serif; }
|
||||
button,input,select { font:inherit; }
|
||||
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; }
|
||||
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; }
|
||||
h2 { font-size:1.35rem; margin:0 0 12px; }
|
||||
h3 { font-size:1.05rem; margin:0 0 8px; }
|
||||
p { margin:0 0 12px; }
|
||||
.intro { max-width:760px; color:var(--muted); margin-bottom:22px; }
|
||||
.panel,.card { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:20px; }
|
||||
.search-row,.controls,.actions { display:flex; gap:10px; align-items:end; flex-wrap:wrap; }
|
||||
label { display:grid; gap:5px; font-size:.84rem; color:var(--muted); font-weight:600; }
|
||||
input,select { min-height:42px; padding:8px 11px; color:var(--text); background:var(--card);
|
||||
border:1px solid var(--line); border-radius:8px; max-width:100%; }
|
||||
#query { flex:1 1 330px; }
|
||||
.search-row label:has(#query) { flex:1 1 330px; }
|
||||
.primary,.secondary { min-height:42px; padding:8px 16px; border-radius:8px; font-weight:650; }
|
||||
.primary { background:var(--accent); border:1px solid var(--accent); color:#fff; }
|
||||
.secondary { background:var(--card); border:1px solid var(--line); color:var(--text); }
|
||||
.small { min-height:34px; padding:5px 10px; font-size:.84rem; }
|
||||
.examples { display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-top:14px; color:var(--muted); font-size:.85rem; }
|
||||
.examples button { border:0; border-bottom:1px dotted var(--accent); background:transparent; color:var(--accent); padding:0; }
|
||||
.status { min-height:24px; margin:14px 0; color:var(--muted); }
|
||||
.status.error { color:var(--bad); }
|
||||
.results { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,340px),1fr)); gap:14px; }
|
||||
.card { display:flex; flex-direction:column; gap:7px; }
|
||||
.card-head { display:flex; align-items:start; justify-content:space-between; gap:12px; }
|
||||
.code { color:var(--accent); font-weight:750; font-variant-numeric:tabular-nums; }
|
||||
.badge { background:#e9f4f1; color:#155f56; padding:3px 8px; border-radius:999px; font-size:.72rem; white-space:nowrap; }
|
||||
.meta,.hint { font-size:.82rem; color:var(--muted); }
|
||||
.card .actions { margin-top:auto; padding-top:7px; }
|
||||
.section { margin-top:28px; }
|
||||
.detail-grid { display:grid; grid-template-columns:minmax(0,1.4fr) minmax(270px,.8fr); gap:18px; }
|
||||
.list { margin:0; padding-left:20px; }
|
||||
.scroll { max-width:100%; overflow:auto; }
|
||||
table { border-collapse:collapse; width:100%; font-size:.86rem; }
|
||||
th,td { border-bottom:1px solid var(--line); text-align:left; padding:8px; vertical-align:top; }
|
||||
th { color:var(--muted); font-weight:650; }
|
||||
.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.comparison { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; }
|
||||
.comparison .card { overflow-wrap:anywhere; }
|
||||
.notice { background:var(--warn); border-radius:9px; padding:10px 12px; font-size:.86rem; }
|
||||
.result-amount { font-size:1.5rem; font-weight:750; font-variant-numeric:tabular-nums; }
|
||||
.quote-controls label { min-width:140px; }
|
||||
.quote-controls #qty { width:125px; }
|
||||
[hidden] { display:none !important; }
|
||||
@media (max-width:760px) { .wrap { padding:18px 14px 40px; } header { margin-bottom:24px; }
|
||||
.detail-grid,.comparison { grid-template-columns:1fr; } .panel,.card { padding:15px; }
|
||||
.search-row > *, .controls > label { flex:1 1 100%; } .search-row button { width:100%; }
|
||||
.quote-controls label { min-width:0; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="wrap">
|
||||
<header><a class="brand" href="/">ИНФОСМЕТА</a><a href="/">Вернуться в чат</a></header>
|
||||
<h1>Подбор норм</h1>
|
||||
<p class="intro">Найдите работу по названию или шифру, проверьте состав и измеритель, сравните варианты. Цены считаются только по доступной форме выбранной зоны и квартала.</p>
|
||||
<div id="auth-notice" class="notice" hidden>Чтобы искать нормы, <a href="/">войдите в Инфосмету</a>.</div>
|
||||
<form id="search-form" class="panel">
|
||||
<div class="search-row">
|
||||
<label for="query">Работа или шифр<input id="query" type="search" maxlength="160" placeholder="Например, монтаж пожарного извещателя" required></label>
|
||||
<label for="base">Нормативная база<select id="base" aria-label="Нормативная база"></select></label>
|
||||
<button class="primary" type="submit">Найти нормы</button>
|
||||
</div>
|
||||
<div class="examples">Примеры: <button type="button" data-query="монтаж извещателя">монтаж извещателя</button>
|
||||
<button type="button" data-query="устройство стяжки пола">устройство стяжки пола</button>
|
||||
<button type="button" data-query="10-08-002-02">10-08-002-02</button></div>
|
||||
</form>
|
||||
<div id="status" class="status" role="status" aria-live="polite"></div>
|
||||
<section id="results-section" class="section" hidden><h2>Подходящие нормы</h2><div id="results" class="results"></div></section>
|
||||
<section id="detail-section" class="section" hidden><div class="detail-grid">
|
||||
<div class="panel"><h2 id="detail-title">Состав нормы</h2><div id="detail"></div></div>
|
||||
<div class="panel"><h2>Предварительный расчёт</h2><p class="hint">Объём вводится в выбранной единице. Недостающие цены и затраты будут отмечены.</p>
|
||||
<div class="controls quote-controls">
|
||||
<label for="subject">Регион<select id="subject"></select></label>
|
||||
<label for="zone">Ценовая зона<select id="zone"></select></label>
|
||||
<label for="period">Квартал<select id="period"></select></label>
|
||||
<label for="qty">Объём<input id="qty" type="number" min="0.000001" max="1000000" step="any" value="1"></label>
|
||||
<label for="unit">Единица<select id="unit"></select></label>
|
||||
</div>
|
||||
<div class="actions" style="margin-top:16px"><button id="calc" type="button" class="primary">Рассчитать</button>
|
||||
<button id="to-chat" type="button" class="secondary">Перенести в чат</button></div>
|
||||
<div id="quote" style="margin-top:16px" aria-live="polite"></div>
|
||||
</div>
|
||||
</div></section>
|
||||
<section id="compare-section" class="section" hidden><h2>Сравнение норм</h2><p id="compare-warning" class="notice" hidden></p>
|
||||
<div id="comparison" class="comparison"></div></section>
|
||||
</main>
|
||||
<script src="/static/norm-finder.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,285 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const $ = id => document.getElementById(id);
|
||||
const token = (() => { try { return localStorage.getItem('token') || ''; } catch { return ''; } })();
|
||||
const subject = (() => {
|
||||
try { return JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))).sub || ''; }
|
||||
catch { return ''; }
|
||||
})();
|
||||
const tabKey = 'tabId:' + subject;
|
||||
const tabId = (() => {
|
||||
try {
|
||||
let id = localStorage.getItem(tabKey);
|
||||
if (!id) { id = crypto.randomUUID(); localStorage.setItem(tabKey, id); }
|
||||
return id;
|
||||
} catch { return crypto.randomUUID(); }
|
||||
})();
|
||||
let active = null;
|
||||
let savedQuote = null;
|
||||
let subjects = [];
|
||||
let priceZones = [];
|
||||
const compared = new Map();
|
||||
const money = n => new Intl.NumberFormat('ru-RU', {minimumFractionDigits:2, maximumFractionDigits:2}).format(n) + ' ₽';
|
||||
|
||||
function node(tag, value, className) {
|
||||
const el = document.createElement(tag);
|
||||
if (value != null) el.textContent = String(value);
|
||||
if (className) el.className = className;
|
||||
return el;
|
||||
}
|
||||
function status(message, error=false) {
|
||||
$('status').textContent = message;
|
||||
$('status').classList.toggle('error', error);
|
||||
}
|
||||
async function api(path, options={}) {
|
||||
const response = await fetch(path, { ...options, headers: {
|
||||
Authorization: 'Bearer ' + token, 'X-Tab-Id': tabId,
|
||||
...(options.body ? {'Content-Type':'application/json'} : {}), ...(options.headers || {})
|
||||
}});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(typeof data.detail === 'string' ? data.detail : 'Запрос не выполнен');
|
||||
return data;
|
||||
}
|
||||
function fillSelect(select, rows, valueKey, nameKey, placeholder) {
|
||||
select.replaceChildren();
|
||||
select.append(node('option', placeholder));
|
||||
select.options[0].value = '';
|
||||
for (const row of rows) {
|
||||
const option = node('option', row[nameKey]);
|
||||
option.value = String(row[valueKey]); select.append(option);
|
||||
}
|
||||
}
|
||||
function selectedZone() { return priceZones.find(z => String(z.zone_id) === $('zone').value); }
|
||||
function setUnits(normUnit) {
|
||||
const unit = String(normUnit || '').trim();
|
||||
const match = unit.match(/^(\d+)\s*(.+)$/);
|
||||
const units = match && Number(match[1]) > 1 ? [match[2], unit] : [unit];
|
||||
fillSelect($('unit'), units.filter(Boolean).map(value => ({value, name:value})),
|
||||
'value', 'name', 'Выберите единицу');
|
||||
if (units[0]) $('unit').value = units[0];
|
||||
}
|
||||
function fillPeriods() {
|
||||
fillSelect($('period'), selectedZone()?.periods || [], 'period_id', 'name', 'Выберите квартал');
|
||||
if ($('period').options.length === 2) $('period').selectedIndex = 1;
|
||||
}
|
||||
async function loadPrices() {
|
||||
priceZones = [];
|
||||
fillSelect($('zone'), [], 'zone_id', 'name', 'Выберите зону'); fillPeriods();
|
||||
if (!$('subject').value) return;
|
||||
const data = await api('/api/norm-finder/prices?subject_id=' + encodeURIComponent($('subject').value));
|
||||
priceZones = data.zones || [];
|
||||
fillSelect($('zone'), priceZones, 'zone_id', 'name', 'Выберите зону');
|
||||
if (priceZones.length === 1) { $('zone').selectedIndex = 1; fillPeriods(); }
|
||||
}
|
||||
function key(item) { return [item.base, item.base_type, item.code].join('|'); }
|
||||
function baseAlias(item) { return item.base === 'ФЕР-2020' ? '2020' : '2022'; }
|
||||
function detailUrl(item) {
|
||||
return '/api/norm-finder/detail?' + new URLSearchParams({base:baseAlias(item),
|
||||
base_type:item.base_type, code:item.code});
|
||||
}
|
||||
async function detailFor(item) { return api(detailUrl(item)); }
|
||||
|
||||
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 open = node('button', 'Открыть состав', 'primary small');
|
||||
open.type = 'button'; open.addEventListener('click', () => openDetail(item));
|
||||
const compare = node('button', compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить', 'secondary small');
|
||||
compare.type = 'button';
|
||||
compare.addEventListener('click', async () => {
|
||||
try {
|
||||
if (compared.has(key(item))) compared.delete(key(item));
|
||||
else {
|
||||
if (compared.size >= 3) { status('Сравнить можно не более трёх норм', true); return; }
|
||||
compared.set(key(item), await detailFor(item));
|
||||
}
|
||||
compare.textContent = compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить';
|
||||
renderComparison();
|
||||
} catch (e) { status(e.message, true); }
|
||||
});
|
||||
actions.append(open, compare); card.append(actions);
|
||||
return card;
|
||||
}
|
||||
async function search(event) {
|
||||
event?.preventDefault();
|
||||
const q = $('query').value.trim(), base = $('base').value;
|
||||
if (q.length < 2) { status('Введите хотя бы два символа', true); return; }
|
||||
status('Ищу нормы…');
|
||||
$('results-section').hidden = true; $('detail-section').hidden = true;
|
||||
try {
|
||||
const data = await api('/api/norm-finder/search?' + new URLSearchParams({q,base,limit:'12'}));
|
||||
const items = data.items || [];
|
||||
$('results').replaceChildren(...items.map(renderSearchItem));
|
||||
$('results-section').hidden = !items.length;
|
||||
status(items.length ? 'Показано ' + items.length + ' подходящих норм. Проверьте состав работ перед расчётом.'
|
||||
: (data.message || 'Нормы не найдены. Уточните работу или шифр.'));
|
||||
} catch (e) { status(e.message, true); }
|
||||
}
|
||||
function renderDetail(item) {
|
||||
$('detail-title').textContent = item.code + ' — ' + (item.name || 'Норма');
|
||||
const root = $('detail'); root.replaceChildren();
|
||||
root.append(node('p', item.base + ' · ' + item.base_type + ' · измеритель: ' + (item.unit || '—'), 'meta'));
|
||||
if (item.section_path) root.append(node('p', item.section_path, 'hint'));
|
||||
if (item.content?.length) {
|
||||
root.append(node('h3', 'Состав работ'));
|
||||
const list = node('ol', null, 'list');
|
||||
for (const line of item.content) list.append(node('li', line));
|
||||
root.append(list);
|
||||
}
|
||||
root.append(node('h3', 'Ресурсы'));
|
||||
const scroll = node('div', null, 'scroll');
|
||||
const table = node('table');
|
||||
const thead = node('thead'); const tr = node('tr');
|
||||
for (const label of ['Код','Ресурс','Единица','Расход на измеритель']) tr.append(node('th', label));
|
||||
thead.append(tr); table.append(thead);
|
||||
const tbody = node('tbody');
|
||||
for (const r of item.resources || []) {
|
||||
const row = node('tr');
|
||||
row.append(node('td', r.code || '—'), node('td', r.name || '—'), node('td', r.unit || '—'),
|
||||
node('td', r.quantity_note || (r.quantity ?? 'не задан'), 'num'));
|
||||
tbody.append(row);
|
||||
}
|
||||
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'));
|
||||
if (item.prices?.cost != null) root.append(node('p', 'Базисная стоимость: ' + money(item.prices.cost) +
|
||||
' (уровень ' + (item.price_level || 'не указан') + '). Это не цена выбранного квартала.', 'notice'));
|
||||
}
|
||||
async function openDetail(item) {
|
||||
status('Загружаю состав нормы…');
|
||||
try {
|
||||
active = await detailFor(item); 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'));
|
||||
$('detail-section').hidden = false;
|
||||
$('detail-section').scrollIntoView({behavior:'smooth', block:'start'});
|
||||
status('Состав нормы загружен. Сверьте измеритель и ресурсы.');
|
||||
} catch (e) { status(e.message, true); }
|
||||
}
|
||||
function renderComparison() {
|
||||
$('compare-section').hidden = compared.size === 0;
|
||||
const items = [...compared.values()];
|
||||
const units = new Set(items.map(i => i.unit || ''));
|
||||
$('compare-warning').hidden = units.size < 2;
|
||||
$('compare-warning').textContent = 'Измерители различаются. Сравнение стоимости без явного приведения объёма некорректно.';
|
||||
const cards = items.map(item => {
|
||||
const card = node('article', null, 'card');
|
||||
card.append(node('div', item.code, 'code'), node('h3', item.name),
|
||||
node('p', item.base + ' · ' + item.base_type + ' · ' + (item.unit || 'без измерителя'), 'meta'));
|
||||
if (item.content?.length) card.append(node('p', 'Состав: ' + item.content.join('; '), 'hint'));
|
||||
card.append(node('p', 'Ресурсов: ' + (item.resources || []).length, 'hint'));
|
||||
for (const row of item.resources || []) card.append(node('p', (row.code || '—') + ' · ' +
|
||||
(row.name || '—') + ' · ' + (row.quantity_note || (row.quantity ?? '—')), 'hint'));
|
||||
return card;
|
||||
});
|
||||
$('comparison').replaceChildren(...cards);
|
||||
}
|
||||
function renderQuote(data) {
|
||||
savedQuote = data;
|
||||
const result = data.result || {};
|
||||
const root = $('quote'); root.replaceChildren();
|
||||
root.append(node('p', [result.code, result.quantity != null ? result.quantity + ' ' + (result.unit || '') : '',
|
||||
result.zone, result.period].filter(Boolean).join(' · '), 'meta'));
|
||||
if (result.complete && result.total != null) {
|
||||
root.append(node('p', 'Предварительный итог', 'meta'), node('div', money(result.total), 'result-amount'));
|
||||
} else {
|
||||
root.append(node('p', 'Расчёт неполный — готовую смету по этим данным получить нельзя.', 'notice'));
|
||||
if (result.accounted != null) root.append(node('p', 'Учтённая часть', 'meta'),
|
||||
node('div', money(result.accounted), 'result-amount'));
|
||||
}
|
||||
if (result.message) root.append(node('p', result.message, 'notice'));
|
||||
for (const missing of result.missing || []) root.append(node('p', 'Не рассчитано: ' +
|
||||
(missing.reason || missing.code || 'позиция'), 'hint'));
|
||||
if (result.unpriced?.length) root.append(node('p', 'Часть ресурсов без цены в выбранной форме.', 'hint'));
|
||||
if (result.limits_note) root.append(node('p', result.limits_note, 'hint'));
|
||||
const link = node('a', 'Ссылка на этот расчёт');
|
||||
link.href = '/podbor?quote=' + encodeURIComponent(data.id);
|
||||
root.append(link);
|
||||
}
|
||||
async function calculate() {
|
||||
if (!active) return;
|
||||
const quantity = Number($('qty').value);
|
||||
if (!Number.isFinite(quantity) || quantity <= 0 || !$('qty').checkValidity()
|
||||
|| !$('subject').value || !$('zone').value || !$('period').value) {
|
||||
status('Укажите регион, зону, квартал и положительный объём', true); return;
|
||||
}
|
||||
const selection = {base:baseAlias(active),base_type:active.base_type,code:active.code,
|
||||
quantity,unit:$('unit').value,subject_id:Number($('subject').value),
|
||||
zone_id:Number($('zone').value),period_id:Number($('period').value)};
|
||||
$('calc').disabled = true; status('Считаю по выбранной форме…');
|
||||
try {
|
||||
const path = savedQuote ? '/api/norm-finder/quotes/' + savedQuote.id : '/api/norm-finder/calculate';
|
||||
const body = {...selection, ...(savedQuote ? {revision:savedQuote.revision} : {})};
|
||||
const data = await api(path, {method:'POST', body:JSON.stringify(body)});
|
||||
renderQuote(data);
|
||||
history.replaceState(null, '', '/podbor?quote=' + encodeURIComponent(data.id));
|
||||
status('Расчёт обновлён в этой карточке.');
|
||||
} catch (e) { status(e.message, true); }
|
||||
finally { $('calc').disabled = false; }
|
||||
}
|
||||
function toChat() {
|
||||
if (!active) return;
|
||||
const prompt = 'Посчитай ' + ($('qty').value || '1') + ' ' + ($('unit').value || active.unit || '') +
|
||||
' по норме ' + active.base_type + ' ' + active.code +
|
||||
(selectedZone() && $('period').value ? ', ' + selectedZone().name + ', ' +
|
||||
$('period').selectedOptions[0].textContent : '') + '. Проверь состав ресурсов.';
|
||||
try { localStorage.setItem('draft_' + tabId, prompt); }
|
||||
catch { status('Не удалось сохранить черновик для чата', true); return; }
|
||||
location.href = '/';
|
||||
}
|
||||
async function restoreQuote() {
|
||||
const id = Number(new URLSearchParams(location.search).get('quote'));
|
||||
if (!Number.isSafeInteger(id) || id < 1) return;
|
||||
try {
|
||||
const data = await api('/api/norm-finder/quotes/' + id);
|
||||
const selection = data.selection || {};
|
||||
active = await detailFor({base:selection.base === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022',
|
||||
base_type:selection.base_type, code:selection.code});
|
||||
renderDetail(active); $('detail-section').hidden = false;
|
||||
$('calc').disabled = !active.current_price_supported;
|
||||
$('qty').value = String(selection.quantity); setUnits(active.unit); $('unit').value = selection.unit;
|
||||
$('subject').value = String(selection.subject_id);
|
||||
await loadPrices(); $('zone').value = String(selection.zone_id); fillPeriods();
|
||||
$('period').value = String(selection.period_id); renderQuote(data);
|
||||
status('Сохранённый расчёт загружен.');
|
||||
} catch (e) { status(e.message, true); }
|
||||
}
|
||||
async function init() {
|
||||
if (!token || !subject) { $('auth-notice').hidden = false; $('search-form').hidden = true; return; }
|
||||
try {
|
||||
const data = await api('/api/norm-finder/catalog');
|
||||
const bases = [...new Set((data.bases || []).map(x => x.base))];
|
||||
fillSelect($('base'), bases.map(b => ({id:b === 'ФЕР-2020' ? '2020' : '2022',name:b})),
|
||||
'id', 'name', 'Выберите базу');
|
||||
if (bases.length) $('base').selectedIndex = 1;
|
||||
subjects = data.subjects || [];
|
||||
fillSelect($('subject'), subjects, 'id', 'name', 'Выберите регион');
|
||||
if (!bases.length) status('Нормативная база пока недоступна', true);
|
||||
await restoreQuote();
|
||||
} catch (e) { status(e.message, true); }
|
||||
}
|
||||
$('search-form').addEventListener('submit', search);
|
||||
document.querySelectorAll('[data-query]').forEach(button => button.addEventListener('click', () => {
|
||||
$('query').value = button.dataset.query; $('search-form').requestSubmit();
|
||||
}));
|
||||
$('subject').addEventListener('change', () => loadPrices().catch(e => status(e.message, true)));
|
||||
$('zone').addEventListener('change', fillPeriods);
|
||||
for (const id of ['subject', 'zone', 'period', 'qty', 'unit']) {
|
||||
$(id).addEventListener('change', () => {
|
||||
if (savedQuote) status('Параметры изменены. Нажмите «Рассчитать», чтобы обновить сумму.');
|
||||
});
|
||||
}
|
||||
$('calc').addEventListener('click', calculate);
|
||||
$('to-chat').addEventListener('click', toChat);
|
||||
init();
|
||||
})();
|
||||
@@ -98,6 +98,7 @@ def test_generic_words_not_required(works_db):
|
||||
assert w["base_type"] == "ГЭСНм"
|
||||
assert w["unit"] == "шт"
|
||||
assert w["price_level"] == "01.01.2022"
|
||||
assert w["provenance"]["decree"] == "приказ (тест)"
|
||||
|
||||
|
||||
def test_all_generic_is_empty(works_db):
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Source-backed norm search and price preview."""
|
||||
import pytest
|
||||
import importlib
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
def test_search_rejects_empty_query_and_uses_existing_fsnb(monkeypatch):
|
||||
import fsnb_ref
|
||||
import norm_finder
|
||||
|
||||
seen = []
|
||||
def find(*, query, base, limit):
|
||||
seen.append((query, base, limit))
|
||||
return {"status": "ok", "works": [{"code": "10-08-002-02", "name": "Извещатель",
|
||||
"unit": "шт.", "base": "ГЭСН-2022", "base_type": "ГЭСНм"}]}
|
||||
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
||||
with pytest.raises(ValueError):
|
||||
norm_finder.search(" ", "2022", 12)
|
||||
found = norm_finder.search("извещатель", "2022", 12)
|
||||
assert found["items"][0]["code"] == "10-08-002-02"
|
||||
assert found["items"][0]["match_reason"].startswith("Совпали слова")
|
||||
assert seen == [("извещатель", "2022", 12)]
|
||||
|
||||
|
||||
def test_search_falls_back_to_subject_term_and_ranks_relevant_work(monkeypatch):
|
||||
import fsnb_ref
|
||||
import norm_finder
|
||||
def find(*, query, base, limit):
|
||||
if query == "устройство стяжки пола":
|
||||
return {"status": "not_found"}
|
||||
assert query == "стяжки"
|
||||
return {"status": "ok", "works": [
|
||||
{"code": "06-12-001-04", "name": "Заполнение откосов со стяжкой",
|
||||
"section_path": "Элеваторы", "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "м3"},
|
||||
{"code": "11-01-011-02", "name": "Устройство стяжек пола",
|
||||
"section_path": "Полы", "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "100 м2"},
|
||||
]}
|
||||
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
||||
monkeypatch.setattr(fsnb_ref, "count_works", lambda word: {"стяжки": 30, "пола": 200}.get(word, 1000))
|
||||
rows = norm_finder.search("устройство стяжки пола", "2022", 12)["items"]
|
||||
assert rows[0]["code"] == "11-01-011-02"
|
||||
|
||||
|
||||
def test_detail_requires_exact_base_type_and_code(monkeypatch):
|
||||
import fsnb_ref
|
||||
import norm_finder
|
||||
|
||||
def composition(*, query, base, limit):
|
||||
return {"status": "ok", "results": [
|
||||
{"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": query,
|
||||
"name": "Другая норма", "unit": "м2", "resources": []},
|
||||
{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": query,
|
||||
"name": "Извещатель", "unit": "шт.", "resources": [{"code": "1-100-40", "quantity": 1}],
|
||||
"provenance": {"decree": "Приказ"}},
|
||||
]}
|
||||
monkeypatch.setattr(fsnb_ref, "find_gesn_composition", composition)
|
||||
item = norm_finder.detail("2022", "ГЭСНм", "10-08-002-02")
|
||||
assert item["name"] == "Извещатель"
|
||||
assert item["provenance"]["decree"] == "Приказ"
|
||||
assert item["current_price_supported"] is True
|
||||
with pytest.raises(ValueError):
|
||||
norm_finder.detail("2022", "ГЭСНр", "10-08-002-02")
|
||||
|
||||
|
||||
def test_calculation_refuses_unpriced_norm_instead_of_fabricating_total(monkeypatch):
|
||||
import norm_finder
|
||||
|
||||
monkeypatch.setattr(norm_finder, "detail", lambda *args: {
|
||||
"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": "10-08-002-02",
|
||||
"name": "Извещатель", "unit": "шт.", "resources": [
|
||||
{"code": "91.01.01-001", "name": "Машина", "unit": "маш.-ч", "quantity": 1}],
|
||||
})
|
||||
with pytest.raises(ValueError, match="не поддерживается"):
|
||||
norm_finder.calculate("2022", "ГЭСНм", "10-08-002-02", 100, "шт.",
|
||||
"Хабаровский край (1 зона)", "4 квартал 2026")
|
||||
|
||||
|
||||
def test_gesn_quantity_uses_base_unit_and_engine_resource_key(monkeypatch):
|
||||
import norm_finder
|
||||
import engine_prices
|
||||
import estimate_contract as ec
|
||||
monkeypatch.setattr(norm_finder, "detail", lambda *args: {
|
||||
"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": "11-01-049-01",
|
||||
"name": "Порог", "unit": "100 м", "resources": [
|
||||
{"code": "1-100-40", "name": "Рабочий", "unit": "чел.-ч", "quantity": 1}],
|
||||
})
|
||||
monkeypatch.setattr(engine_prices, "resolve", lambda meta: {"status": "ok", "entry": {}})
|
||||
monkeypatch.setattr(engine_prices, "load_lookup", lambda entry: object())
|
||||
seen = []
|
||||
def fake_calc(draft, resources, prices, basis):
|
||||
seen.append((draft.positions[0].qty, sorted(resources)))
|
||||
return {"status": "ok", "ok": False, "grand_total": 10.0,
|
||||
"missing": [{"reason": "НР/СП"}], "unpriced": []}
|
||||
monkeypatch.setattr(ec, "build_and_calc", fake_calc)
|
||||
result = norm_finder.calculate("2022", "ГЭСН", "11-01-049-01", 50, "м",
|
||||
"Хабаровский край (1 зона)", "4 квартал 2026")
|
||||
assert seen == [(0.5, ["11-01-049-01"])]
|
||||
assert result["total"] is None and result["accounted"] == 10.0
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def api(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "finder.db"))
|
||||
monkeypatch.setenv("SESSION_SECRET", "finder-test-secret")
|
||||
import auth
|
||||
import db
|
||||
import main
|
||||
for module in (db, auth, main):
|
||||
importlib.reload(module)
|
||||
db.init_db()
|
||||
db.create_user("finder@x", auth.hash_password("Passw0rd!ok"))
|
||||
db.admin_verify_user("finder@x")
|
||||
headers = {"Authorization": "Bearer " + auth._make_token("finder@x"), "X-Tab-Id": "tab"}
|
||||
return TestClient(main.app), headers, db
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method,path", [
|
||||
("get", "/api/norm-finder/catalog"),
|
||||
("get", "/api/norm-finder/search?q=извещатель&base=2022"),
|
||||
("get", "/api/norm-finder/detail?base=2022&base_type=ГЭСНм&code=10-08-002-02"),
|
||||
("get", "/api/norm-finder/prices?subject_id=264"),
|
||||
("post", "/api/norm-finder/calculate"),
|
||||
("get", "/api/norm-finder/quotes/1"),
|
||||
("post", "/api/norm-finder/quotes/1"),
|
||||
])
|
||||
def test_finder_requires_login(api, method, path):
|
||||
client, _, _ = api
|
||||
assert getattr(client, method)(path).status_code == 401
|
||||
|
||||
|
||||
def test_finder_api_search_detail_and_catalog(api, monkeypatch):
|
||||
import norm_finder
|
||||
client, headers, _ = api
|
||||
monkeypatch.setattr(norm_finder, "catalog", lambda: [{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "count": 100}])
|
||||
monkeypatch.setattr(norm_finder, "search", lambda q, b, limit: {"status": "ok", "items": [
|
||||
{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": "10-08-002-02", "name": "Извещатель", "unit": "шт."}]})
|
||||
monkeypatch.setattr(norm_finder, "detail", lambda b, t, c: {"base": "ГЭСН-2022", "base_type": t,
|
||||
"code": c, "name": "Извещатель", "unit": "шт.", "resources": [], "provenance": {"decree": "Приказ"}})
|
||||
assert client.get("/api/norm-finder/catalog", headers=headers).json()["bases"][0]["count"] == 100
|
||||
found = client.get("/api/norm-finder/search?q=извещатель&base=2022", headers=headers)
|
||||
assert found.status_code == 200 and found.json()["items"][0]["code"] == "10-08-002-02"
|
||||
detail = client.get("/api/norm-finder/detail?base=2022&base_type=ГЭСНм&code=10-08-002-02", headers=headers)
|
||||
assert detail.status_code == 200 and detail.json()["provenance"]["decree"] == "Приказ"
|
||||
|
||||
|
||||
def test_finder_quote_is_saved_and_revised_in_place(api, monkeypatch):
|
||||
import norm_finder
|
||||
import engine_prices
|
||||
client, headers, db = api
|
||||
monkeypatch.setattr(engine_prices, "basis_options", lambda sid: [
|
||||
{"zone_id": 118, "name": "Хабаровский край (1 зона)",
|
||||
"periods": [{"period_id": 428, "name": "4 квартал 2026"}]}] if sid == 264 else [])
|
||||
monkeypatch.setattr(norm_finder, "calculate", lambda b, t, c, q, u, z, p: {
|
||||
"status": "ok", "complete": False, "accounted": q * 100,
|
||||
"base": "ГЭСН-2022", "base_type": t, "code": c, "quantity": q,
|
||||
"unit": u, "zone": z, "period": p, "missing": [{"reason": "НР/СП"}]})
|
||||
body = {"base": "2022", "base_type": "ГЭСНм", "code": "10-08-002-02",
|
||||
"quantity": 100, "unit": "шт.", "subject_id": 264, "zone_id": 118, "period_id": 428}
|
||||
assert client.post("/api/norm-finder/calculate", json={**body, "period_id": 999}, headers=headers).status_code == 400
|
||||
created = client.post("/api/norm-finder/calculate", json=body, headers=headers)
|
||||
assert created.status_code == 200, created.text
|
||||
quote = created.json()
|
||||
assert quote["result"]["accounted"] == 10000
|
||||
assert db.get_history("finder@x", "tab")[-1]["role"] == "norm_quote"
|
||||
url = f"/api/norm-finder/quotes/{quote['id']}"
|
||||
import auth
|
||||
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
|
||||
db.admin_verify_user("other@x")
|
||||
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "tab"}
|
||||
assert client.get(url, headers=other).status_code == 404
|
||||
assert client.post(url, json={**body, "revision": 0}, headers=other).status_code == 404
|
||||
assert client.get(url, headers=headers).json()["result"]["accounted"] == 10000
|
||||
updated = client.post(url, json={**body, "quantity": 75, "revision": quote["revision"]}, headers=headers)
|
||||
assert updated.status_code == 200 and updated.json()["id"] == quote["id"]
|
||||
assert updated.json()["result"]["accounted"] == 7500
|
||||
assert client.post(url, json={**body, "quantity": 50, "revision": quote["revision"]}, headers=headers).status_code == 409
|
||||
|
||||
|
||||
def test_finder_page_is_reachable_from_site(api):
|
||||
client, _, _ = api
|
||||
page = client.get("/podbor")
|
||||
assert page.status_code == 200
|
||||
assert "Подбор норм" in page.text
|
||||
assert 'src="/static/norm-finder.js"' in page.text
|
||||
assert "/podbor" in client.get("/").text
|
||||
Reference in New Issue
Block a user