501 lines
28 KiB
Python
501 lines
28 KiB
Python
"""Source-backed norm search and price preview."""
|
|
import pytest
|
|
import importlib
|
|
import sqlite3
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
def test_browse_keeps_sections_and_base_types_separate(tmp_path, monkeypatch):
|
|
import norm_finder
|
|
import fsnb_ref
|
|
db = tmp_path / "fsnb.sqlite"
|
|
with sqlite3.connect(db) as con:
|
|
con.execute("CREATE TABLE sources (source_id INTEGER)")
|
|
con.execute("CREATE TABLE works (base TEXT, base_type TEXT, code TEXT, name TEXT, "
|
|
"unit TEXT, cost REAL, price_level TEXT, section_path TEXT, "
|
|
"salary REAL, machines REAL, salary_mach REAL, materials REAL)")
|
|
con.executemany("INSERT INTO works (base,base_type,code,name,unit,cost,price_level,section_path) "
|
|
"VALUES (?,?,?,?,?,?,?,?)", [
|
|
("ГЭСН-2022", "ГЭСН", "01-01-001-01", "Разработка грунта", "1000 м3", None,
|
|
"норма", "Земляные работы > Раздел 1 > Таблица 1"),
|
|
("ГЭСН-2022", "ГЭСН", "01-01-001-02", "Разработка грунта 2", "1000 м3", None,
|
|
"норма", "Земляные работы > Раздел 1 > Таблица 1"),
|
|
("ГЭСН-2022", "ГЭСНм", "01-01-001-01", "Монтаж", "шт", None,
|
|
"норма", "Оборудование > Раздел 1"),
|
|
])
|
|
monkeypatch.setattr(fsnb_ref, "db_path", lambda: db)
|
|
root = norm_finder.browse("2022", "ГЭСН", "")
|
|
assert [row["name"] for row in root["children"]] == ["Земляные работы"]
|
|
section = norm_finder.browse("2022", "ГЭСН", "Земляные работы")
|
|
assert [row["name"] for row in section["children"]] == ["Раздел 1"]
|
|
leaf = norm_finder.browse("2022", "ГЭСН", "Земляные работы > Раздел 1 > Таблица 1", limit=1)
|
|
assert [row["code"] for row in leaf["items"]] == ["01-01-001-01"]
|
|
assert leaf["has_more"] is True
|
|
assert norm_finder.browse("2022", "ГЭСН", leaf["path"], limit=1, offset=1)["items"][0]["code"] == "01-01-001-02"
|
|
with pytest.raises(ValueError):
|
|
norm_finder.browse("2022", "ГЭСН", "Земляные работы > Несуществующий")
|
|
with pytest.raises(ValueError):
|
|
norm_finder.browse("2022", "ГЭСН", "%")
|
|
|
|
|
|
def test_browse_orders_collections_and_sections_by_norm_code(tmp_path, monkeypatch):
|
|
import norm_finder
|
|
import fsnb_ref
|
|
db = tmp_path / "ordered_fsnb.sqlite"
|
|
with sqlite3.connect(db) as con:
|
|
con.execute("CREATE TABLE sources (source_id INTEGER)")
|
|
con.execute("CREATE TABLE works (base TEXT, base_type TEXT, code TEXT, name TEXT, "
|
|
"unit TEXT, cost REAL, price_level TEXT, section_path TEXT, "
|
|
"salary REAL, machines REAL, salary_mach REAL, materials REAL)")
|
|
con.executemany("INSERT INTO works (base,base_type,code,name,unit,cost,price_level,section_path) "
|
|
"VALUES (?,?,?,?,?,?,?,?)", [
|
|
("ГЭСН-2022", "ГЭСН", "06-01-001-01", "Бетон", "м3", None,
|
|
"норма", "Бетонные работы > Раздел 1"),
|
|
("ГЭСН-2022", "ГЭСН", "02-01-001-01", "Горные работы", "м3", None,
|
|
"норма", "Горные работы > Раздел 1"),
|
|
("ГЭСН-2022", "ГЭСН", "01-10-001-01", "Земляные работы 10", "м3", None,
|
|
"норма", "Земляные работы > Раздел 10"),
|
|
("ГЭСН-2022", "ГЭСН", "01-02-001-01", "Земляные работы 2", "м3", None,
|
|
"норма", "Земляные работы > Раздел 2"),
|
|
])
|
|
monkeypatch.setattr(fsnb_ref, "db_path", lambda: db)
|
|
root = norm_finder.browse("2022", "ГЭСН")
|
|
assert [row["name"] for row in root["children"]] == [
|
|
"Земляные работы", "Горные работы", "Бетонные работы"]
|
|
sections = norm_finder.browse("2022", "ГЭСН", "Земляные работы")
|
|
assert [row["name"] for row in sections["children"]] == ["Раздел 2", "Раздел 10"]
|
|
|
|
|
|
def test_browse_exposes_only_its_own_base_cost_components(tmp_path, monkeypatch):
|
|
import norm_finder
|
|
import fsnb_ref
|
|
db = tmp_path / "costs.sqlite"
|
|
with sqlite3.connect(db) as con:
|
|
con.execute("CREATE TABLE sources (source_id INTEGER)")
|
|
con.execute("CREATE TABLE works (base TEXT, base_type TEXT, code TEXT, name TEXT, "
|
|
"unit TEXT, cost REAL, price_level TEXT, section_path TEXT, "
|
|
"salary REAL, machines REAL, salary_mach REAL, materials REAL)")
|
|
con.executemany("INSERT INTO works VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", [
|
|
("ГЭСН-2022", "ГЭСН", "01-01-001-01", "Земляные работы", "1000 м3", None,
|
|
"01.01.2022", "Земляные работы", None, None, None, None),
|
|
("ФЕР-2020", "ФЕР", "01-01-001-01", "Земляные работы", "1000 м3", 2968.03,
|
|
"01.01.2000", "Земляные работы", 14.48, 2953.55, 87.84, 0.0),
|
|
])
|
|
monkeypatch.setattr(fsnb_ref, "db_path", lambda: db)
|
|
fer = norm_finder.browse("2020", "ФЕР")["items"][0]
|
|
assert {field: fer[field] for field in ("cost", "salary", "machines", "salary_mach", "materials")} == {
|
|
"cost": 2968.03, "salary": 14.48, "machines": 2953.55,
|
|
"salary_mach": 87.84, "materials": 0.0}
|
|
gesn = norm_finder.browse("2022", "ГЭСН")["items"][0]
|
|
assert all(gesn[field] is None for field in
|
|
("cost", "salary", "machines", "salary_mach", "materials"))
|
|
|
|
|
|
def test_rate_catalog_uses_source_table_item_without_assigning_it_to_norm():
|
|
import norm_finder
|
|
rows = norm_finder.rate_catalog()
|
|
earthwork = next(row for row in rows if row["id"] == "1.1")
|
|
assert earthwork["nr_pct"] == 92
|
|
assert earthwork["sp_pct"] == 46
|
|
assert earthwork["nr_code"] == "812/пр, п.1.1"
|
|
assert earthwork["sp_code"] == "774/пр, п.1.1"
|
|
assert all("code" not in row for row in rows)
|
|
|
|
|
|
def test_search_rejects_empty_query_and_uses_existing_fsnb(monkeypatch):
|
|
import fsnb_ref
|
|
import norm_finder
|
|
|
|
seen = []
|
|
def find(*, query, base, limit):
|
|
seen.append((query, base, limit))
|
|
return {"status": "ok", "works": [{"code": "10-08-002-02", "name": "Извещатель",
|
|
"unit": "шт.", "base": "ГЭСН-2022", "base_type": "ГЭСНм"}]}
|
|
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
|
with pytest.raises(ValueError):
|
|
norm_finder.search(" ", "2022", 12)
|
|
found = norm_finder.search("извещатель", "2022", 12)
|
|
assert found["items"][0]["code"] == "10-08-002-02"
|
|
assert found["items"][0]["match_reason"].startswith("Совпали слова")
|
|
assert seen == [("извещатель", "2022", 60)]
|
|
|
|
|
|
def test_search_pages_keep_the_same_ranked_window(monkeypatch):
|
|
import fsnb_ref
|
|
import norm_finder
|
|
calls = []
|
|
def find(*, query, base, limit):
|
|
calls.append(limit)
|
|
return {"status": "ok", "works": [
|
|
{"code": f"11-01-{i:03d}-01", "name": f"Стяжка пола {i}",
|
|
"base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "100 м2"}
|
|
for i in range(20)]}
|
|
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
|
monkeypatch.setattr(fsnb_ref, "count_works", lambda term: 0)
|
|
first = norm_finder.search("стяжка", "2022", 8, 0)
|
|
second = norm_finder.search("стяжка", "2022", 8, 8)
|
|
assert first["has_more"] is True
|
|
assert len({row["code"] for row in first["items"] + second["items"]}) == 16
|
|
assert calls == [60, 60]
|
|
with pytest.raises(ValueError):
|
|
norm_finder.search("стяжка", "2022", 8, 60)
|
|
|
|
|
|
def test_search_falls_back_to_subject_term_and_ranks_relevant_work(monkeypatch):
|
|
import fsnb_ref
|
|
import norm_finder
|
|
def find(*, query, base, limit):
|
|
if query == "устройство стяжки пола":
|
|
return {"status": "not_found"}
|
|
assert query == "стяжки"
|
|
return {"status": "ok", "works": [
|
|
{"code": "06-12-001-04", "name": "Заполнение откосов со стяжкой",
|
|
"section_path": "Элеваторы", "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "м3"},
|
|
{"code": "11-01-011-02", "name": "Устройство стяжек пола",
|
|
"section_path": "Полы", "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "100 м2"},
|
|
]}
|
|
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
|
monkeypatch.setattr(fsnb_ref, "count_works", lambda word: {"стяжки": 30, "пола": 200}.get(word, 1000))
|
|
rows = norm_finder.search("устройство стяжки пола", "2022", 12)["items"]
|
|
assert rows[0]["code"] == "11-01-011-02"
|
|
|
|
|
|
def test_search_recovers_work_when_full_phrase_finds_only_accessory(monkeypatch):
|
|
import fsnb_ref
|
|
import norm_finder
|
|
|
|
accessory = {"code": "10-01-040-03", "name": "Корзина для пожарных извещателей",
|
|
"section_path": "Оборудование связи", "base": "ГЭСН-2022",
|
|
"base_type": "ГЭСНм", "unit": "шт"}
|
|
work = {"code": "10-08-002-02", "name": "Извещатель ПС автоматический дымовой",
|
|
"section_path": "Пожарная сигнализация > Извещатели", "base": "ГЭСН-2022",
|
|
"base_type": "ГЭСНм", "unit": "шт"}
|
|
def find(*, query, base, limit):
|
|
assert base == "2022"
|
|
if query == "установка пожарного извещателя":
|
|
return {"status": "ok", "works": [accessory]}
|
|
if fsnb_ref._stem(query) == "извещател":
|
|
return {"status": "ok", "works": [work]}
|
|
return {"status": "not_found"}
|
|
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
|
monkeypatch.setattr(fsnb_ref, "count_works", lambda term: 10)
|
|
rows = norm_finder.search("установка пожарного извещателя", "2022", 12)["items"]
|
|
assert rows[0]["code"] == "10-08-002-02"
|
|
assert rows[0]["match_score"] < 100 # только шифр получает уверенное точное совпадение
|
|
|
|
|
|
def test_search_corrects_typo_from_normative_vocabulary(monkeypatch):
|
|
import fsnb_ref
|
|
import norm_finder
|
|
|
|
def find(*, query, base, limit):
|
|
if query == "извещатель дымовой":
|
|
return {"status": "ok", "works": [{"code": "10-08-002-02",
|
|
"name": "Извещатель ПС автоматический дымовой",
|
|
"section_path": "Извещатели", "base": "ГЭСН-2022",
|
|
"base_type": "ГЭСНм", "unit": "шт"}]}
|
|
return {"status": "not_found"}
|
|
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
|
monkeypatch.setattr(fsnb_ref, "count_works", lambda term: 0)
|
|
result = norm_finder.search("извешатель дымовой", "2022", 12)
|
|
assert result["items"][0]["code"] == "10-08-002-02"
|
|
assert result["interpreted_query"] == "извещатель дымовой"
|
|
|
|
|
|
def test_detail_requires_exact_base_type_and_code(monkeypatch):
|
|
import fsnb_ref
|
|
import norm_finder
|
|
|
|
def composition(*, query, base, limit):
|
|
return {"status": "ok", "results": [
|
|
{"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": query,
|
|
"name": "Другая норма", "unit": "м2", "resources": []},
|
|
{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": query,
|
|
"name": "Извещатель", "unit": "шт.", "resources": [{"code": "1-100-40", "quantity": 1}],
|
|
"provenance": {"decree": "Приказ"}},
|
|
]}
|
|
monkeypatch.setattr(fsnb_ref, "find_gesn_composition", composition)
|
|
item = norm_finder.detail("2022", "ГЭСНм", "10-08-002-02")
|
|
assert item["name"] == "Извещатель"
|
|
assert item["provenance"]["decree"] == "Приказ"
|
|
assert item["current_price_supported"] is True
|
|
with pytest.raises(ValueError):
|
|
norm_finder.detail("2022", "ГЭСНр", "10-08-002-02")
|
|
|
|
|
|
def test_calculation_refuses_unpriced_norm_instead_of_fabricating_total(monkeypatch):
|
|
import norm_finder
|
|
|
|
monkeypatch.setattr(norm_finder, "detail", lambda *args: {
|
|
"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": "10-08-002-02",
|
|
"name": "Извещатель", "unit": "шт.", "resources": [
|
|
{"code": "91.01.01-001", "name": "Машина", "unit": "маш.-ч", "quantity": 1}],
|
|
})
|
|
with pytest.raises(ValueError, match="не поддерживается"):
|
|
norm_finder.calculate("2022", "ГЭСНм", "10-08-002-02", 100, "шт.",
|
|
"Хабаровский край (1 зона)", "4 квартал 2026")
|
|
|
|
|
|
def test_gesn_quantity_uses_base_unit_and_engine_resource_key(monkeypatch):
|
|
import norm_finder
|
|
import engine_prices
|
|
import estimate_contract as ec
|
|
monkeypatch.setattr(norm_finder, "detail", lambda *args: {
|
|
"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": "11-01-049-01",
|
|
"name": "Порог", "unit": "100 м", "resources": [
|
|
{"code": "1-100-40", "name": "Рабочий", "unit": "чел.-ч", "quantity": 1}],
|
|
})
|
|
monkeypatch.setattr(engine_prices, "resolve", lambda meta: {"status": "ok", "entry": {}})
|
|
monkeypatch.setattr(engine_prices, "load_lookup", lambda entry: object())
|
|
seen = []
|
|
def fake_calc(draft, resources, prices, basis):
|
|
seen.append((draft.positions[0].qty, sorted(resources)))
|
|
return {"status": "ok", "ok": False, "grand_total": 10.0,
|
|
"missing": [{"reason": "НР/СП"}], "unpriced": []}
|
|
monkeypatch.setattr(ec, "build_and_calc", fake_calc)
|
|
result = norm_finder.calculate("2022", "ГЭСН", "11-01-049-01", 50, "м",
|
|
"Хабаровский край (1 зона)", "4 квартал 2026")
|
|
assert seen == [(0.5, ["11-01-049-01"])]
|
|
assert result["total"] is None and result["accounted"] == 10.0
|
|
|
|
|
|
@pytest.fixture()
|
|
def api(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("DB_PATH", str(tmp_path / "finder.db"))
|
|
monkeypatch.setenv("SESSION_SECRET", "finder-test-secret")
|
|
import auth
|
|
import db
|
|
import main
|
|
for module in (db, auth, main):
|
|
importlib.reload(module)
|
|
db.init_db()
|
|
db.create_user("finder@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("finder@x")
|
|
headers = {"Authorization": "Bearer " + auth._make_token("finder@x"), "X-Tab-Id": "tab"}
|
|
return TestClient(main.app), headers, db
|
|
|
|
|
|
@pytest.mark.parametrize("method,path", [
|
|
("get", "/api/norm-finder/catalog"),
|
|
("get", "/api/norm-finder/search?q=извещатель&base=2022"),
|
|
("get", "/api/norm-finder/detail?base=2022&base_type=ГЭСНм&code=10-08-002-02"),
|
|
("get", "/api/norm-finder/prices?subject_id=264"),
|
|
("post", "/api/norm-finder/calculate"),
|
|
("get", "/api/norm-finder/quotes/1"),
|
|
("post", "/api/norm-finder/quotes/1"),
|
|
("post", "/api/norm-finder/drafts"),
|
|
("get", "/api/norm-finder/drafts/1"),
|
|
("put", "/api/norm-finder/drafts/1"),
|
|
("post", "/api/norm-finder/drafts/1/calculate"),
|
|
])
|
|
def test_finder_requires_login(api, method, path):
|
|
client, _, _ = api
|
|
assert getattr(client, method)(path).status_code == 401
|
|
|
|
|
|
def test_catalog_exposes_rate_choices_without_automatic_norm_assignment(api, monkeypatch):
|
|
import norm_finder
|
|
client, headers, _ = api
|
|
monkeypatch.setattr(norm_finder, "catalog", lambda: [])
|
|
for path, auth_headers in (("/api/public/norm-finder/catalog", {}),
|
|
("/api/norm-finder/catalog", headers)):
|
|
response = client.get(path, headers=auth_headers)
|
|
assert response.status_code == 200
|
|
rates = response.json()["rates"]
|
|
selected = next(row for row in rates if row["id"] == "1.1")
|
|
assert selected["nr_pct"] == 92 and selected["sp_pct"] == 46
|
|
assert "norm_code" not in selected
|
|
|
|
|
|
def test_finder_api_search_detail_and_catalog(api, monkeypatch):
|
|
import norm_finder
|
|
client, headers, _ = api
|
|
monkeypatch.setattr(norm_finder, "catalog", lambda: [{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "count": 100}])
|
|
monkeypatch.setattr(norm_finder, "search", lambda q, b, limit: {"status": "ok", "items": [
|
|
{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": "10-08-002-02", "name": "Извещатель", "unit": "шт."}]})
|
|
monkeypatch.setattr(norm_finder, "detail", lambda b, t, c: {"base": "ГЭСН-2022", "base_type": t,
|
|
"code": c, "name": "Извещатель", "unit": "шт.", "resources": [], "provenance": {"decree": "Приказ"}})
|
|
assert client.get("/api/norm-finder/catalog", headers=headers).json()["bases"][0]["count"] == 100
|
|
found = client.get("/api/norm-finder/search?q=извещатель&base=2022", headers=headers)
|
|
assert found.status_code == 200 and found.json()["items"][0]["code"] == "10-08-002-02"
|
|
detail = client.get("/api/norm-finder/detail?base=2022&base_type=ГЭСНм&code=10-08-002-02", headers=headers)
|
|
assert detail.status_code == 200 and detail.json()["provenance"]["decree"] == "Приказ"
|
|
|
|
|
|
def test_finder_quote_is_saved_and_revised_in_place(api, monkeypatch):
|
|
import norm_finder
|
|
import engine_prices
|
|
client, headers, db = api
|
|
monkeypatch.setattr(engine_prices, "basis_options", lambda sid: [
|
|
{"zone_id": 118, "name": "Хабаровский край (1 зона)",
|
|
"periods": [{"period_id": 428, "name": "4 квартал 2026"}]}] if sid == 264 else [])
|
|
monkeypatch.setattr(norm_finder, "calculate", lambda b, t, c, q, u, z, p: {
|
|
"status": "ok", "complete": False, "accounted": q * 100,
|
|
"base": "ГЭСН-2022", "base_type": t, "code": c, "quantity": q,
|
|
"unit": u, "zone": z, "period": p, "missing": [{"reason": "НР/СП"}]})
|
|
body = {"base": "2022", "base_type": "ГЭСНм", "code": "10-08-002-02",
|
|
"quantity": 100, "unit": "шт.", "subject_id": 264, "zone_id": 118, "period_id": 428}
|
|
assert client.post("/api/norm-finder/calculate", json={**body, "period_id": 999}, headers=headers).status_code == 400
|
|
created = client.post("/api/norm-finder/calculate", json=body, headers=headers)
|
|
assert created.status_code == 200, created.text
|
|
quote = created.json()
|
|
assert quote["result"]["accounted"] == 10000
|
|
assert db.get_history("finder@x", "tab")[-1]["role"] == "norm_quote"
|
|
url = f"/api/norm-finder/quotes/{quote['id']}"
|
|
import auth
|
|
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("other@x")
|
|
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "tab"}
|
|
assert client.get(url, headers=other).status_code == 404
|
|
assert client.post(url, json={**body, "revision": 0}, headers=other).status_code == 404
|
|
assert client.get(url, headers=headers).json()["result"]["accounted"] == 10000
|
|
updated = client.post(url, json={**body, "quantity": 75, "revision": quote["revision"]}, headers=headers)
|
|
assert updated.status_code == 200 and updated.json()["id"] == quote["id"]
|
|
assert updated.json()["result"]["accounted"] == 7500
|
|
assert client.post(url, json={**body, "quantity": 50, "revision": quote["revision"]}, headers=headers).status_code == 409
|
|
|
|
|
|
def test_finder_page_is_reachable_from_site(api):
|
|
import main
|
|
client, _, _ = api
|
|
page = client.get("/podbor")
|
|
assert page.status_code == 200
|
|
assert "Подбор норм" in page.text
|
|
assert f'src="/static/norm-finder.js?v={main.APP_VERSION}"' in page.text
|
|
assert 'href="/podbor">Найти норму без входа</a>' in client.get("/").text
|
|
assert client.get("/static/norm-finder.js").headers["Cache-Control"] == "no-cache, must-revalidate"
|
|
|
|
|
|
def test_browse_routes_bound_public_pages_and_require_auth(api, monkeypatch):
|
|
import norm_finder
|
|
client, headers, _ = api
|
|
calls = []
|
|
def fake_browse(base, base_type, path, limit, offset):
|
|
calls.append((base, base_type, path, limit, offset))
|
|
return {"children": [], "items": [{"code": "01-01-001-01"}], "has_more": False}
|
|
monkeypatch.setattr(norm_finder, "browse", fake_browse)
|
|
url = "/api/public/norm-finder/browse?base=2022&base_type=ГЭСН&path=Земляные работы&limit=20"
|
|
response = client.get(url)
|
|
assert response.status_code == 200
|
|
assert response.json()["items"][0]["code"] == "01-01-001-01"
|
|
assert calls == [("2022", "ГЭСН", "Земляные работы", 20, 0)]
|
|
assert client.get(url.replace("limit=20", "limit=21")).status_code == 400
|
|
assert client.get("/api/norm-finder/browse").status_code == 401
|
|
assert client.get("/api/norm-finder/browse", headers=headers).status_code == 200
|
|
|
|
|
|
def test_finder_draft_is_scoped_revisioned_and_never_totals_missing_costs(api, monkeypatch):
|
|
import auth
|
|
import engine_prices
|
|
import norm_finder
|
|
client, headers, db = api
|
|
monkeypatch.setattr(norm_finder, "detail", lambda base, kind, code: {
|
|
"base": "ГЭСН-2022", "base_type": kind, "code": code,
|
|
"name": "Стяжка " + code, "unit": "100 м2"})
|
|
monkeypatch.setattr(norm_finder, "calculate", lambda base, kind, code, qty, unit, zone, period: {
|
|
"status": "ok", "complete": code.endswith("-01"),
|
|
"total": qty * 100 if code.endswith("-01") else None,
|
|
"accounted": None if code.endswith("-01") else qty * 20,
|
|
"missing": [] if code.endswith("-01") else [{"reason": "Нет цены ресурса"}]})
|
|
monkeypatch.setattr(engine_prices, "basis_options", lambda sid: [{
|
|
"zone_id": 118, "name": "Хабаровский край (1 зона)",
|
|
"periods": [{"period_id": 428, "name": "4 квартал 2026"}]}] if sid == 264 else [])
|
|
positions = [{"base": "2022", "base_type": "ГЭСН", "code": "11-01-011-01",
|
|
"unit": "м2", "quantity": 50},
|
|
{"base": "2022", "base_type": "ГЭСН", "code": "11-01-011-12",
|
|
"unit": "100 м2", "quantity": 2}]
|
|
invalid = [{**positions[0], "unit": "м3"}]
|
|
assert client.post("/api/norm-finder/drafts", json={"positions": invalid}, headers=headers).status_code == 400
|
|
created = client.post("/api/norm-finder/drafts", json={"positions": positions}, headers=headers)
|
|
assert created.status_code == 200, created.text
|
|
draft = created.json()
|
|
assert draft["revision"] == 0 and len(draft["positions"]) == 2
|
|
assert db.get_history("finder@x", "tab")[-1]["role"] == "norm_draft"
|
|
url = f"/api/norm-finder/drafts/{draft['id']}"
|
|
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("other@x")
|
|
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "tab"}
|
|
wrong_tab = {**headers, "X-Tab-Id": "other-tab"}
|
|
assert client.get(url, headers=other).status_code == 404
|
|
assert client.get(url, headers=wrong_tab).status_code == 404
|
|
assert client.put(url, json={"revision": 0, "positions": positions}, headers=other).status_code == 404
|
|
updated = client.put(url, json={"revision": 0, "positions": [
|
|
{**positions[0], "quantity": 60}, positions[1]]}, headers=headers)
|
|
assert updated.status_code == 200 and updated.json()["revision"] == 1
|
|
assert client.put(url, json={"revision": 0, "positions": positions}, headers=headers).status_code == 409
|
|
calc = url + "/calculate"
|
|
basis = {"revision": 1, "subject_id": 264, "zone_id": 118, "period_id": 428}
|
|
assert client.post(calc, json={**basis, "period_id": 999}, headers=headers).status_code == 400
|
|
response = client.post(calc, json=basis, headers=headers)
|
|
assert response.status_code == 200, response.text
|
|
result = response.json()
|
|
assert result["revision"] == 2
|
|
assert result["calculation"]["complete"] is False
|
|
assert result["calculation"]["total"] is None
|
|
assert result["calculation"]["accounted"] == 6040
|
|
assert client.post(calc, json=basis, headers=headers).status_code == 409
|
|
assert client.get(url, headers=headers).json()["calculation"] == result["calculation"]
|
|
|
|
|
|
def test_chat_receives_scoped_draft_context_without_replacing_user_question(api, monkeypatch):
|
|
import auth
|
|
import main
|
|
import norm_draft
|
|
import norm_finder
|
|
client, headers, db = api
|
|
monkeypatch.setattr(norm_finder, "detail", lambda base, kind, code: {
|
|
"base": "ГЭСН-2022", "base_type": kind, "code": code,
|
|
"name": "Цементная стяжка", "unit": "100 м2"})
|
|
position = {"base": "2022", "base_type": "ГЭСН", "code": "11-01-011-01",
|
|
"quantity": 50, "unit": "м2"}
|
|
draft = client.post("/api/norm-finder/drafts", json={"positions": [position]}, headers=headers).json()
|
|
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("other@x")
|
|
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "other-tab"}
|
|
payload = {"message": "Проверь выбранные работы", "norm_draft_id": draft["id"]}
|
|
monkeypatch.setattr(main, "safe_work_dir", lambda *a, **k: None)
|
|
monkeypatch.setattr(main, "_trial_state", lambda *a: None)
|
|
assert client.post("/api/chat", json=payload, headers=other).status_code == 404
|
|
monkeypatch.setattr(main, "_check_rate_limit", lambda *a: None)
|
|
monkeypatch.setattr(main, "_refuse_if_read_only", lambda *a: None)
|
|
monkeypatch.setattr(main, "_refuse_if_trial_over", lambda *a: None)
|
|
async def no_limits(*args):
|
|
return None
|
|
monkeypatch.setattr(main, "_check_limits", no_limits)
|
|
monkeypatch.setattr(db, "get_app_setting", lambda key, default=None: "off")
|
|
seen = []
|
|
async def fake_stream(message, user, tab, context=""):
|
|
seen.append((message, context))
|
|
yield 'event: done\ndata: {"result":"ok"}\n\n'
|
|
monkeypatch.setattr(main, "_stream_and_save", fake_stream)
|
|
response = client.post("/api/chat", json=payload, headers=headers)
|
|
assert response.status_code == 200, response.text
|
|
assert seen[0][0] == "Проверь выбранные работы"
|
|
assert "11-01-011-01" in seen[0][1] and "50.0" in seen[0][1]
|
|
assert "ПОДБОРКА" in seen[0][1]
|
|
assert "total" not in norm_draft.agent_context({"positions": draft["positions"],
|
|
"calculation": {"complete": False, "total": 9999}})
|
|
|
|
|
|
def test_public_norm_catalog_is_read_only_bounded_and_anonymous(api, monkeypatch):
|
|
import main
|
|
import norm_finder
|
|
client, _, _ = api
|
|
main._public_finder_rate.clear()
|
|
monkeypatch.setattr(norm_finder, "catalog", lambda: [{"base": "ГЭСН-2022", "count": 56192}])
|
|
monkeypatch.setattr(norm_finder, "search", lambda q, base, limit: {
|
|
"status": "ok", "items": [{"code": "11-01-011-01", "name": "Стяжка"}], "shown": 1})
|
|
monkeypatch.setattr(norm_finder, "detail", lambda base, kind, code: {
|
|
"base": "ГЭСН-2022", "base_type": kind, "code": code, "name": "Стяжка", "resources": []})
|
|
assert client.get("/api/public/norm-finder/catalog").status_code == 200
|
|
assert client.get("/api/public/norm-finder/catalog", headers={
|
|
"Authorization": "Bearer ", "X-Tab-Id": "guest-tab"}).status_code == 200
|
|
assert client.get("/api/public/norm-finder/search?q=стяжка").json()["items"][0]["code"] == "11-01-011-01"
|
|
assert client.get("/api/public/norm-finder/detail?base=2022&base_type=ГЭСН&code=11-01-011-01").status_code == 200
|
|
assert client.get("/api/public/norm-finder/search?q=стяжка&limit=9").status_code == 400
|
|
assert client.post("/api/norm-finder/drafts", json={"positions": []}).status_code == 401
|
|
for _ in range(25):
|
|
assert client.get("/api/public/norm-finder/search?q=стяжка").status_code == 200
|
|
blocked = client.get("/api/public/norm-finder/search?q=стяжка")
|
|
assert blocked.status_code == 429 and blocked.headers["Retry-After"] == "60"
|