Files
anorandClaude Code d752339315 fix(ТСН): при нулевой оплате труда НР/СП не начисляются и расчёт помечен неполным
У машинных расценок ОТ=0 (зарплата внутри «Эксплуатации машин»): процент от нуля давал
0,0 как будто норма применена. Теперь это nr_sp_incomplete с прямыми затратами в итоге.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-18 04:45:43 +10:00

143 lines
7.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Расчёт по ТСН (T8): базис есть всегда, текущая цена — только с коэффициентом."""
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_calc # noqa: E402
def _db(tmp_path, monkeypatch, with_index: bool):
monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path / "ext")
(tmp_path / "ext").mkdir()
base = tmp_path / "ext" / "snapshots" / "niac_tsn" / "s"
d = base / "rates"
d.mkdir(parents=True)
(d / "extract.json").write_text(json.dumps({"works": [{
"code": "1-5-1", "name": "Разработка грунта", "unit": "100 м3",
"pz": 320.63, "ot": 5.79, "em": 314.84, "mat": 0.0, "labor": 0.55, "page": 20,
"resources": []}], "stats": {"works_parsed": 1}}), encoding="utf-8")
(d / "meta.json").write_text(json.dumps({"key": "rates", "kind": "rate_book",
"book": "ТСН-2001.3", "chapter": "3-1",
"edition": "", "addendum_no": ""}), encoding="utf-8")
if with_index:
i = base / "index"
i.mkdir(parents=True)
(i / "extract.json").write_text(json.dumps({"issue_no": "222", "quarter": 4,
"year": 2026, "decree": "МКЭ-ОД/26-76", "addendum_no": "83",
"values": [{"code": "3.1-5-1", "value": 5.5, "page": 12}],
"stats": {"values_parsed": 1}}), encoding="utf-8")
(i / "meta.json").write_text(json.dumps({"key": "index", "kind": "index_release",
"book": "", "chapter": "",
"edition": "", "addendum_no": "83",
"issue_no": "222"}), 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_without_mapping_no_current_price(tmp_path, monkeypatch):
_db(tmp_path, monkeypatch, with_index=False)
rep = tsn_calc.calc_position("1-5-1")
assert rep["status"] == "index_unavailable"
assert rep["base"]["pz"] == 320.63, "базис обязан возвращаться"
assert rep["current"] is None, "текущей цены без коэффициента быть не может"
def test_with_mapping_computes_current_price(tmp_path, monkeypatch):
_db(tmp_path, monkeypatch, with_index=True)
rep = tsn_calc.calc_position("1-5-1")
assert rep["status"] == "ok", rep
# округление до копейки — ROUND_HALF_UP (банковское округление float дало бы 1763.46)
assert rep["current"]["pz"] == tsn_calc._money(320.63 * 5.5) == 1763.47
assert rep["index"]["issue_no"] == "222"
def test_estimate_refuses_when_any_position_unpriced(tmp_path, monkeypatch):
_db(tmp_path, monkeypatch, with_index=False)
rep = tsn_calc.calc_estimate([{"code": "1-5-1", "qty": 2}])
assert rep["status"] == "index_unavailable"
assert rep["grand_total"] is None
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 без прибыли
def test_zero_labour_marks_nr_sp_incomplete(monkeypatch):
"""ОТ=0 (вся зарплата внутри ЭМ) — НР/СП от ФОТ не начислить: помечаем неполноту,
а не показываем ноль как норму."""
import tsn_calc, tsn_ref
monkeypatch.setattr(tsn_ref, "find_work", lambda q, as_of=None, limit=5: {
"status": "ok", "items": [{"code": "1-14-1", "book": "ТСН-2001.3", "chapter": "3-1",
"pz": 84.89, "ot": 0.0, "em": 84.89, "mat": 0.0,
"unit": "1000 м3", "addendum_no": "", "edition": ""}]})
monkeypatch.setattr(tsn_calc, "find_rate_index", lambda w, as_of=None: {
"status": "ok", "value": 73.0, "issue_no": "222", "quarter": 4, "year": 2026})
monkeypatch.setattr(tsn_ref, "find_nr_sp", lambda q: {
"status": "ok", "items": [{"work_type": "Земляные работы", "overhead": 98.0,
"profit": 77.0}]})
res = tsn_calc.calc_position("1-14-1", work_type="Земляные работы")
assert res["nr_sp_incomplete"] is True and res["nr_sp"] is None
assert res["total"] == 6196.97
assert "ОТ" in res["message"]