Add inline price basis switching to saved estimate answers
This commit is contained in:
@@ -579,11 +579,12 @@ def init_db():
|
||||
def save_message(username: str, tab_id: str, role: str, content: str):
|
||||
"""Save a user or assistant message."""
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
cursor = conn.execute(
|
||||
"INSERT INTO messages (session_id, username, tab_id, role, content, timestamp) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(f"{username}/{tab_id}", username, tab_id, role, content, time.time()),
|
||||
)
|
||||
return cursor.lastrowid
|
||||
|
||||
|
||||
HISTORY_LIMIT = 2000 # потолок выдачи истории: длинные переписки нужны целиком
|
||||
@@ -601,7 +602,7 @@ def get_history(username: str, tab_id: str, limit: int = HISTORY_LIMIT,
|
||||
(проверено на всех 1299 диалогах боевой базы 09.09.2026), но записи, добавленные задним
|
||||
числом — цена под старым ответом, — обязаны вставать на своё место, а не в конец
|
||||
диалога."""
|
||||
sql = "SELECT role, content, timestamp FROM messages WHERE username = ? AND tab_id = ?"
|
||||
sql = "SELECT id, role, content, timestamp FROM messages WHERE username = ? AND tab_id = ?"
|
||||
args: list = [username, tab_id]
|
||||
if roles:
|
||||
sql += " AND role IN (" + ",".join("?" * len(roles)) + ")"
|
||||
@@ -613,6 +614,68 @@ def get_history(username: str, tab_id: str, limit: int = HISTORY_LIMIT,
|
||||
return [dict(r) for r in reversed(rows)]
|
||||
|
||||
|
||||
def get_linked_estimate(username: str, tab_id: str, estimate_id: int) -> dict | None:
|
||||
"""Return an estimate only when its answer belongs to the same user's dialog."""
|
||||
import json
|
||||
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? AND role='estimate'",
|
||||
(estimate_id, username, tab_id),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(row["content"])
|
||||
assistant_id = data.get("_assistant_id")
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
return None
|
||||
if not isinstance(assistant_id, int) or isinstance(assistant_id, bool):
|
||||
return None
|
||||
answer = conn.execute(
|
||||
"SELECT id FROM messages WHERE id=? AND username=? AND tab_id=? AND role='assistant'",
|
||||
(assistant_id, username, tab_id),
|
||||
).fetchone()
|
||||
return data if answer else None
|
||||
|
||||
|
||||
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."""
|
||||
import json
|
||||
|
||||
with _conn() as conn:
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
row = conn.execute(
|
||||
"SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? AND role='estimate'",
|
||||
(estimate_id, username, tab_id),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return "missing"
|
||||
try:
|
||||
current = json.loads(row["content"])
|
||||
assistant_id = current.get("_assistant_id")
|
||||
revision = current.get("_revision", 0)
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
return "missing"
|
||||
if not isinstance(assistant_id, int) or isinstance(assistant_id, bool):
|
||||
return "missing"
|
||||
if revision != expected_revision:
|
||||
return "stale"
|
||||
answer_row = conn.execute(
|
||||
"SELECT id FROM messages WHERE id=? AND username=? AND tab_id=? AND role='assistant'",
|
||||
(assistant_id, username, tab_id),
|
||||
).fetchone()
|
||||
if not answer_row:
|
||||
return "missing"
|
||||
data["_assistant_id"] = assistant_id
|
||||
data["_revision"] = expected_revision + 1
|
||||
conn.execute("UPDATE messages SET content=? WHERE id=?", (answer, assistant_id))
|
||||
conn.execute("UPDATE messages SET content=? WHERE id=?",
|
||||
(json.dumps(data, ensure_ascii=False), estimate_id))
|
||||
return "ok"
|
||||
|
||||
|
||||
def clear_history(username: str, tab_id: str):
|
||||
"""Delete chat messages for one tab — backs the explicit reset action.
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Интерактивная ценовая основа сметы
|
||||
|
||||
Проверяемые критерии:
|
||||
|
||||
1. В новом структурированном ответе сметы выбор зоны и квартала находится внутри того же пузыря ответа; при выборе сервер пересчитывает зависимые числа и заменяет содержимое этого пузыря без нового сообщения.
|
||||
2. Доступны только реально собранные формы выбранного субъекта. Пустая/недоступная форма, чужой диалог и устаревшая ревизия не меняют сохранённый ответ.
|
||||
3. Изменённый ответ и основа расчёта сохраняются вместе и правильно восстанавливаются после перезагрузки истории. Старые ответы без привязки остаются читаемыми.
|
||||
4. Никакой клиентский пересчёт сумм: числа берутся из `estimate_contract.calc_estimate`. Продукт не показывает неполный итог как готовую смету.
|
||||
5. Гейт release и ручной осмотр десктопа и узкого экрана проходят до предложения выкладки на прод.
|
||||
|
||||
План: (A) связать сохранённые assistant/estimate записи и допустимые формы → (B) scoped API пересчёта и атомарного сохранения → (C) селекторы и замена внутри пузыря → (D) интеграционные и UI проверки → (E) release стенд и визуальный осмотр.
|
||||
|
||||
Риски: поток перерисует кнопки; выбор устаревшего периода даст чужие цены; два окна одновременно перетрут друг друга; после reload текст и панель разойдутся; длинная таблица сломает мобильную ширину. Меры: монтировать после `done`, стабильные ID каталога, ревизия, транзакция, браузерный осмотр.
|
||||
@@ -232,6 +232,27 @@ def load_catalog() -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
def basis_options(subject_id: int) -> list[dict]:
|
||||
"""Only built price forms for one subject, grouped for an inline selector."""
|
||||
catalog = load_catalog() or {}
|
||||
zones: dict[int, dict] = {}
|
||||
for entry in catalog.get("zones") or []:
|
||||
if entry.get("subject_id") != subject_id:
|
||||
continue
|
||||
zone_id = entry.get("zone_id")
|
||||
period_id = entry.get("period_id")
|
||||
if not isinstance(zone_id, int) or not isinstance(period_id, int):
|
||||
continue
|
||||
zone = zones.setdefault(zone_id, {"zone_id": zone_id,
|
||||
"name": entry.get("zone_name") or "",
|
||||
"periods": []})
|
||||
zone["periods"].append({"period_id": period_id,
|
||||
"name": entry.get("period_label") or ""})
|
||||
for zone in zones.values():
|
||||
zone["periods"].sort(key=lambda period: period["period_id"])
|
||||
return sorted(zones.values(), key=lambda zone: zone["name"])
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=4)
|
||||
def _load_form(path: str, sha256: str | None, builder: int | None):
|
||||
# Контрольная сумма и версия — в ключе кеша: перезалитая форма той же зоны и периода лежит по
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Validated inputs and deterministic answer text for inline estimate revisions."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
|
||||
def selected_form(options: list[dict], zone_id: int, period_id: int) -> tuple[dict, dict] | None:
|
||||
for zone in options:
|
||||
if zone["zone_id"] == zone_id:
|
||||
for period in zone["periods"]:
|
||||
if period["period_id"] == period_id:
|
||||
return zone, period
|
||||
return None
|
||||
|
||||
|
||||
def positions_for_revision(saved: dict, edited: object = None) -> list[dict]:
|
||||
"""The browser may change quantities, never estimate codes or measuring units."""
|
||||
source = saved.get("positions") or []
|
||||
if not isinstance(source, list) or not 1 <= len(source) <= 1000:
|
||||
raise ValueError("В смете нет позиций для пересчёта")
|
||||
if edited is not None and (not isinstance(edited, list) or len(edited) != len(source)):
|
||||
raise ValueError("Состав позиций изменился; обновите диалог")
|
||||
result = []
|
||||
for index, row in enumerate(source):
|
||||
if not isinstance(row, dict) or not row.get("code"):
|
||||
raise ValueError("Позиция не содержит шифр для пересчёта")
|
||||
incoming = edited[index] if edited is not None else row
|
||||
if not isinstance(incoming, dict) or incoming.get("code") != row["code"]:
|
||||
raise ValueError("Шифры позиций нельзя менять этим выбором")
|
||||
if edited is not None and (incoming.get("unit") or "") != (row.get("unit") or ""):
|
||||
raise ValueError("Единицы измерения нельзя менять этим выбором")
|
||||
try:
|
||||
qty = float(incoming["qty"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
raise ValueError("Укажите числовой объём для каждой позиции") from None
|
||||
if not math.isfinite(qty) or qty < 0:
|
||||
raise ValueError("Объём каждой позиции не может быть отрицательным")
|
||||
result.append({"code": row["code"], "unit": row.get("unit", ""), "qty": qty})
|
||||
return result
|
||||
|
||||
|
||||
def revised_answer(result: dict) -> str:
|
||||
"""Replace stale AI prose with values from the same calculation as the panel."""
|
||||
applied = result["applied"]
|
||||
total = result.get("grand_total")
|
||||
if not isinstance(total, (int, float)) or not math.isfinite(total):
|
||||
raise ValueError("Движок не вернул итог")
|
||||
zone = str(applied.get("zone") or "").replace("\n", " ")
|
||||
period = str(applied.get("period") or "").replace("\n", " ")
|
||||
lines = ["Смета пересчитана по выбранным ценам.", "",
|
||||
f"Ценовая зона: {zone}. Период цен: {period}.", "",
|
||||
("Предварительный итог: " if not result.get("ok") or result.get("unpriced")
|
||||
else "Итого по локальной смете: ")
|
||||
+ f"{total:,.2f} ₽".replace(",", " "),
|
||||
"Позиции и их стоимости приведены в таблице ниже."]
|
||||
if result.get("unpriced"):
|
||||
lines.append("⚠ Часть ресурсов не оценена; итог неполный.")
|
||||
if result.get("missing"):
|
||||
lines.append("⚠ Часть позиций не рассчитана; итог неполный.")
|
||||
if result.get("limits_note"):
|
||||
lines.extend(["", str(result["limits_note"])])
|
||||
return "\n".join(lines)
|
||||
@@ -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):
|
||||
"""Удалить свой диалог ЦЕЛИКОМ (история в БД + загруженные файлы на диске).
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
[
|
||||
{
|
||||
"version": "2026-12-02d",
|
||||
"date": "2026-12-02",
|
||||
"changes": [
|
||||
"В готовой смете можно выбрать другую доступную ценовую зону или квартал прямо в ответе: итог пересчитывается и сохраняется в этом же диалоге"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026-12-02c",
|
||||
"date": "2026-12-02",
|
||||
|
||||
+168
-10
@@ -356,6 +356,12 @@ button { font-family: inherit; }
|
||||
.est-tot-row .num { font-variant-numeric: tabular-nums; }
|
||||
.est-tot-strong { font-weight: 700; color: var(--text); font-size: .95rem; }
|
||||
.est-basis { padding: .35rem .9rem; font-size: .78rem; color: var(--text-muted); border-bottom: 1px solid var(--border); overflow-wrap: anywhere; }
|
||||
.msg-ai.has-estimate { width: 100%; max-width: 100%; }
|
||||
.msg-ai .est-panel { width: 100%; box-sizing: border-box; }
|
||||
.est-basis-picker { display: inline-flex; gap: .35rem; align-items: center; flex-wrap: wrap; }
|
||||
.est-basis-picker button, .est-basis-picker select { max-width: 100%; font: inherit; color: var(--text); background: var(--bg-card); border: 1px solid var(--border); border-radius: 6px; padding: .25rem .4rem; cursor: pointer; }
|
||||
.est-basis-picker button:hover, .est-basis-picker select:focus-visible { border-color: var(--accent); }
|
||||
.est-basis-error { color: var(--danger); display: block; margin-top: .3rem; }
|
||||
.est-input { color: var(--text-muted); font-size: .85em; }
|
||||
.est-warn { padding: .5rem .9rem; border-top: 1px solid var(--border); background: var(--error-bg); color: var(--error-text, var(--text)); font-size: .8rem; display: flex; flex-direction: column; gap: .25rem; }
|
||||
.ka-sub { padding: .3rem .9rem; font-size: .72rem; color: var(--text-muted); font-family: monospace; border-bottom: 1px solid var(--border-light, var(--border)); word-break: break-all; }
|
||||
@@ -417,6 +423,28 @@ button { font-family: inherit; }
|
||||
.msg-ai .table-wrap .num, .msg-ai .table-wrap th.num { white-space: normal; overflow-wrap: anywhere; }
|
||||
.msg-ai .table-wrap th, .msg-ai .table-wrap td { min-width: 0; }
|
||||
.msg-ai .table-wrap thead th { position: sticky; top: 0; background: var(--ai-bg); z-index: 1; }
|
||||
@media (max-width: 600px) {
|
||||
.msg-ai.has-estimate .est-table, .msg-ai.has-estimate .est-table tbody,
|
||||
.msg-ai.has-estimate .est-table tr { display: block; width: 100%; }
|
||||
.msg-ai.has-estimate .est-table .est-header-row { display: none; }
|
||||
.msg-ai.has-estimate .est-table tr { padding: .45rem; border-bottom: 1px solid var(--border); }
|
||||
.msg-ai.has-estimate .est-table td {
|
||||
display: grid; grid-template-columns: minmax(7.3rem, 42%) minmax(0, 1fr);
|
||||
gap: .35rem; width: 100%; max-width: none; box-sizing: border-box;
|
||||
border: 0; padding: .2rem .35rem; white-space: normal; overflow-wrap: anywhere;
|
||||
}
|
||||
.msg-ai.has-estimate .est-table td::before {
|
||||
content: attr(data-label); color: var(--text-muted); font-weight: 600;
|
||||
}
|
||||
.msg-ai.has-estimate .est-table td.num { text-align: left; white-space: normal; }
|
||||
.msg-ai.has-estimate .est-table td input { min-width: 0; max-width: 100%; box-sizing: border-box; }
|
||||
.msg-ai.has-estimate .est-actions {
|
||||
display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .4rem;
|
||||
}
|
||||
.msg-ai.has-estimate .est-actions .est-dl {
|
||||
width: 100%; min-height: 2.5rem; word-break: normal; overflow-wrap: normal;
|
||||
}
|
||||
}
|
||||
.msg-ai th, .msg-ai td { border: 1px solid var(--border-light); padding: .35rem .6rem; text-align: left; vertical-align: top; white-space: normal; max-width: 360px; }
|
||||
.msg-ai th { background: var(--bg); font-weight: 600; position: sticky; top: 0; }
|
||||
.msg-ai td.num, .msg-ai th.num { white-space: nowrap; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
@@ -2175,6 +2203,28 @@ function addMsg(type, text, ts) {
|
||||
scrollIfPinned();
|
||||
return div;
|
||||
}
|
||||
|
||||
// Структурированная смета приходит после done. Отделяем текст ответа от кнопок,
|
||||
// стоимости и панели, чтобы пересчёт заменял содержимое ЭТОГО пузыря.
|
||||
function estimateAnswerBody(host) {
|
||||
let body = host.querySelector(':scope > .ai-body');
|
||||
if (body) return body;
|
||||
body = document.createElement('div'); body.className = 'ai-body';
|
||||
for (const child of Array.from(host.childNodes)) {
|
||||
if (child.nodeType === 1 && child.matches('.msg-time, .copy-btn, .msg-cost, .est-panel, .fb-form')) continue;
|
||||
body.appendChild(child);
|
||||
}
|
||||
const time = host.querySelector(':scope > .msg-time');
|
||||
if (time) time.after(body); else host.prepend(body);
|
||||
return body;
|
||||
}
|
||||
|
||||
function replaceEstimateAnswer(host, text) {
|
||||
const body = estimateAnswerBody(host);
|
||||
body.innerHTML = renderMarkdown(text);
|
||||
host._rawText = text;
|
||||
enhanceTables(body); typografAI(body); externalizeLinks(body);
|
||||
}
|
||||
function addTyping() {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'typing';
|
||||
@@ -3013,8 +3063,8 @@ async function runChat(text, retried, готовыйПоток, внешнийCt
|
||||
// Агент подготовил файлы — кнопки скачивания прямо в чате
|
||||
if (data.files && data.files.length) addFilesMsg(data.files);
|
||||
} else if (eventType === 'estimate') {
|
||||
// Структурированная смета — панель с таблицей (срез 6.1, JS НЕ считает)
|
||||
if (data && data.positions) addEstimatePanel(data);
|
||||
// Смета живёт в том же ответе, который её породил.
|
||||
if (data && data.positions) addEstimatePanel(data, null, aiDiv);
|
||||
} else if (eventType === 'ka_form') {
|
||||
// Конъюнктурный анализ — панель офферов (срез 7)
|
||||
if (data && data.rows) addKaPanel(data);
|
||||
@@ -3058,7 +3108,7 @@ function fmtMoney(v) {
|
||||
if (typeof v !== 'number' || !isFinite(v)) return v == null ? '' : String(v);
|
||||
return v.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2});
|
||||
}
|
||||
function addEstimatePanel(data, prevData) {
|
||||
function addEstimatePanel(data, prevData, host) {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'est-panel';
|
||||
panel.setAttribute('role', 'region');
|
||||
@@ -3076,12 +3126,93 @@ function addEstimatePanel(data, prevData) {
|
||||
// По какой форме посчитано: зона места стройки и уровень цен — подпись итога не должна
|
||||
// приписать числа чужому региону (инцидент 01.08.2026).
|
||||
const ap = data.applied;
|
||||
async function applyLinked(zoneId, periodId, positions) {
|
||||
if (!data._message_id || !host) return;
|
||||
const requestTab = tabId;
|
||||
panel.querySelectorAll('button, select, input').forEach(el => { el.disabled = true; });
|
||||
let error = panel.querySelector('.est-basis-error');
|
||||
if (error) error.remove();
|
||||
try {
|
||||
const r = await authFetch('/api/estimates/' + data._message_id + '/basis', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({zone_id: zoneId, period_id: periodId,
|
||||
revision: data._revision || 0, positions})});
|
||||
if (!r.ok) throw new Error(await reasonOrText(r));
|
||||
const updated = await r.json();
|
||||
if (requestTab !== tabId || !panel.isConnected) return;
|
||||
replaceEstimateAnswer(host, updated.answer);
|
||||
addEstimatePanel(updated.estimate, data, host);
|
||||
panel.remove();
|
||||
srAnnounce('Смета пересчитана в текущем ответе');
|
||||
} catch (e) {
|
||||
if (!panel.isConnected) return;
|
||||
error = document.createElement('span'); error.className = 'est-basis-error';
|
||||
error.setAttribute('role', 'alert');
|
||||
error.textContent = e.message || 'Не удалось пересчитать';
|
||||
(panel.querySelector('.est-basis') || panel.querySelector('.est-head')).appendChild(error);
|
||||
panel.querySelectorAll('button, select, input').forEach(el => { el.disabled = false; });
|
||||
}
|
||||
}
|
||||
if (ap && ap.zone) {
|
||||
const basis = document.createElement('div');
|
||||
basis.className = 'est-basis';
|
||||
basis.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '')
|
||||
+ (ap.period_default ? ' (последний доступный период)' : '')
|
||||
+ (ap.letter ? ' · ' + ap.letter : '');
|
||||
if (data._message_id && data._assistant_id && host && !viewOwner && ap.subject_id != null) {
|
||||
const picker = document.createElement('span'); picker.className = 'est-basis-picker';
|
||||
const open = document.createElement('button'); open.type = 'button';
|
||||
open.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '') + ' ▾';
|
||||
open.setAttribute('aria-label', 'Изменить ценовую зону или квартал');
|
||||
open.onclick = async () => {
|
||||
open.disabled = true; open.textContent = 'Загружаю доступные цены…';
|
||||
try {
|
||||
const r = await authFetch('/api/estimates/' + data._message_id + '/basis');
|
||||
if (!r.ok) throw new Error(await reasonOrText(r));
|
||||
const options = await r.json();
|
||||
if (!panel.isConnected) return;
|
||||
const zones = options.zones || [];
|
||||
const zoneSelect = document.createElement('select');
|
||||
zoneSelect.setAttribute('aria-label', 'Ценовая зона');
|
||||
zones.forEach(z => { const o = document.createElement('option');
|
||||
o.value = String(z.zone_id); o.textContent = z.name; zoneSelect.appendChild(o); });
|
||||
zoneSelect.value = String(ap.zone_id);
|
||||
const periodSelect = document.createElement('select');
|
||||
periodSelect.setAttribute('aria-label', 'Квартал цен');
|
||||
const fillPeriods = () => {
|
||||
periodSelect.replaceChildren();
|
||||
const selected = zones.find(z => String(z.zone_id) === zoneSelect.value);
|
||||
const periods = selected ? selected.periods : [];
|
||||
periods.forEach(p => { const o = document.createElement('option');
|
||||
o.value = String(p.period_id); o.textContent = p.name; periodSelect.appendChild(o); });
|
||||
if ([...periodSelect.options].some(o => o.value === String(ap.period_id)))
|
||||
periodSelect.value = String(ap.period_id);
|
||||
else if (periods.length) periodSelect.value = String(periods[periods.length - 1].period_id);
|
||||
};
|
||||
fillPeriods();
|
||||
const submit = () => {
|
||||
if (Number(zoneSelect.value) === ap.zone_id && Number(periodSelect.value) === ap.period_id) return;
|
||||
const inputs = Array.from(panel.querySelectorAll('.est-qty'));
|
||||
const positions = inputs.map(inp => ({code: inp.dataset.code, unit: inp.dataset.unit || '',
|
||||
qty: parseFloat(inp.value)}));
|
||||
applyLinked(Number(zoneSelect.value), Number(periodSelect.value), positions);
|
||||
};
|
||||
zoneSelect.onchange = () => { fillPeriods(); submit(); };
|
||||
periodSelect.onchange = submit;
|
||||
picker.replaceChildren(zoneSelect, periodSelect);
|
||||
zoneSelect.focus();
|
||||
} catch (e) {
|
||||
open.disabled = false; open.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '') + ' ▾';
|
||||
const err = document.createElement('span'); err.className = 'est-basis-error';
|
||||
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Нет связи';
|
||||
basis.appendChild(err);
|
||||
}
|
||||
};
|
||||
picker.appendChild(open); basis.appendChild(picker);
|
||||
if (ap.letter) { const letter = document.createElement('span');
|
||||
letter.textContent = ' · ' + ap.letter; basis.appendChild(letter); }
|
||||
} else {
|
||||
basis.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '')
|
||||
+ (ap.period_default ? ' (последний доступный период)' : '')
|
||||
+ (ap.letter ? ' · ' + ap.letter : '');
|
||||
}
|
||||
panel.appendChild(basis);
|
||||
}
|
||||
|
||||
@@ -3090,6 +3221,7 @@ function addEstimatePanel(data, prevData) {
|
||||
const table = document.createElement('table');
|
||||
table.className = 'est-table';
|
||||
const thead = document.createElement('tr');
|
||||
thead.className = 'est-header-row';
|
||||
['№', 'Код', 'Наименование', 'Ед.', 'Кол-во', 'Цена/ед', 'Стоимость'].forEach(h => {
|
||||
const th = document.createElement('th'); th.textContent = h; thead.appendChild(th);
|
||||
});
|
||||
@@ -3101,6 +3233,7 @@ function addEstimatePanel(data, prevData) {
|
||||
p.qty != null ? p.qty : '', fmtMoney(p.unit_cost), fmtMoney(p.total)];
|
||||
cells.forEach((c, ci) => {
|
||||
const td = document.createElement('td');
|
||||
td.dataset.label = ['№', 'Код', 'Наименование', 'Ед.', 'Кол-во', 'Цена/ед', 'Стоимость'][ci];
|
||||
if (ci === 4 && editable && p.code) {
|
||||
// объём — редактируемый; правка пересчитывается ДВИЖКОМ (не JS)
|
||||
const inp = document.createElement('input');
|
||||
@@ -3196,6 +3329,10 @@ function addEstimatePanel(data, prevData) {
|
||||
return;
|
||||
}
|
||||
if (!positions.length) return;
|
||||
if (data._message_id && host && ap && ap.zone_id != null && ap.period_id != null) {
|
||||
await applyLinked(ap.zone_id, ap.period_id, positions);
|
||||
return;
|
||||
}
|
||||
rc.disabled = true; rc.textContent = '↻ Считаю...';
|
||||
try {
|
||||
const r = await authFetch('/api/recalc', {method: 'POST',
|
||||
@@ -3221,7 +3358,14 @@ function addEstimatePanel(data, prevData) {
|
||||
if (prevData) {
|
||||
const un = document.createElement('button');
|
||||
un.className = 'est-dl'; un.type = 'button'; un.textContent = '↩ Отменить пересчёт';
|
||||
un.onclick = () => { const back = addEstimatePanel(prevData); panel.replaceWith(back); };
|
||||
un.onclick = () => {
|
||||
if (data._message_id && host && prevData.applied) {
|
||||
applyLinked(prevData.applied.zone_id, prevData.applied.period_id,
|
||||
(prevData.positions || []).map(p => ({code: p.code, unit: p.unit || '', qty: p.qty})));
|
||||
} else {
|
||||
const back = addEstimatePanel(prevData); panel.replaceWith(back);
|
||||
}
|
||||
};
|
||||
acts.appendChild(un);
|
||||
}
|
||||
// Утвердить смету (срез 6.4): человек фиксирует смету — блокируем правки, метка
|
||||
@@ -3230,6 +3374,8 @@ function addEstimatePanel(data, prevData) {
|
||||
appr.onclick = () => {
|
||||
panel.classList.add('est-approved');
|
||||
panel.querySelectorAll('.est-qty').forEach(i => { i.readOnly = true; i.tabIndex = -1; });
|
||||
panel.querySelectorAll('.est-basis-picker button, .est-basis-picker select')
|
||||
.forEach(el => { el.disabled = true; });
|
||||
acts.querySelectorAll('button').forEach(b => { if (b !== dl) b.disabled = true; });
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'est-badge'; badge.textContent = '✓ Утверждено';
|
||||
@@ -3240,7 +3386,11 @@ function addEstimatePanel(data, prevData) {
|
||||
panel.appendChild(acts);
|
||||
|
||||
const ob = document.getElementById('onboarding'); if (ob) ob.remove();
|
||||
msgs.appendChild(panel);
|
||||
if (host) {
|
||||
estimateAnswerBody(host);
|
||||
host.classList.add('has-estimate');
|
||||
host.appendChild(panel);
|
||||
} else msgs.appendChild(panel);
|
||||
scrollIfPinned();
|
||||
return panel;
|
||||
}
|
||||
@@ -3493,7 +3643,10 @@ async function loadHistory() {
|
||||
let lastAi = null;
|
||||
for (const m of history) {
|
||||
if (m.role === 'user') addMsg('user', m.content, m.timestamp);
|
||||
else if (m.role === 'assistant') lastAi = addMsg('ai', m.content, m.timestamp);
|
||||
else if (m.role === 'assistant') {
|
||||
lastAi = addMsg('ai', m.content, m.timestamp);
|
||||
lastAi._messageId = m.id;
|
||||
}
|
||||
else if (m.role === 'spend') {
|
||||
try { attachCost(lastAi, JSON.parse(m.content)); } catch {}
|
||||
}
|
||||
@@ -3502,7 +3655,12 @@ async function loadHistory() {
|
||||
try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {}
|
||||
}
|
||||
else if (m.role === 'estimate') {
|
||||
try { addEstimatePanel(JSON.parse(m.content)); } catch {}
|
||||
try {
|
||||
const estimate = JSON.parse(m.content);
|
||||
const host = !estimate._assistant_id || lastAi && lastAi._messageId === estimate._assistant_id
|
||||
? lastAi : null;
|
||||
addEstimatePanel({...estimate, _message_id: m.id}, null, host);
|
||||
} catch {}
|
||||
}
|
||||
else if (m.role === 'ka_form') {
|
||||
try { addKaPanel(JSON.parse(m.content)); } catch {}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Switching a price form changes the saved answer and estimate as one revision."""
|
||||
import importlib
|
||||
import json
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def case(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "chat.db"))
|
||||
monkeypatch.setenv("SESSION_SECRET", "inline-estimate-test")
|
||||
monkeypatch.setenv("ESTIMATE_ENGINE", "on")
|
||||
import auth
|
||||
import db
|
||||
import main
|
||||
import engine_prices
|
||||
import estimate_contract
|
||||
|
||||
for module in (db, auth, main):
|
||||
importlib.reload(module)
|
||||
db.init_db()
|
||||
for email in ("alice@x", "bob@x"):
|
||||
db.create_user(email, auth.hash_password("Passw0rd!ok"))
|
||||
db.admin_verify_user(email)
|
||||
old = {
|
||||
"title": "Смета", "positions": [{"code": "ГЭСН 01-01-001-01", "name": "Работа",
|
||||
"unit": "м3", "qty": 2, "total": 100}],
|
||||
"totals": {"grand_total": 100}, "ok": True,
|
||||
"applied": {"subject": "Тестовый край", "subject_id": 1,
|
||||
"zone": "Тестовый край (1 зона)", "zone_id": 11,
|
||||
"period": "3 квартал 2026", "period_id": 403},
|
||||
"meta": {"region": "Тестовый край (1 зона)", "price_level": "3 квартал 2026"},
|
||||
}
|
||||
assistant_id = db.save_message("alice@x", "tab", "assistant", "Исходный ответ: 100 руб.")
|
||||
estimate_id = db.save_message("alice@x", "tab", "estimate",
|
||||
json.dumps({**old, "_assistant_id": assistant_id}, ensure_ascii=False))
|
||||
catalog = {"zones": [
|
||||
{"subject_id": 1, "subject_name": "Тестовый край", "zone_id": 11,
|
||||
"zone_name": "Тестовый край (1 зона)", "period_id": 403,
|
||||
"period_label": "3 квартал 2026"},
|
||||
{"subject_id": 1, "subject_name": "Тестовый край", "zone_id": 12,
|
||||
"zone_name": "Тестовый край (2 зона)", "period_id": 404,
|
||||
"period_label": "4 квартал 2026"},
|
||||
{"subject_id": 2, "subject_name": "Чужой край", "zone_id": 21,
|
||||
"zone_name": "Чужой край", "period_id": 404,
|
||||
"period_label": "4 квартал 2026"},
|
||||
]}
|
||||
monkeypatch.setattr(engine_prices, "load_catalog", lambda: catalog)
|
||||
seen = []
|
||||
|
||||
def calculate(positions, meta):
|
||||
seen.append((positions, meta))
|
||||
return {"status": "ok", "ok": True, "grand_total": 240,
|
||||
"positions": [{"code": "ГЭСН 01-01-001-01", "name": "Работа",
|
||||
"unit": "м3", "qty": 2, "total": 240}],
|
||||
"missing": [], "unpriced": [], "limits_note": "Без дополнительных затрат и НДС.",
|
||||
"applied": {"subject": "Тестовый край", "subject_id": 1,
|
||||
"zone": "Тестовый край (2 зона)", "zone_id": 12,
|
||||
"period": "4 квартал 2026", "period_id": 404}}
|
||||
|
||||
monkeypatch.setattr(estimate_contract, "calc_estimate", calculate)
|
||||
client = TestClient(main.app)
|
||||
alice = {"Authorization": "Bearer " + auth._make_token("alice@x"), "X-Tab-Id": "tab"}
|
||||
bob = {"Authorization": "Bearer " + auth._make_token("bob@x"), "X-Tab-Id": "tab"}
|
||||
return db, client, alice, bob, estimate_id, assistant_id, seen
|
||||
|
||||
|
||||
def _request(client, estimate_id, headers, **values):
|
||||
return client.post(f"/api/estimates/{estimate_id}/basis", headers=headers,
|
||||
json={"zone_id": 12, "period_id": 404, "revision": 0, **values})
|
||||
|
||||
|
||||
def test_basis_switch_is_saved_in_same_answer(case):
|
||||
db, client, alice, _, eid, aid, seen = case
|
||||
r = _request(client, eid, alice)
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["estimate"]["applied"]["zone_id"] == 12
|
||||
assert body["estimate"]["_revision"] == 1
|
||||
assert "240" in body["answer"] and "4 квартал 2026" in body["answer"]
|
||||
assert "**" not in body["answer"]
|
||||
assert seen == [([{"code": "ГЭСН 01-01-001-01", "unit": "м3", "qty": 2}],
|
||||
{"region": "Тестовый край", "zone": "Тестовый край (2 зона)",
|
||||
"price_level": "4 квартал 2026"})]
|
||||
rows = db.get_history("alice@x", "tab")
|
||||
assert len(rows) == 2 and [row["id"] for row in rows] == [aid, eid]
|
||||
assert rows[0]["content"] == body["answer"]
|
||||
assert json.loads(rows[1]["content"])["_revision"] == 1
|
||||
|
||||
|
||||
def test_basis_switch_requires_owner_and_current_revision(case):
|
||||
db, client, alice, bob, eid, _, seen = case
|
||||
assert _request(client, eid, {}).status_code == 401
|
||||
assert _request(client, eid, bob).status_code == 404
|
||||
assert _request(client, eid, alice, zone_id=21).status_code == 400
|
||||
assert seen == []
|
||||
assert _request(client, eid, alice).status_code == 200
|
||||
assert _request(client, eid, alice).status_code == 409
|
||||
assert len(db.get_history("alice@x", "tab")) == 2
|
||||
|
||||
|
||||
def test_basis_options_only_contain_current_subject(case):
|
||||
_, client, alice, _, eid, _, _ = case
|
||||
r = client.get(f"/api/estimates/{eid}/basis", headers=alice)
|
||||
assert r.status_code == 200
|
||||
assert [(z["zone_id"], [p["period_id"] for p in z["periods"]])
|
||||
for z in r.json()["zones"]] == [(11, [403]), (12, [404])]
|
||||
|
||||
|
||||
def test_stream_links_estimate_to_answer_before_sending_event(tmp_path, monkeypatch):
|
||||
import main
|
||||
|
||||
saved = []
|
||||
|
||||
def save(_user, _tab, role, content):
|
||||
saved.append((role, content))
|
||||
return len(saved)
|
||||
|
||||
monkeypatch.setattr(main, "save_message", save)
|
||||
monkeypatch.setattr(main, "get_work_dir", lambda _u, _t: tmp_path)
|
||||
monkeypatch.setattr(main, "_work_dir_snapshot", lambda _path: {})
|
||||
monkeypatch.setattr(main, "_maybe_autotitle", lambda *_: None)
|
||||
(tmp_path / "_estimate_panel.json").write_text(json.dumps({
|
||||
"positions": [{"code": "ГЭСН 01-01-001-01", "qty": 2}],
|
||||
"applied": {"subject_id": 1}}), encoding="utf-8")
|
||||
|
||||
async def stream(*_):
|
||||
yield 'event: text\ndata: {"text":"Смета посчитана"}\n\n'
|
||||
yield 'event: done\ndata: {"result":"Смета посчитана","usage":{}}\n\n'
|
||||
|
||||
monkeypatch.setattr(main, "stream_claude", stream)
|
||||
chunks = asyncio.run(_collect(main._stream_and_save("Посчитай смету", "alice@x", "tab")))
|
||||
event = next(json.loads(chunk.split("data: ", 1)[1]) for chunk in chunks
|
||||
if chunk.startswith("event: estimate"))
|
||||
assistant_id = next(i for i, (role, _) in enumerate(saved, 1) if role == "assistant")
|
||||
estimate_id = next(i for i, (role, _) in enumerate(saved, 1) if role == "estimate")
|
||||
assert event["_assistant_id"] == assistant_id
|
||||
assert event["_message_id"] == estimate_id
|
||||
assert json.loads(saved[estimate_id - 1][1])["_assistant_id"] == assistant_id
|
||||
|
||||
|
||||
async def _collect(stream):
|
||||
return [chunk async for chunk in stream]
|
||||
@@ -0,0 +1,124 @@
|
||||
"""The price selector edits the current answer bubble in a real browser."""
|
||||
import functools
|
||||
import http.server
|
||||
import os
|
||||
import socketserver
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
import ui_smoke_harness # noqa: E402
|
||||
from test_password_reset_ui import browser # noqa: E402,F401
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site(tmp_path_factory):
|
||||
directory = tmp_path_factory.mktemp("inline-estimate")
|
||||
ui_smoke_harness.build_stub(directory / "index.html", logged_in=True)
|
||||
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(directory))
|
||||
|
||||
class Quiet(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
server = Quiet(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{server.server_address[1]}/index.html"
|
||||
server.shutdown()
|
||||
|
||||
|
||||
def test_choice_replaces_current_answer_without_new_bubble(browser, site):
|
||||
page = browser.new_page(viewport={"width": 390, "height": 844})
|
||||
page.goto(site)
|
||||
page.wait_for_timeout(500)
|
||||
page.evaluate("""() => {
|
||||
const oldFetch = window.fetch;
|
||||
window._basisPosts = [];
|
||||
const old = {title:'Смета', _message_id:31, _assistant_id:30, _revision:0, ok:true,
|
||||
positions:[{code:'ГЭСН 01-01-001-01',name:'Работа',unit:'м3',qty:2,total:100}],
|
||||
totals:{grand_total:100}, applied:{subject:'Тестовый край',subject_id:1,
|
||||
zone:'Тестовый край (1 зона)',zone_id:11,period:'3 квартал 2026',period_id:403}};
|
||||
window.fetch = async (url, opts={}) => {
|
||||
if (String(url).includes('/api/estimates/31/basis')) {
|
||||
if (opts.method === 'POST') {
|
||||
window._basisPosts.push(JSON.parse(opts.body));
|
||||
return new Response(JSON.stringify({answer:'Итого: 240 ₽ · 4 квартал 2026',
|
||||
estimate:{...old,_revision:1,
|
||||
positions:[{...old.positions[0],total:240}],totals:{grand_total:240},
|
||||
applied:{...old.applied,zone:'Тестовый край (2 зона)',zone_id:12,
|
||||
period:'4 квартал 2026',period_id:404}}}),
|
||||
{status:200,headers:{'Content-Type':'application/json'}});
|
||||
}
|
||||
return new Response(JSON.stringify({revision:0,zones:[
|
||||
{zone_id:11,name:'Тестовый край (1 зона)',periods:[{period_id:403,name:'3 квартал 2026'}]},
|
||||
{zone_id:12,name:'Тестовый край (2 зона)',periods:[
|
||||
{period_id:402,name:'2 квартал 2026'},
|
||||
{period_id:404,name:'4 квартал 2026'}]}]}),
|
||||
{status:200,headers:{'Content-Type':'application/json'}});
|
||||
}
|
||||
return oldFetch(url,opts);
|
||||
};
|
||||
const answer = addMsg('ai','Исходный ответ: 100 ₽');
|
||||
addEstimatePanel(old,null,answer);
|
||||
window._answer = answer;
|
||||
}""")
|
||||
page.locator(".est-basis-picker button").click()
|
||||
page.locator('select[aria-label="Ценовая зона"]').select_option("12")
|
||||
page.wait_for_function("window._basisPosts.length === 1 && window._answer.innerText.includes('240')")
|
||||
state = page.evaluate("""() => ({
|
||||
bubbles: document.querySelectorAll('#messages .msg-ai').length,
|
||||
within: !!window._answer.querySelector('.est-panel'),
|
||||
text: window._answer.innerText,
|
||||
posts: window._basisPosts,
|
||||
cssWidth: window.innerWidth,
|
||||
headDisplay: getComputedStyle(window._answer.querySelector('.est-header-row')).display,
|
||||
hostClass: window._answer.className,
|
||||
horizontalOverflow: document.documentElement.scrollWidth > window.innerWidth
|
||||
})""")
|
||||
screenshot_dir = os.environ.get("INLINE_ESTIMATE_SCREENSHOTS")
|
||||
if screenshot_dir:
|
||||
page.evaluate("document.querySelector('#messages').scrollTop = 0")
|
||||
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-mobile.png"))
|
||||
page.evaluate("document.querySelector('#messages').scrollTop = document.querySelector('#messages').scrollHeight")
|
||||
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-mobile-bottom.png"))
|
||||
page.set_viewport_size({"width": 1280, "height": 800})
|
||||
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-desktop.png"))
|
||||
page.close()
|
||||
assert state["bubbles"] == 1 and state["within"]
|
||||
assert "Исходный ответ: 100" not in state["text"]
|
||||
assert "240" in state["text"] and "4 квартал 2026" in state["text"]
|
||||
assert state["posts"][0]["zone_id"] == 12
|
||||
assert state["posts"][0]["period_id"] == 404
|
||||
assert state["headDisplay"] == "none", state
|
||||
assert not state["horizontalOverflow"]
|
||||
|
||||
|
||||
def test_saved_revision_reopens_inside_same_bubble(browser, site):
|
||||
page = browser.new_page(viewport={"width": 390, "height": 844})
|
||||
page.goto(site)
|
||||
page.wait_for_timeout(500)
|
||||
state = page.evaluate("""async () => {
|
||||
const oldFetch = window.fetch;
|
||||
window.fetch = async (url, opts={}) => {
|
||||
if (String(url).includes('/api/history')) return new Response(JSON.stringify([
|
||||
{id:30,role:'assistant',content:'Итого по локальной смете: 240 ₽',timestamp:1},
|
||||
{id:31,role:'estimate',timestamp:2,content:JSON.stringify({
|
||||
_assistant_id:30,_revision:1,title:'Смета',ok:true,
|
||||
positions:[{code:'ГЭСН 01-01-001-01',name:'Работа',unit:'м3',qty:2,total:240}],
|
||||
totals:{grand_total:240},applied:{subject:'Тестовый край',subject_id:1,
|
||||
zone:'Тестовый край (2 зона)',zone_id:12,period:'4 квартал 2026',period_id:404}})}
|
||||
]),{status:200,headers:{'Content-Type':'application/json'}});
|
||||
return oldFetch(url,opts);
|
||||
};
|
||||
await loadHistory();
|
||||
return {bubbles:document.querySelectorAll('#messages .msg-ai').length,
|
||||
inside:!!document.querySelector('#messages .msg-ai .est-panel'),
|
||||
text:document.querySelector('#messages .msg-ai')?.innerText || ''};
|
||||
}""")
|
||||
page.close()
|
||||
assert state["bubbles"] == 1 and state["inside"]
|
||||
assert "240" in state["text"] and "4 квартал 2026" in state["text"]
|
||||
Reference in New Issue
Block a user