Add inline price basis switching to saved estimate answers

This commit is contained in:
anor
2026-12-02 21:56:06 +10:00
parent 7e4d4f841c
commit 856dbebdd1
9 changed files with 696 additions and 16 deletions
+145
View File
@@ -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]
+124
View File
@@ -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"]