146 lines
6.8 KiB
Python
146 lines
6.8 KiB
Python
"""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,00 ₽" 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]
|