Add inline price basis switching to saved estimate answers
This commit is contained in:
@@ -555,7 +555,7 @@ MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||
APP_VERSION = "2026-12-02c"
|
||||
APP_VERSION = "2026-12-02d"
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
@@ -1995,8 +1995,9 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
|
||||
# был бы уже вторым и диалог остался бы без стабильного имени.
|
||||
_maybe_autotitle(user, tab_id, message)
|
||||
return
|
||||
assistant_message_id = None
|
||||
if full_response:
|
||||
save_message(user, tab_id, "assistant", full_response)
|
||||
assistant_message_id = save_message(user, tab_id, "assistant", full_response)
|
||||
# Цена ответа — отдельной записью СРАЗУ за ответом: так она переживает
|
||||
# обновление страницы. В память диалога эта роль не попадает (chat_context
|
||||
# берёт только реплики), иначе модель начала бы отвечать на цену.
|
||||
@@ -2011,8 +2012,13 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
|
||||
try:
|
||||
est_data = json.loads(est_file.read_text(encoding="utf-8"))
|
||||
if isinstance(est_data, dict) and est_data.get("positions"):
|
||||
save_message(user, tab_id, "estimate", json.dumps(est_data, ensure_ascii=False))
|
||||
yield f"event: estimate\ndata: {json.dumps(est_data, ensure_ascii=False)}\n\n"
|
||||
if assistant_message_id:
|
||||
est_data["_assistant_id"] = assistant_message_id
|
||||
est_data["_revision"] = 0
|
||||
estimate_message_id = save_message(
|
||||
user, tab_id, "estimate", json.dumps(est_data, ensure_ascii=False))
|
||||
event_data = {**est_data, "_message_id": estimate_message_id}
|
||||
yield f"event: estimate\ndata: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
@@ -2398,6 +2404,87 @@ async def recalc(request: Request):
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/estimates/{estimate_id}/basis")
|
||||
async def estimate_basis_options(estimate_id: int, request: Request):
|
||||
user = _get_user(request)
|
||||
tab_id = _get_tab(request)
|
||||
saved = await asyncio.to_thread(db.get_linked_estimate, user, tab_id, estimate_id)
|
||||
if saved is None:
|
||||
raise HTTPException(404, "Смета этого диалога не найдена")
|
||||
import engine_prices
|
||||
subject_id = (saved.get("applied") or {}).get("subject_id")
|
||||
if not isinstance(subject_id, int) or isinstance(subject_id, bool):
|
||||
raise HTTPException(400, "У этой сметы не указана ценовая база")
|
||||
zones = await asyncio.to_thread(engine_prices.basis_options, subject_id)
|
||||
if not zones:
|
||||
raise HTTPException(400, "Для этой сметы нет доступных ценовых форм")
|
||||
return {"zones": zones, "revision": saved.get("_revision", 0)}
|
||||
|
||||
|
||||
@app.post("/api/estimates/{estimate_id}/basis")
|
||||
async def change_estimate_basis(estimate_id: int, request: Request):
|
||||
"""Recalculate and replace the same answer; never accept prices from the browser."""
|
||||
user = _get_user(request)
|
||||
tab_id = _get_tab(request)
|
||||
body = await _тело(request)
|
||||
zone_id, period_id, revision = (body.get(key) for key in
|
||||
("zone_id", "period_id", "revision"))
|
||||
if any(not isinstance(value, int) or isinstance(value, bool) or value < 0
|
||||
for value in (zone_id, period_id, revision)):
|
||||
raise HTTPException(400, "Укажите зону, квартал и версию ответа")
|
||||
saved = await asyncio.to_thread(db.get_linked_estimate, user, tab_id, estimate_id)
|
||||
if saved is None:
|
||||
raise HTTPException(404, "Смета этого диалога не найдена")
|
||||
if saved.get("_revision", 0) != revision:
|
||||
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
|
||||
import engine_prices
|
||||
import estimate_contract as ec
|
||||
import estimate_interactive as ei
|
||||
if not ec.engine_enabled():
|
||||
raise HTTPException(400, "Расчётный движок выключен")
|
||||
subject_id = (saved.get("applied") or {}).get("subject_id")
|
||||
if not isinstance(subject_id, int) or isinstance(subject_id, bool):
|
||||
raise HTTPException(400, "У этой сметы не указана ценовая база")
|
||||
zones = await asyncio.to_thread(engine_prices.basis_options, subject_id)
|
||||
selected = ei.selected_form(zones, zone_id, period_id)
|
||||
if selected is None:
|
||||
raise HTTPException(400, "Выбранной ценовой формы нет в каталоге")
|
||||
zone, period = selected
|
||||
try:
|
||||
positions = ei.positions_for_revision(saved, body.get("positions"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
subject = (saved.get("applied") or {}).get("subject")
|
||||
meta = {"region": subject, "zone": zone["name"], "price_level": period["name"]}
|
||||
result = await asyncio.to_thread(ec.calc_estimate, positions, meta)
|
||||
if result.get("status") != "ok":
|
||||
raise HTTPException(400, result.get("message") or "Не удалось пересчитать смету")
|
||||
applied = result.get("applied") or {}
|
||||
if applied.get("zone_id") != zone_id or applied.get("period_id") != period_id:
|
||||
raise HTTPException(409, "Ценовая база изменилась — обновите диалог")
|
||||
try:
|
||||
answer = ei.revised_answer(result)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
updated = {
|
||||
"title": saved.get("title") or "Смета (пересчёт)",
|
||||
"positions": [{"code": p.get("code"), "name": p.get("name"), "unit": p.get("unit"),
|
||||
"qty": p.get("qty"), "total": p.get("total")}
|
||||
for p in result.get("positions", [])],
|
||||
"totals": {"grand_total": result["grand_total"]},
|
||||
"ok": result.get("ok"), "missing": result.get("missing"),
|
||||
"applied": applied, "unpriced": result.get("unpriced"),
|
||||
"limits_note": result.get("limits_note"), "meta": ec.recalc_meta(applied),
|
||||
}
|
||||
outcome = await asyncio.to_thread(db.replace_linked_estimate, user, tab_id,
|
||||
estimate_id, revision, updated, answer)
|
||||
if outcome == "stale":
|
||||
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
|
||||
if outcome != "ok":
|
||||
raise HTTPException(404, "Смета этого диалога не найдена")
|
||||
return {"answer": answer, "estimate": {**updated, "_message_id": estimate_id}}
|
||||
|
||||
|
||||
@app.delete("/api/sessions/{tab_id}")
|
||||
async def delete_session_ep(tab_id: str, request: Request):
|
||||
"""Удалить свой диалог ЦЕЛИКОМ (история в БД + загруженные файлы на диске).
|
||||
|
||||
Reference in New Issue
Block a user