Revise plain estimate answers from inline price zones
This commit is contained in:
@@ -124,3 +124,56 @@ def test_saved_revision_reopens_inside_same_bubble(browser, site):
|
||||
page.close()
|
||||
assert state["bubbles"] == 1 and state["inside"]
|
||||
assert "240" in state["text"] and "4 квартал 2026" in state["text"]
|
||||
|
||||
|
||||
def test_plain_answer_zone_changes_inside_its_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.fetch = async (url, opts={}) => {
|
||||
if (String(url).includes('/api/messages/30/basis')) {
|
||||
if (opts.method === 'POST') return new Response(JSON.stringify({
|
||||
answer:'Норма 10-08-002-02. Объём 100 шт. Ценовая зона: Хабаровский край (2 зона), 4 квартал 2026. Стоимость учтённой части: 280 ₽.'
|
||||
}), {status:200,headers:{'Content-Type':'application/json'}});
|
||||
return new Response(JSON.stringify({revision:'old-hash',zones:[
|
||||
{zone_id:118,name:'Хабаровский край (1 зона)',periods:[{period_id:428,name:'4 квартал 2026'}]},
|
||||
{zone_id:179,name:'Хабаровский край (2 зона)',periods:[{period_id:428,name:'4 квартал 2026'}]}
|
||||
]}), {status:200,headers:{'Content-Type':'application/json'}});
|
||||
}
|
||||
return oldFetch(url,opts);
|
||||
};
|
||||
const answer = addMsg('ai','Норма ГЭСНм 10-08-002-02, объём работ = 100 шт.\\nВыберите ценовую зону:\\n1. Хабаровский край (1 зона)\\n2. Хабаровский край (2 зона)');
|
||||
answer._messageId = 30;
|
||||
bindFreeformBasis(answer);
|
||||
}""")
|
||||
page.locator(".inline-basis-trigger").first.click()
|
||||
screenshot_dir = os.environ.get("INLINE_FREEFORM_SCREENSHOTS")
|
||||
if screenshot_dir:
|
||||
page.screenshot(path=str(Path(screenshot_dir) / "inline-freeform-picker.png"))
|
||||
page.locator('select[aria-label="Ценовая зона"]').select_option("179")
|
||||
page.locator('select[aria-label="Квартал цен"]').select_option("428")
|
||||
page.locator(".inline-basis-apply").click()
|
||||
page.locator(".msg-ai .ai-body", has_text="280 ₽").wait_for(timeout=10000)
|
||||
assert page.locator("#messages .msg-ai").count() == 1
|
||||
assert "Выберите ценовую зону" not in page.locator(".msg-ai").inner_text()
|
||||
assert page.locator(".inline-basis-trigger").count() >= 1
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
if screenshot_dir:
|
||||
page.screenshot(path=str(Path(screenshot_dir) / "inline-freeform-updated.png"))
|
||||
page.close()
|
||||
|
||||
|
||||
def test_plain_zone_without_calculable_position_has_no_dead_selector(browser, site):
|
||||
page = browser.new_page()
|
||||
page.goto(site)
|
||||
page.wait_for_timeout(500)
|
||||
count = page.evaluate("""() => {
|
||||
const answer = addMsg('ai','Выберите ценовую зону: Хабаровский край (1 зона).');
|
||||
answer._messageId = 40;
|
||||
bindFreeformBasis(answer);
|
||||
return answer.querySelectorAll('.inline-basis-trigger').length;
|
||||
}""")
|
||||
page.close()
|
||||
assert count == 0
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""A price zone chosen in a plain AI answer revises that answer in place."""
|
||||
import importlib
|
||||
|
||||
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-freeform-test")
|
||||
import auth
|
||||
import db
|
||||
import engine_prices
|
||||
import main
|
||||
|
||||
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)
|
||||
db.save_message("alice@x", "tab", "user", "Посчитай 100 извещателей в Хабаровском крае")
|
||||
original = ("Выберите ценовую зону:\n"
|
||||
"1. Хабаровский край (1 зона)\n"
|
||||
"2. Хабаровский край (2 зона)")
|
||||
answer_id = db.save_message("alice@x", "tab", "assistant", original)
|
||||
monkeypatch.setattr(engine_prices, "load_catalog", lambda: {"zones": [
|
||||
{"subject_id": 264, "zone_id": 118, "zone_name": "Хабаровский край (1 зона)",
|
||||
"period_id": 428, "period_label": "4 квартал 2026"},
|
||||
{"subject_id": 264, "zone_id": 179, "zone_name": "Хабаровский край (2 зона)",
|
||||
"period_id": 428, "period_label": "4 квартал 2026"},
|
||||
{"subject_id": 265, "zone_id": 300, "zone_name": "Другой край (1 зона)",
|
||||
"period_id": 428, "period_label": "4 квартал 2026"},
|
||||
]})
|
||||
seen = []
|
||||
|
||||
async def generate(user, tab, question, old_answer, zone, period):
|
||||
seen.append((user, tab, question, old_answer, zone, period))
|
||||
return {"answer": "Расчёт для Хабаровский край (2 зона), 4 квартал 2026: 280 ₽.",
|
||||
"usage": {}, "provider": "test", "model": "test"}
|
||||
|
||||
monkeypatch.setattr(main, "_generate_freeform_basis_answer", generate, raising=False)
|
||||
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, answer_id, original, seen
|
||||
|
||||
|
||||
def test_plain_answer_switches_in_place_and_rejects_stale_or_foreign(case):
|
||||
db, client, alice, bob, answer_id, original, seen = case
|
||||
url = f"/api/messages/{answer_id}/basis"
|
||||
params = {"label": "Хабаровский край (1 зона)"}
|
||||
assert client.get(url, params=params).status_code == 401
|
||||
assert client.get(url, params=params, headers=bob).status_code == 404
|
||||
options = client.get(url, params=params, headers=alice)
|
||||
assert options.status_code == 200, options.text
|
||||
assert [z["zone_id"] for z in options.json()["zones"]] == [118, 179]
|
||||
payload = {"label": params["label"], "zone_id": 179, "period_id": 428,
|
||||
"revision": options.json()["revision"]}
|
||||
assert client.post(url, json={**payload, "zone_id": 300}, headers=alice).status_code == 400
|
||||
assert client.post(url, json=payload, headers=bob).status_code == 404
|
||||
result = client.post(url, json=payload, headers=alice)
|
||||
assert result.status_code == 200, result.text
|
||||
assert "280 ₽" in result.json()["answer"]
|
||||
rows = db.get_history("alice@x", "tab")
|
||||
assert len(rows) == 2 and rows[1]["id"] == answer_id
|
||||
assert rows[1]["content"] == result.json()["answer"]
|
||||
assert client.post(url, json=payload, headers=alice).status_code == 409
|
||||
assert len(seen) == 1 and seen[0][3] == original
|
||||
|
||||
|
||||
def test_label_must_exist_in_saved_answer(case):
|
||||
_, client, alice, _, answer_id, _, seen = case
|
||||
url = f"/api/messages/{answer_id}/basis"
|
||||
assert client.get(url, params={"label": "Другой край (1 зона)"}, headers=alice).status_code == 400
|
||||
assert seen == []
|
||||
|
||||
|
||||
def test_plain_answer_extracts_explicit_norm_and_volume_without_guessing():
|
||||
import answer_basis
|
||||
question = "Посчитай монтаж 100 пожарных извещателей в Хабаровском крае"
|
||||
answer = "Норма ГЭСНм 10-08-002-02. Измеритель 1 шт. На 100 извещателей объём работ = 100 шт."
|
||||
assert answer_basis.extract_position(question, answer) == ("10-08-002-02", 100.0)
|
||||
assert answer_basis.extract_position("Какая цена?", "ГЭСНм 10-08-002-02") is None
|
||||
|
||||
|
||||
def test_incomplete_engine_result_is_never_presented_as_full_total():
|
||||
import answer_basis
|
||||
result = {"status": "ok", "ok": False, "grand_total": 156066.82,
|
||||
"missing": [{"code": "ГЭСНм 10-08-002-02", "reason": "НР/СП не определены"}],
|
||||
"unpriced": [], "positions": [{"code": "ГЭСНм 10-08-002-02", "qty": 100,
|
||||
"unit": "шт", "total": 156066.82}]}
|
||||
text = answer_basis.format_plain_result(result, "10-08-002-02", 100,
|
||||
"Хабаровский край (2 зона)", "4 квартал 2026")
|
||||
assert "156 066,82 ₽" in text
|
||||
assert "НР/СП не определены" in text
|
||||
assert "итого по локальной смете" not in text.lower()
|
||||
Reference in New Issue
Block a user