Add source-linked inline comparison for uploaded estimates
This commit is contained in:
@@ -2013,6 +2013,19 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
|
||||
save_message(user, tab_id, "spend",
|
||||
json.dumps(_spend_payload["answer"], ensure_ascii=False))
|
||||
_maybe_autotitle(user, tab_id, message)
|
||||
# A file comparison belongs to the answer that requested it. Store only
|
||||
# source selections; rows are reread from the user's current work folder.
|
||||
if assistant_message_id and not errored:
|
||||
import inline_compare
|
||||
compare_mode = inline_compare.detect_mode(message)
|
||||
if compare_mode:
|
||||
compare_data = {"_assistant_id": assistant_message_id, "_revision": 0,
|
||||
"mode": compare_mode, "left": None, "right": None,
|
||||
"choices": {}, "price_fields": {}}
|
||||
compare_id = save_message(user, tab_id, "file_compare",
|
||||
json.dumps(compare_data, ensure_ascii=False))
|
||||
compare_data["_message_id"] = compare_id
|
||||
yield f"event: file_compare\ndata: {json.dumps(compare_data, ensure_ascii=False)}\n\n"
|
||||
# Структурированная смета от агента (tool show_estimate пишет _estimate_panel.json) →
|
||||
# событие estimate + панель. Файл читаем, эмитим, удаляем (не в кнопки, не повторно).
|
||||
est_file = work_dir / "_estimate_panel.json"
|
||||
@@ -2500,6 +2513,121 @@ async def norm_finder_recalculate(quote_id: int, request: Request):
|
||||
return {"id": quote_id, **updated}
|
||||
|
||||
|
||||
@app.get("/api/file-compare/workbooks")
|
||||
async def file_compare_workbooks(request: Request):
|
||||
user, tab_id = _get_user(request), _get_tab(request)
|
||||
from path_safety import safe_work_dir
|
||||
import inline_compare
|
||||
folder = safe_work_dir(user, tab_id, create=False)
|
||||
return {"workbooks": await asyncio.to_thread(inline_compare.list_workbooks, folder)}
|
||||
|
||||
|
||||
def _file_compare_state(folder: Path, data: dict, page: int = 0) -> dict:
|
||||
import inline_compare
|
||||
left, right = data.get("left"), data.get("right")
|
||||
if not left or not right:
|
||||
return {"comparison": None, "page": 0}
|
||||
for selected in (left, right):
|
||||
if inline_compare.file_fingerprint(folder, selected["file"]) != selected["fingerprint"]:
|
||||
raise HTTPException(409, "Исходный файл изменился — выберите файлы заново")
|
||||
mode = data["mode"]
|
||||
roles = {"ka_lsr": ("ka", "lsr"), "vor_lsr": ("vor", "lsr"), "ka_kp": ("ka", "kp")}
|
||||
left_table = inline_compare.read_table(folder, left["file"], left["sheet"], roles[mode][0])
|
||||
right_table = inline_compare.read_table(folder, right["file"], right["sheet"], roles[mode][1])
|
||||
if (left_table["fingerprint"] != left["fingerprint"] or
|
||||
right_table["fingerprint"] != right["fingerprint"]):
|
||||
raise HTTPException(409, "Исходный файл изменился во время чтения")
|
||||
choices = {int(k): v for k, v in data.get("choices", {}).items()}
|
||||
fields = {int(k): v for k, v in data.get("price_fields", {}).items()}
|
||||
compared = inline_compare.compare(left_table, right_table, mode,
|
||||
choices=choices, price_fields=fields)
|
||||
all_rows = compared["rows"]
|
||||
compared["rows"] = all_rows[page * 50:(page + 1) * 50]
|
||||
compared["total_rows"] = len(all_rows)
|
||||
compared["unmatched"] = sum(row["difference"] is None for row in all_rows)
|
||||
compared["left"].pop("rows")
|
||||
compared["right"].pop("rows")
|
||||
return {"comparison": compared, "page": page}
|
||||
|
||||
|
||||
@app.get("/api/file-compare/{compare_id}")
|
||||
async def file_compare_get(compare_id: int, request: Request, page: int = 0):
|
||||
user, tab_id = _get_user(request), _get_tab(request)
|
||||
from path_safety import safe_work_dir
|
||||
saved = await asyncio.to_thread(db.get_linked_file_compare, user, tab_id, compare_id)
|
||||
if saved is None:
|
||||
raise HTTPException(404, "Сверка этого диалога не найдена")
|
||||
if not 0 <= page <= 99:
|
||||
raise HTTPException(400, "Недопустимая страница")
|
||||
try:
|
||||
state = await asyncio.to_thread(_file_compare_state,
|
||||
safe_work_dir(user, tab_id, create=False),
|
||||
saved["data"], page)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
return {"id": compare_id, **saved["data"], **state}
|
||||
|
||||
|
||||
@app.post("/api/file-compare/{compare_id}")
|
||||
async def file_compare_update(compare_id: int, request: Request):
|
||||
user, tab_id = _get_user(request), _get_tab(request)
|
||||
from path_safety import safe_work_dir
|
||||
import inline_compare
|
||||
body = await _тело(request)
|
||||
saved = await asyncio.to_thread(db.get_linked_file_compare, user, tab_id, compare_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, "Сверка изменена в другой вкладке — обновите страницу")
|
||||
folder = safe_work_dir(user, tab_id, create=False)
|
||||
updated = dict(current)
|
||||
source_changed = False
|
||||
try:
|
||||
for side in ("left", "right"):
|
||||
if side in body:
|
||||
src = body[side]
|
||||
if not isinstance(src, dict) or not all(isinstance(src.get(k), str)
|
||||
for k in ("file", "sheet")):
|
||||
raise ValueError("Выберите файл и лист")
|
||||
available = inline_compare.list_workbooks(folder)
|
||||
if not any(w["filename"] == src["file"] and src["sheet"] in w["sheets"]
|
||||
for w in available):
|
||||
raise ValueError("Файл или лист отсутствует в рабочей папке")
|
||||
selected = {"file": src["file"], "sheet": src["sheet"],
|
||||
"fingerprint": inline_compare.file_fingerprint(folder, src["file"])}
|
||||
source_changed |= selected != current.get(side)
|
||||
updated[side] = selected
|
||||
if source_changed:
|
||||
updated["choices"], updated["price_fields"] = {}, {}
|
||||
else:
|
||||
for key in ("choices", "price_fields"):
|
||||
if key in body:
|
||||
raw = body[key]
|
||||
if not isinstance(raw, dict) or len(raw) > inline_compare.MAX_ROWS:
|
||||
raise ValueError("Недопустимый выбор строк")
|
||||
parsed = {}
|
||||
for index, value in raw.items():
|
||||
if not str(index).isdigit() or int(index) >= inline_compare.MAX_ROWS:
|
||||
raise ValueError("Недопустимый номер строки")
|
||||
if key == "choices" and (not isinstance(value, int) or isinstance(value, bool)):
|
||||
raise ValueError("Недопустимое сопоставление")
|
||||
if key == "price_fields" and not isinstance(value, str):
|
||||
raise ValueError("Недопустимый столбец")
|
||||
parsed[str(index)] = value
|
||||
updated[key] = parsed
|
||||
state = await asyncio.to_thread(_file_compare_state, folder, updated)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
updated["_revision"] = revision + 1
|
||||
changed = await asyncio.to_thread(db.replace_linked_file_compare, user, tab_id, compare_id,
|
||||
saved["raw"], json.dumps(updated, ensure_ascii=False))
|
||||
if not changed:
|
||||
raise HTTPException(409, "Сверка изменена в другой вкладке — обновите страницу")
|
||||
return {"id": compare_id, **updated, **state}
|
||||
|
||||
|
||||
@app.post("/api/recalc")
|
||||
async def recalc(request: Request):
|
||||
"""Пересчитать смету движком по правкам объёмов (срез 6.2). Числа — из движка, не из JS.
|
||||
|
||||
Reference in New Issue
Block a user