feat(ТСН): проверка позиций сметы по базе (T10, ядро)
Шифр и единица проверяются уверенно; деньги — только в базисе 2000, иначе позиция в unchecked с причиной (индексов по видам работ ещё нет). 5 проверок. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
"""Проверка сметы по ТСН (T10): код, единица, деньги только там, где можно."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import ext_state # noqa: E402
|
||||
import scripts.build_tsn_ref as build_mod # noqa: E402
|
||||
import tsn_verify # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def db(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path / "ext")
|
||||
(tmp_path / "ext").mkdir()
|
||||
d = tmp_path / "ext" / "snapshots" / "niac_tsn" / "s" / "k"
|
||||
d.mkdir(parents=True)
|
||||
extract = {"works": [{"code": "1-1-1", "name": "Земляные работы", "unit": "100 м3",
|
||||
"pz": 30.0, "ot": 10.0, "em": 20.0, "mat": 0.0, "labor": 0.5,
|
||||
"page": 17}], "stats": {"works_parsed": 1}}
|
||||
(d / "extract.json").write_text(json.dumps(extract), encoding="utf-8")
|
||||
(d / "meta.json").write_text(json.dumps({"key": "k", "kind": "rate_book",
|
||||
"book": "ТСН-2001.3", "chapter": "1-1",
|
||||
"edition": "", "addendum_no": ""}), encoding="utf-8")
|
||||
out = tmp_path / "tsn.sqlite"
|
||||
build_mod.build(tmp_path / "ext", out)
|
||||
monkeypatch.setenv("TSN_REF_PATH", str(out))
|
||||
return out
|
||||
|
||||
|
||||
def test_good_position_passes(db):
|
||||
rep = tsn_verify.verify([{"code": "1-1-1", "unit": "100 м3", "qty": 2.0}], base="ТСН-2001")
|
||||
assert rep["ok"] is True and rep["checked"] == 1 and rep["errors"] == []
|
||||
|
||||
|
||||
def test_unit_mismatch_is_error(db):
|
||||
rep = tsn_verify.verify([{"code": "1-1-1", "unit": "шт", "qty": 1}], base="ТСН-2001")
|
||||
assert rep["ok"] is False
|
||||
assert any(e["rule"] == "единица" for e in rep["errors"])
|
||||
|
||||
|
||||
def test_unknown_code_is_error(db):
|
||||
rep = tsn_verify.verify([{"code": "9-9-9", "unit": "м3", "qty": 1}], base="ТСН-2001")
|
||||
assert rep["ok"] is False
|
||||
assert any("отсутствует" in e["rule"] for e in rep["errors"])
|
||||
|
||||
|
||||
def test_current_price_is_unchecked_not_judged(db):
|
||||
rep = tsn_verify.verify([{"code": "1-1-1", "unit": "100 м3", "qty": 1,
|
||||
"unit_cost": 555.0, "price_level": "IV квартал 2026"}],
|
||||
base="ТСН-2001")
|
||||
assert rep["ok"] is True
|
||||
assert any("индекс" in u["reason"].lower() for u in rep["unchecked"])
|
||||
|
||||
|
||||
def test_base_price_checked_against_pz(db):
|
||||
rep = tsn_verify.verify([{"code": "1-1-1", "unit": "100 м3", "qty": 1,
|
||||
"unit_cost": 99.0, "price_level": "01.01.2000"}],
|
||||
base="ТСН-2001")
|
||||
assert rep["ok"] is False
|
||||
assert any(e["rule"] == "цена" for e in rep["errors"])
|
||||
@@ -0,0 +1,64 @@
|
||||
"""tsn_verify — проверка позиций сметы по базе ТСН (T10).
|
||||
|
||||
Что проверяется уверенно: шифр есть в базе, единица измерения совпадает. Деньги —
|
||||
только если цена позиции в базисе 2000 года: тогда сравниваем с ПЗ расценки.
|
||||
Цена в текущем уровне требует индекса по виду работ, которого в базе пока нет;
|
||||
такая позиция уходит в `unchecked` с причиной, а не в «ошибку» и не в «всё хорошо».
|
||||
|
||||
Точность важнее полноты: спорное — предупреждение, неоценимое — `unchecked`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import tsn_ref
|
||||
|
||||
_UNIT_ALIASES = {"м3": "м3", "куб.м": "м3", "куб м": "м3", "m3": "м3",
|
||||
"м2": "м2", "кв.м": "м2", "m2": "м2", "шт": "шт", "шт.": "шт",
|
||||
"т": "т", "тонн": "т", "чел.-ч": "чел.-ч", "маш.-ч": "маш.-ч"}
|
||||
|
||||
|
||||
def _unit(value: str | None) -> str:
|
||||
u = (value or "").strip().lower().replace("³", "3").replace("²", "2")
|
||||
u = re.sub(r"\s+", " ", u)
|
||||
return _UNIT_ALIASES.get(u, u)
|
||||
|
||||
|
||||
def verify(positions: list[dict], *, base: str, as_of: str | None = None) -> dict:
|
||||
errors: list[dict] = []
|
||||
unchecked: list[dict] = []
|
||||
warnings: list[dict] = []
|
||||
checked = 0
|
||||
for p in positions or []:
|
||||
code = str(p.get("code") or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
found = tsn_ref.find_work(code, as_of=as_of, limit=1)
|
||||
if found.get("status") != "ok":
|
||||
errors.append({"rule": "шифр отсутствует в базе", "code": code,
|
||||
"expected": "расценка ТСН", "actual": found.get("status"),
|
||||
"page": None})
|
||||
continue
|
||||
work = found["items"][0]
|
||||
if _unit(p.get("unit")) != _unit(work.get("unit")):
|
||||
errors.append({"rule": "единица", "code": code,
|
||||
"expected": work.get("unit"), "actual": p.get("unit"),
|
||||
"page": work.get("page")})
|
||||
continue
|
||||
checked += 1 # шифр и единица подтверждены — позиция проверена по норме
|
||||
price_level = str(p.get("price_level") or "").strip()
|
||||
cost = p.get("unit_cost")
|
||||
if cost is None:
|
||||
warnings.append({"rule": "цена позиции не указана", "code": code})
|
||||
elif price_level in ("01.01.2000", "2000", "базис 2000"):
|
||||
if work.get("pz") is not None and abs(float(cost) - work["pz"]) > max(0.01, work["pz"] * 0.01):
|
||||
errors.append({"rule": "цена", "code": code, "expected": work["pz"],
|
||||
"actual": cost, "page": work.get("page")})
|
||||
continue
|
||||
else:
|
||||
unchecked.append({"code": code,
|
||||
"reason": "цена в текущем уровне: индексы по видам работ "
|
||||
"в базе ещё не разобраны — не сужу"})
|
||||
ok = not errors
|
||||
return {"ok": ok, "base": base, "checked": checked, "errors": errors,
|
||||
"warnings": warnings, "unchecked": unchecked}
|
||||
Reference in New Issue
Block a user