Implement source-backed norm finder and saved price previews
This commit is contained in:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user