diff --git a/estimate_contract.py b/estimate_contract.py index 25f4a46..75121bb 100644 --- a/estimate_contract.py +++ b/estimate_contract.py @@ -7,6 +7,7 @@ LLM выдаёт EstimateDraft (список позиций: код+объём) """ from __future__ import annotations +import os import sys from pathlib import Path @@ -16,10 +17,18 @@ from pydantic import BaseModel, Field _SR = Path(__file__).resolve().parent.parent / "smeta-railway" / "src" if _SR.exists() and str(_SR) not in sys.path: sys.path.insert(0, str(_SR)) +_SR_ROOT = _SR.parent # ~/smeta-railway — тут resources.json и fgis_split_form.xlsx import estimate_verify # noqa: E402 +def engine_enabled() -> bool: + """Флаг go-live движка (срез 4.4). Владелец: включать сразу по готовности. + Значение по умолчанию OFF — чтобы код можно было выкатить инертно и проверить + на реальных данных ДО включения. Включается ESTIMATE_ENGINE=on в .env.""" + return os.environ.get("ESTIMATE_ENGINE", "off").strip().lower() in ("on", "1", "true", "yes") + + class DraftPosition(BaseModel): code: str qty: float @@ -70,4 +79,38 @@ def build_and_calc(draft: EstimateDraft, resources: dict, fgis) -> dict: "missing": result.missing, "verify": v, "positions_count": len(result.positions), + "positions": norm["positions"], } + + +# Ленивый кэш реальных ресурсов/ФГИС (тяжёлые: ~24k расценок + прайс-лист ФГИС). +_RES_CACHE = None +_FGIS_CACHE = None + + +def _load_engine_data(): + """Загрузить реальные resources.json + fgis_split_form.xlsx (один раз на процесс).""" + global _RES_CACHE, _FGIS_CACHE + if _RES_CACHE is None or _FGIS_CACHE is None: + from smeta_railway.data.gesn import load_resources + from smeta_railway.data.fgis import load_fgis + res_path = _SR_ROOT / "resources.json" + fgis_xlsx = _SR_ROOT / "fgis_split_form.xlsx" + fgis_cache = _SR_ROOT / "fgis_cache.pkl" + _RES_CACHE = load_resources(res_path) + _FGIS_CACHE = load_fgis(str(fgis_xlsx), str(fgis_cache)) + return _RES_CACHE, _FGIS_CACHE + + +def calc_estimate(positions: list[dict], meta: dict | None = None) -> dict: + """Детерминированный расчёт сметы по позициям (код+объём) на РЕАЛЬНЫХ данных. + positions: [{code, qty, unit?, name?}]. Возвращает то же, что build_and_calc + (ok, grand_total, missing, verify, positions). Числа — только из движка, не из LLM. + Не готово к включению (ESTIMATE_ENGINE=off) → вызывающий сам решает; функция считает + всегда (флаг проверяет вызывающий на границе агент/эндпоинт).""" + resources, fgis = _load_engine_data() + draft = EstimateDraft( + meta=DraftMeta(**(meta or {})), + positions=[DraftPosition(**p) for p in positions], + ) + return build_and_calc(draft, resources, fgis) diff --git a/tests/test_engine_contract.py b/tests/test_engine_contract.py index c5144d3..bbf9414 100644 --- a/tests/test_engine_contract.py +++ b/tests/test_engine_contract.py @@ -55,3 +55,19 @@ def test_missing_labor_price_fails_loud(): r = ec.build_and_calc(_draft(2), _resources(), FGISLookup()) assert r["ok"] is False assert any("труд" in m["code"] for m in r["missing"]) + + +def test_calc_estimate_uses_positions_dicts(monkeypatch): + # calc_estimate принимает [{code, qty}] и считает через build_and_calc на данных + monkeypatch.setattr(ec, "_load_engine_data", lambda: (_resources(), _fgis())) + r = ec.calc_estimate([{"code": "ГЭСН 01-01-001-01", "unit": "м3", "qty": 2}]) + assert r["ok"] is True and r["grand_total"] == 4380.0 + + +def test_engine_flag(monkeypatch): + monkeypatch.setenv("ESTIMATE_ENGINE", "off") + assert ec.engine_enabled() is False + monkeypatch.setenv("ESTIMATE_ENGINE", "on") + assert ec.engine_enabled() is True + monkeypatch.setenv("ESTIMATE_ENGINE", "1") + assert ec.engine_enabled() is True