feat(ТСН): НР/СП из сборника .8 — разбор, хранение и начисление от ФОТ

План T8 требовал НР/СП по видам работ; до сих пор их не было вовсе.
- tsn_parse: разбор таблицы .8 (номер, название с переносами и подпунктами,
  два процента справа); на настоящем сборнике 58 видов работ.
- build_tsn_ref: таблица nr_sp, схема 3; отчёт считает nr_sp.
- ext_pull: разбор .8 идёт через parse_nr_sp.
- tsn_ref.find_nr_sp: поиск нормы по виду работ с провенансом.
- tsn_calc.calc_position(work_type=…): НР и СП от текущей заработной платы (ОТ),
  итог = ПЗ + НР + СП; без вида работ или без ставки — nr_sp_incomplete, итог без
  НР/СП (прямые затраты), не «0» и не выдуманное число.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
anor
2026-11-18 04:39:56 +10:00
co-authored by Claude Code
parent 6381e2625f
commit 3764b67064
8 changed files with 232 additions and 6 deletions
+3
View File
@@ -386,6 +386,9 @@ def pull_niac_tsn(docs: list[dict] | None = None, scope: str = "v1", client=None
elif doc["kind"] in ("price_book", "machine_book"): elif doc["kind"] in ("price_book", "machine_book"):
extract = tsn_parse.parse_price_book(str(dest), doc) extract = tsn_parse.parse_price_book(str(dest), doc)
works_n = extract.get("stats", {}).get("items_parsed", 0) works_n = extract.get("stats", {}).get("items_parsed", 0)
elif doc["kind"] == "nr_sp":
extract = tsn_parse.parse_nr_sp(str(dest), doc)
works_n = extract.get("stats", {}).get("items_parsed", 0)
else: else:
extract = tsn_parse.parse_rate_book(str(dest), doc) extract = tsn_parse.parse_rate_book(str(dest), doc)
works_n = extract.get("stats", {}).get("works_parsed", 0) works_n = extract.get("stats", {}).get("works_parsed", 0)
+19 -2
View File
@@ -59,6 +59,11 @@ CREATE INDEX idx_tsn_works_name ON works(name);
CREATE TABLE work_resources( CREATE TABLE work_resources(
work_id INTEGER NOT NULL REFERENCES works(work_id), seq INTEGER NOT NULL, work_id INTEGER NOT NULL REFERENCES works(work_id), seq INTEGER NOT NULL,
code TEXT NOT NULL, quantity REAL, PRIMARY KEY(work_id, seq)); code TEXT NOT NULL, quantity REAL, PRIMARY KEY(work_id, seq));
CREATE TABLE nr_sp(
nr_id INTEGER PRIMARY KEY, release_id INTEGER NOT NULL REFERENCES release(release_id),
source_id INTEGER NOT NULL REFERENCES sources(source_id),
work_type TEXT NOT NULL, overhead REAL, profit REAL, page INTEGER);
CREATE INDEX idx_tsn_nr_type ON nr_sp(work_type);
CREATE TABLE price_items( CREATE TABLE price_items(
item_id INTEGER PRIMARY KEY, release_id INTEGER NOT NULL REFERENCES release(release_id), item_id INTEGER PRIMARY KEY, release_id INTEGER NOT NULL REFERENCES release(release_id),
source_id INTEGER NOT NULL REFERENCES sources(source_id), source_id INTEGER NOT NULL REFERENCES sources(source_id),
@@ -122,7 +127,7 @@ def build(snapshots: os.PathLike | str, out_path: os.PathLike | str) -> dict:
seen: dict[tuple, float | None] = {} seen: dict[tuple, float | None] = {}
seen_items: dict[str, tuple[float, int]] = {} seen_items: dict[str, tuple[float, int]] = {}
src_id = 0 src_id = 0
docs_n = works_n = values_n = items_n = 0 docs_n = works_n = values_n = items_n = nr_n = 0
for meta, extract in _docs(snapshots): for meta, extract in _docs(snapshots):
docs_n += 1 docs_n += 1
src_id += 1 src_id += 1
@@ -155,6 +160,18 @@ def build(snapshots: os.PathLike | str, out_path: os.PathLike | str) -> dict:
(len(extract.get("values", [])), source_id)) (len(extract.get("values", [])), source_id))
continue continue
# Нормы накладных расходов и сметной прибыли (.8): проценты по видам работ.
if kind == "nr_sp":
for it in extract.get("items", []):
con.execute("INSERT INTO nr_sp(release_id, source_id, work_type, overhead,"
" profit, page) VALUES(1,?,?,?,?,?)",
(source_id, it.get("work_type") or "", it.get("overhead"),
it.get("profit"), it.get("page")))
nr_n += 1
con.execute("UPDATE sources SET values_n=? WHERE source_id=?",
(len(extract.get("items", [])), source_id))
continue
# Ценовые справочники .1/.2 дают цены ресурсов (материалы/машины) — это # Ценовые справочники .1/.2 дают цены ресурсов (материалы/машины) — это
# не расценки: отдельная таблица, свой поиск. # не расценки: отдельная таблица, свой поиск.
if kind in ("price_book", "machine_book"): if kind in ("price_book", "machine_book"):
@@ -235,7 +252,7 @@ def build(snapshots: os.PathLike | str, out_path: os.PathLike | str) -> dict:
con.close() con.close()
report = {"ok": not problems, "problems": problems, "db": str(out_path), report = {"ok": not problems, "problems": problems, "db": str(out_path),
"docs": docs_n, "works": works_n, "values": values_n, "docs": docs_n, "works": works_n, "values": values_n,
"price_items": items_n} "price_items": items_n, "nr_sp": nr_n}
Path(str(out_path) + ".report.json").write_text( Path(str(out_path) + ".report.json").write_text(
json.dumps(report, ensure_ascii=False, indent=1), encoding="utf-8") json.dumps(report, ensure_ascii=False, indent=1), encoding="utf-8")
return report return report
+53
View File
@@ -68,3 +68,56 @@ def test_estimate_refuses_when_any_position_unpriced(tmp_path, monkeypatch):
assert rep["status"] == "index_unavailable" assert rep["status"] == "index_unavailable"
assert rep["grand_total"] is None assert rep["grand_total"] is None
assert rep["missing"][0]["code"] == "1-5-1" assert rep["missing"][0]["code"] == "1-5-1"
def test_calc_position_adds_nr_sp_from_work_type(monkeypatch):
"""НР и СП начисляются от ФОТ (ОТ) по норме вида работ; итог = ПЗ + НР + СП."""
import tsn_calc, tsn_ref
monkeypatch.setattr(tsn_ref, "find_work", lambda q, as_of=None, limit=5: {
"status": "ok", "items": [{"code": "1-5-1", "book": "ТСН-2001.3", "chapter": "3-1",
"pz": 1000.0, "ot": 100.0, "em": 900.0, "mat": 0.0,
"unit": "100 м3", "addendum_no": "", "edition": ""}]})
monkeypatch.setattr(tsn_calc, "find_rate_index", lambda w, as_of=None: {
"status": "ok", "value": 5.5, "issue_no": "222", "quarter": 4, "year": 2026})
monkeypatch.setattr(tsn_ref, "find_nr_sp", lambda q: {
"status": "ok", "items": [{"work_type": "Земляные работы", "overhead": 95.0,
"profit": 50.0}]})
res = tsn_calc.calc_position("1-5-1", work_type="Земляные работы")
assert res["current"]["pz"] == 5500.0
assert res["nr_sp"]["overhead"] == 522.5 # 5500 × 0.95
assert res["nr_sp"]["profit"] == 275.0 # 5500 × 0.50
assert res["total"] == 6297.5
assert res["nr_sp_incomplete"] is False
def test_calc_position_without_work_type_is_incomplete(monkeypatch):
import tsn_calc, tsn_ref
monkeypatch.setattr(tsn_ref, "find_work", lambda q, as_of=None, limit=5: {
"status": "ok", "items": [{"code": "1-5-1", "book": "ТСН-2001.3", "chapter": "3-1",
"pz": 1000.0, "ot": 100.0, "em": 900.0, "mat": 0.0,
"unit": "100 м3", "addendum_no": "", "edition": ""}]})
monkeypatch.setattr(tsn_calc, "find_rate_index", lambda w, as_of=None: {
"status": "ok", "value": 5.5, "issue_no": "222", "quarter": 4, "year": 2026})
res = tsn_calc.calc_position("1-5-1")
assert res["nr_sp_incomplete"] is True
assert res["nr_sp"] is None
# сумма без НР/СП — это прямые затраты, а не ноль и не выдумка
assert res["total"] == 5500.0
assert "НР" in res["message"] or "вид работ" in res["message"]
def test_missing_profit_rate_marks_incomplete(monkeypatch):
"""Ставка есть, но прибыль не задана — считаем НР и помечаем неполноту."""
import tsn_calc, tsn_ref
monkeypatch.setattr(tsn_ref, "find_work", lambda q, as_of=None, limit=5: {
"status": "ok", "items": [{"code": "1-5-1", "book": "ТСН-2001.3", "chapter": "3-1",
"pz": 1000.0, "ot": 100.0, "em": 900.0, "mat": 0.0,
"unit": "100 м3", "addendum_no": "", "edition": ""}]})
monkeypatch.setattr(tsn_calc, "find_rate_index", lambda w, as_of=None: {
"status": "ok", "value": 5.5, "issue_no": "222", "quarter": 4, "year": 2026})
monkeypatch.setattr(tsn_ref, "find_nr_sp", lambda q: {
"status": "ok", "items": [{"work_type": "Земляные работы", "overhead": 95.0,
"profit": None}]})
res = tsn_calc.calc_position("1-5-1", work_type="Земляные работы")
assert res["nr_sp_incomplete"] is True and res["nr_sp"] is None
assert res["total"] == 6022.5, res # 5500 + 522,5 без прибыли
+30
View File
@@ -183,3 +183,33 @@ def test_unit_state_belongs_to_its_table():
assert u("100 м3", "Таблица 1-1 (продолжение)") == "100 м3" assert u("100 м3", "Таблица 1-1 (продолжение)") == "100 м3"
assert u("100 м3", "Прямые затраты") == "100 м3" assert u("100 м3", "Прямые затраты") == "100 м3"
assert u("", "Измеритель:") == "" assert u("", "Измеритель:") == ""
def test_nr_sp_items_from_lines():
"""Таблица НР/СП .8: номер, название (может переноситься), два процента справа.
Строка-заголовок без процентов позиции не даёт."""
def line(y, words):
return [(x, y, w) for x, w in words]
lines = [
line(0, [(57, "5."), (97, "Бетонные,"), (143, "железобетонные"),
(217, "конструкции"), (274, "монолитные"), (410, "98"), (496, "70")]),
line(12, [(57, "7."), (97, "Комплекс"), (142, "работ"), (168, "по"),
(181, "монтажу"), (221, "конструкций")]),
line(24, [(97, "жилых"), (129, "домов")]),
line(36, [(57, "7.01."), (97, "Нулевой"), (136, "цикл,"), (162, "подземная"),
(209, "часть"), (408, "151"), (493, "130")]),
]
items = tsn_parse._nr_sp_items(lines, page=2)
assert [i["work_type"] for i in items] == [
"Бетонные, железобетонные конструкции монолитные",
"Комплекс работ по монтажу конструкций жилых домов Нулевой цикл, подземная часть"], items
assert items[0]["overhead"] == 98 and items[0]["profit"] == 70
assert items[1]["overhead"] == 151 and items[1]["profit"] == 130
grouped = [
line(0, [(57, "1."), (97, "Земляные"), (141, "работы,"), (177, "выполняемые:")]),
line(12, [(57, "1.01."), (97, "Механизированным"), (185, "способом"),
(410, "98"), (496, "77")]),
]
got = tsn_parse._nr_sp_items(grouped, page=1)
assert got[0]["work_type"] == "Земляные работы, выполняемые: Механизированным способом", got
+13
View File
@@ -62,6 +62,10 @@ def built(tmp_path, monkeypatch):
_snap(snaps, "mach", "machine_book", _items_extract( _snap(snaps, "mach", "machine_book", _items_extract(
[{"code": "2.1-1-13", "name": "Экскаватор", "unit": "маш.-ч", "price": 241.75, "page": 5}]), [{"code": "2.1-1-13", "name": "Экскаватор", "unit": "маш.-ч", "price": 241.75, "page": 5}]),
book="ТСН-2001.2") book="ТСН-2001.2")
_snap(snaps, "nr", "nr_sp", {"items": [
{"work_type": "Земляные работы, выполняемые: Механизированным способом",
"overhead": 98.0, "profit": 77.0, "page": 1}],
"stats": {"items_parsed": 1}}, book="ТСН-2001.8")
out = tmp_path / "tsn_ref.sqlite" out = tmp_path / "tsn_ref.sqlite"
report = build_mod.build(snaps, out) report = build_mod.build(snaps, out)
return {"db": out, "report": report, "tmp": tmp_path} return {"db": out, "report": report, "tmp": tmp_path}
@@ -252,3 +256,12 @@ def test_tsn_ref_imports_without_ext_state_when_path_given(tmp_path):
cwd=tmp_path, env=env, capture_output=True, text=True) cwd=tmp_path, env=env, capture_output=True, text=True)
assert r.returncode == 0, r.stderr assert r.returncode == 0, r.stderr
assert str(tmp_path / "x.sqlite") in r.stdout assert str(tmp_path / "x.sqlite") in r.stdout
def test_find_nr_sp_by_type(built, monkeypatch):
monkeypatch.setenv("TSN_REF_PATH", str(built["db"]))
got = tsn_ref.find_nr_sp("Земляные работы, выполняемые: Механизированным способом")
assert got["status"] == "ok" and got["items"][0]["overhead"] == 98.0
part = tsn_ref.find_nr_sp("механизированным")
assert part["status"] == "ok", part
assert tsn_ref.find_nr_sp("такого вида нет")["status"] == "not_found"
+27 -3
View File
@@ -55,8 +55,14 @@ def _money(value: float | None) -> float | None:
return float(Decimal(str(value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) return float(Decimal(str(value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
def calc_position(code: str, qty: float = 1.0, *, as_of: str | None = None) -> dict: def calc_position(code: str, qty: float = 1.0, *, as_of: str | None = None,
"""Стоимость позиции: базис из базы, текущая — только при найденном коэффициенте.""" work_type: str | None = None) -> dict:
"""Стоимость позиции: базис, текущая (базис × коэффициент) и НР/СП от ФОТ.
НР/СП начисляются только когда назван вид работ и он есть в сборнике .8
(проценты к заработной плате рабочих). Без вида работ итог — прямые затраты,
с пометой `nr_sp_incomplete`, а не «0» и не выдуманное число.
"""
found = tsn_ref.find_work(code, as_of=as_of, limit=1) found = tsn_ref.find_work(code, as_of=as_of, limit=1)
if found.get("status") != "ok": if found.get("status") != "ok":
return {"status": found.get("status", "not_found"), "code": code, return {"status": found.get("status", "not_found"), "code": code,
@@ -70,9 +76,27 @@ def calc_position(code: str, qty: float = 1.0, *, as_of: str | None = None) -> d
"message": idx.get("message", "коэффициент не найден")} "message": idx.get("message", "коэффициент не найден")}
k = idx["value"] k = idx["value"]
current = {name: _money((base[name] or 0) * k * qty) for name in ("pz", "ot", "em", "mat")} current = {name: _money((base[name] or 0) * k * qty) for name in ("pz", "ot", "em", "mat")}
nr = sp = None
incomplete = True
if work_type:
got = tsn_ref.find_nr_sp(work_type)
if got.get("status") == "ok" and got["items"]:
rate = got["items"][0]
ot = current.get("ot") or 0
if rate.get("overhead") is not None:
nr = _money(ot * rate["overhead"] / 100.0)
if rate.get("profit") is not None:
sp = _money(ot * rate["profit"] / 100.0)
incomplete = nr is None or sp is None
total = _money((current.get("pz") or 0) + (nr or 0) + (sp or 0))
return {"status": "ok", "code": code, "base": base, "current": current, return {"status": "ok", "code": code, "base": base, "current": current,
"method": "rate_index", "index": idx, "method": "rate_index", "index": idx,
"message": f"текущая цена = база 2000 × {k} (выпуск {idx.get('issue_no')})"} "nr_sp": {"overhead": nr, "profit": sp} if not incomplete else None,
"nr_sp_incomplete": incomplete, "total": total,
"message": (f"текущая цена = база 2000 × {k} (выпуск {idx.get('issue_no')})"
+ ("" if not incomplete else
"; НР/СП не начислены: вид работ не назван или норма не найдена — "
"итог без них, расчёт неполный"))}
def calc_estimate(positions: list[dict], *, as_of: str | None = None) -> dict: def calc_estimate(positions: list[dict], *, as_of: str | None = None) -> dict:
+55
View File
@@ -378,6 +378,61 @@ def _unit_of_tokens(tokens: list[str]) -> str:
return unit[:-1] + "." if unit.endswith(",") else unit return unit[:-1] + "." if unit.endswith(",") else unit
NR_NUM_X = 400 # в таблице .8 проценты стоят справа от x=400
def _nr_sp_items(lines: list, page: int = 0) -> list[dict]:
"""Строки таблицы НР/СП: номер позиции, название (может переноситься), два процента.
Заголовки групп без процентов позиции не дают, но их текст прилипает к следующей
названной строке — так «Комплекс работ по монтажу конструкций крупнопанельных /
жилых домов» не теряется.
"""
items: list[dict] = []
pending, group, group_no = "", "", ""
for line in lines:
words = sorted(line)
if not words:
continue
num = words[0][2] if words[0][0] < 90 else ""
is_number = bool(re.match(r"^\d+(?:\.\d+)*\.$", num))
text = " ".join(w for x, _, w in words if 90 <= x < NR_NUM_X)
nums = [w for x, _, w in words if x >= NR_NUM_X]
if is_number and not nums:
group, group_no, pending = text, num.rstrip("."), text
continue
if is_number:
# подпункт «1.01.» наследует название группы «1. Земляные работы, выполняемые:»
prefix = group if group_no and num.startswith(group_no + ".") else ""
pending = f"{prefix} {text}".strip() if prefix else text
elif text and not nums:
pending = (pending + " " + text).strip()
if group_no:
group = (group + " " + text).strip()
if len(nums) >= 2 and pending:
over = _num(nums[0])
prof = _num(nums[1])
if over is not None and prof is not None:
items.append({"work_type": pending, "overhead": over, "profit": prof,
"page": page})
pending = ""
return items
def parse_nr_sp(path: str, meta: dict | None = None) -> dict:
"""Сборник ТСН-2001.8: нормы накладных расходов и сметной прибыли по видам работ."""
meta = meta or {}
items: list[dict] = []
pages_total = 0
with fitz.open(path) as doc:
pages_total = doc.page_count
for pno in range(pages_total):
items.extend(_nr_sp_items(_lines(doc[pno].get_text("words")), page=pno + 1))
return {"items": items, "book": meta.get("book") or "ТСН-2001.8",
"stats": {"pages_total": pages_total, "items_parsed": len(items)},
"file": meta.get("file")}
def parse_price_book(path: str, meta: dict | None = None) -> dict: def parse_price_book(path: str, meta: dict | None = None) -> dict:
"""Сметные цены ресурсов из справочника .1 (материалы) или .2 (машины). """Сметные цены ресурсов из справочника .1 (материалы) или .2 (машины).
+32 -1
View File
@@ -16,7 +16,7 @@ import sqlite3
from pathlib import Path from pathlib import Path
SCHEMA_VERSION = 2 # 2 — добавлены цены ресурсов .1/.2 (price_items) SCHEMA_VERSION = 3 # 3 — НР/СП из .8; 2 — цены ресурсов .1/.2
def db_path() -> Path: def db_path() -> Path:
@@ -51,6 +51,7 @@ def _problem_of(path: Path | None = None) -> str | None:
return "schema_mismatch" return "schema_mismatch"
con.execute("SELECT COUNT(*) FROM works").fetchone() con.execute("SELECT COUNT(*) FROM works").fetchone()
con.execute("SELECT COUNT(*) FROM price_items").fetchone() con.execute("SELECT COUNT(*) FROM price_items").fetchone()
con.execute("SELECT COUNT(*) FROM nr_sp").fetchone()
finally: finally:
con.close() con.close()
except sqlite3.DatabaseError: except sqlite3.DatabaseError:
@@ -69,6 +70,7 @@ def verify_db(path) -> dict:
return {"ok": True, "works": con.execute("SELECT COUNT(*) FROM works").fetchone()[0], return {"ok": True, "works": con.execute("SELECT COUNT(*) FROM works").fetchone()[0],
"values": con.execute("SELECT COUNT(*) FROM index_values").fetchone()[0], "values": con.execute("SELECT COUNT(*) FROM index_values").fetchone()[0],
"items": con.execute("SELECT COUNT(*) FROM price_items").fetchone()[0], "items": con.execute("SELECT COUNT(*) FROM price_items").fetchone()[0],
"nr_sp": con.execute("SELECT COUNT(*) FROM nr_sp").fetchone()[0],
"schema_version": SCHEMA_VERSION} "schema_version": SCHEMA_VERSION}
finally: finally:
con.close() con.close()
@@ -212,6 +214,35 @@ def find_item(query: str, *, as_of: str | None = None, limit: int = 5) -> dict:
con.close() con.close()
def find_nr_sp(query: str, limit: int = 5) -> dict:
"""Норма НР/СП по виду работ (.8). Ставки печатаются в процентах к ФОТ."""
status = _problem_of()
if status:
return _fail(status)
q = (query or "").strip()
if not q:
return {"status": "not_found", "items": [], "message": "Пустой запрос."}
con = _connect(db_path())
try:
sql = ("SELECT n.*, s.file, s.sha256, s.url FROM nr_sp n"
" JOIN sources s ON s.source_id=n.source_id")
rows = con.execute(sql + " WHERE n.work_type = ? COLLATE NOCASE LIMIT ?",
(q, limit)).fetchall()
if not rows:
rows = con.execute(sql + " WHERE py_lower(n.work_type) LIKE ? LIMIT ?",
(f"%{q.lower()}%", limit)).fetchall()
if not rows:
return {"status": "not_found", "items": [],
"message": f"Вид работ {q!r} в сборнике НР/СП не найден — итог без НР/СП."}
items = [{"work_type": r["work_type"], "overhead": r["overhead"],
"profit": r["profit"], "page": r["page"],
"provenance": {"file": r["file"], "sha256": r["sha256"], "url": r["url"]}}
for r in rows]
return {"status": "ok", "items": items, "message": ""}
finally:
con.close()
_Q_RE = __import__("re").compile(r"^(\d{4})-Q([1-4])$|^(I{1,3}V?|IV)\s*квартал\s*(\d{4})$", __import__("re").IGNORECASE) _Q_RE = __import__("re").compile(r"^(\d{4})-Q([1-4])$|^(I{1,3}V?|IV)\s*квартал\s*(\d{4})$", __import__("re").IGNORECASE)
_ROMAN = {"I": 1, "II": 2, "III": 3, "IV": 4} _ROMAN = {"I": 1, "II": 2, "III": 3, "IV": 4}