Revise plain estimate answers from inline price zones

This commit is contained in:
anor
2026-12-02 23:21:25 +10:00
parent 2a3cdf8bd8
commit d908d183d5
8 changed files with 534 additions and 28 deletions
+75 -1
View File
@@ -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-02d"
APP_VERSION = "2026-12-02e"
# Audit: path → action name mapping
_AUDIT_MAP = [
@@ -1998,6 +1998,8 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
assistant_message_id = None
if full_response:
assistant_message_id = save_message(user, tab_id, "assistant", full_response)
yield ("event: assistant_id\ndata: "
+ json.dumps({"id": assistant_message_id}) + "\n\n")
# Цена ответа — отдельной записью СРАЗУ за ответом: так она переживает
# обновление страницы. В память диалога эта роль не попадает (chat_context
# берёт только реплики), иначе модель начала бы отвечать на цену.
@@ -2421,6 +2423,78 @@ async def estimate_basis_options(estimate_id: int, request: Request):
return {"zones": zones, "revision": saved.get("_revision", 0)}
async def _generate_freeform_basis_answer(user: str, tab_id: str, question: str,
old_answer: str, zone: str, period: str) -> dict:
"""Strict recalculation; never substitute an LLM's guessed price for a form."""
import answer_basis
try:
answer = await asyncio.to_thread(answer_basis.calculate_plain,
question, old_answer, zone, period)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
return {"answer": answer, "usage": {}, "provider": "estimate-engine", "model": ""}
@app.get("/api/messages/{message_id}/basis")
async def freeform_basis_options(message_id: int, request: Request, label: str = ""):
user, tab_id = _get_user(request), _get_tab(request)
saved = await asyncio.to_thread(db.get_scoped_assistant, user, tab_id, message_id)
if saved is None:
raise HTTPException(404, "Ответ этого диалога не найден")
import answer_basis
try:
zones, _ = await asyncio.to_thread(answer_basis.options_for_label, saved["content"], label)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
return {"zones": zones, "revision": answer_basis.revision(saved["content"])}
@app.post("/api/messages/{message_id}/basis")
async def change_freeform_basis(message_id: int, request: Request):
"""Regenerate one plain answer in place after an explicit price basis choice."""
user, tab_id = _get_user(request), _get_tab(request)
body = await _тело(request)
label, token = body.get("label"), body.get("revision")
zone_id, period_id = body.get("zone_id"), body.get("period_id")
if (not isinstance(label, str) or not isinstance(token, str)
or any(not isinstance(value, int) or isinstance(value, bool) or value < 0
for value in (zone_id, period_id))):
raise HTTPException(400, "Укажите ценовую зону, квартал и версию ответа")
saved = await asyncio.to_thread(db.get_scoped_assistant, user, tab_id, message_id)
if saved is None:
raise HTTPException(404, "Ответ этого диалога не найден")
import answer_basis
import estimate_interactive
if answer_basis.revision(saved["content"]) != token:
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
try:
zones, _ = await asyncio.to_thread(answer_basis.options_for_label, saved["content"], label)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
selected = estimate_interactive.selected_form(zones, zone_id, period_id)
if selected is None:
raise HTTPException(400, "Выбранной ценовой формы нет в каталоге")
zone, period = selected
safe_work_dir(user, tab_id, create=False)
_check_rate_limit(user)
_refuse_if_read_only(user)
_refuse_if_trial_over(user)
await _check_limits(user, tab_id)
log_action(user, "chat", "POST", f"/api/messages/{message_id}/basis",
f"tab={tab_id}; zone={zone_id}; period={period_id}", _client_ip(request) or None, 200)
try:
generated = await asyncio.wait_for(
_generate_freeform_basis_answer(user, tab_id, saved["question"], saved["content"],
zone["name"], period["name"]), timeout=180)
except TimeoutError as exc:
raise HTTPException(504, "Пересчёт не завершился — прежний ответ сохранён") from exc
changed = await asyncio.to_thread(db.replace_scoped_assistant, user, tab_id, message_id,
saved["content"], generated["answer"])
if not changed:
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
return {"answer": generated["answer"]}
@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."""