fix(движок): материалы по сметной цене; ресурс без цены в форме зоны — «не оценён», а не базис без индекса

Разбор формы брал отпускную цену материала раньше сметной. В строгом режиме ресурс, которого нет
в форме ценовой зоны, молча считался по базисной цене ресурсного состава — и «голой», и умноженной на
индекс зоны; теперь цена ноль и запись в result.unpriced, итог помечается неполным.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ADvViaqN9hgCWVNH3HVQ6r
This commit is contained in:
anor
2026-09-14 18:50:09 +10:00
co-authored by Claude Opus 5
parent e16d263cb3
commit d9fae4dee3
4 changed files with 138 additions and 4 deletions
+20 -2
View File
@@ -56,11 +56,13 @@ class EstimateCalculator:
# а не тихий ноль (иначе смета «посчитается» с дырами и занизит итог).
self.strict = strict
self._missing: list = []
self._unpriced: list = []
def calculate(self, sections: list[Section]) -> EstimateResult:
"""Calculate entire estimate from sections list."""
result = EstimateResult()
self._missing = []
self._unpriced = []
for section in sections:
for subsection in section.subsections:
@@ -112,6 +114,7 @@ class EstimateCalculator:
)
result.missing = self._missing
result.unpriced = self._unpriced
result.ok = not self._missing
return result
@@ -169,6 +172,13 @@ class EstimateCalculator:
unresolved=(price_data is None),
)
def _unpriced_resource(self, code: str, position: str) -> None:
"""Базисная цена 2022 года без индекса — не текущая цена: молча подставлять её значит
занижать итог. В форме зоны нет ни индекса, ни текущей цены — ресурс не оценён."""
self._unpriced.append({
"code": code, "position": position,
"reason": "цены нет в форме ценовой зоны — определяется конъюнктурным анализом"})
def _calc_gesn(self, item: WorkItem) -> PositionResult:
"""Calculate GESN position with full resource expansion."""
code_key = item.code.replace("ГЭСН ", "").strip()
@@ -208,13 +218,18 @@ class EstimateCalculator:
for m in res.machines:
m_index = self.fgis.get_index(m.code)
m_base_fgis = self.fgis.get_base_price(m.code, m.cost_base)
# Строгий режим: база — только из формы зоны. Базисная цена ресурсного состава — другая
# база, умножать на неё индекс зоны нельзя (разбор 14.09.2026).
m_base_fgis = self.fgis.get_base_price(m.code, 0 if self.strict else m.cost_base)
m_current_fgis = self.fgis.get_current_price(m.code)
if m_index and m_base_fgis:
m_current = round(m_base_fgis * m_index, 2)
elif m_current_fgis:
m_current = m_current_fgis
elif m.cost_base and self.strict:
m_current = 0
self._unpriced_resource(m.code, item.code)
elif m.cost_base:
m_current = m.cost_base
else:
@@ -246,13 +261,16 @@ class EstimateCalculator:
continue
mat_index = self.fgis.get_index(mat.code)
mat_base_fgis = self.fgis.get_base_price(mat.code, mat.cost_base)
mat_base_fgis = self.fgis.get_base_price(mat.code, 0 if self.strict else mat.cost_base)
mat_current_fgis = self.fgis.get_current_price(mat.code)
if mat_index and mat_base_fgis:
mat_current = round(mat_base_fgis * mat_index, 2)
elif mat_current_fgis:
mat_current = mat_current_fgis
elif mat.cost_base and self.strict:
mat_current = 0
self._unpriced_resource(mat.code, item.code)
elif mat.cost_base:
mat_current = mat.cost_base
else:
+4 -2
View File
@@ -73,8 +73,10 @@ def build_fgis_lookup(xlsx_path: str) -> FGISLookup:
lookup.index_map[code] = idx
continue
# Material codes
for bp_col in [3, 4]:
# Material codes: сметная цена (колонка 4) — базис сметы; отпускная (3) только если
# сметной нет. Раньше порядок был обратный, и материалы шли по отпускной (разбор
# 14.09.2026: итог Приморского края занижался на 0,46 %).
for bp_col in [4, 3]:
bp = _parse_float(row[bp_col])
if bp is not None:
lookup.base_price_map[code] = bp
+3
View File
@@ -101,3 +101,6 @@ class EstimateResult:
# strict-режим (срез 4.1): fail-loud вместо тихих нулей.
missing: list = field(default_factory=list) # [{code, reason}] — что не рассчиталось
ok: bool = True # False → в смете есть нерассчитанные позиции
# Ресурсы без цены в форме ценовой зоны: итог посчитан без них и неполон (решение владельца
# 14.09.2026 — неполный итог со списком, а не отказ и не базисная цена без индекса).
unpriced: list = field(default_factory=list) # [{code, position, reason}]
+111
View File
@@ -0,0 +1,111 @@
"""Цены движка по форме ценовой зоны: сметная цена материала и честный «не оценён».
Разбор 14.09.2026 (smeta-web docs/TASK_2026-09-14_engine_zones.md):
- разбор формы брал базисную цену материала из колонки 3 (отпускная) раньше колонки 4 (сметная),
хотя смета считается по сметной цене; справочные инструменты сервиса (rim_calc, fgis_ref) берут её;
- в строгом режиме ресурс, которого нет в форме зоны (ни индекса, ни текущей цены), молча
считался по базисной цене 2022 года без индекса — занижение итога без пометки. Решение
владельца: итог считается, но помечается неполным со списком неоценённых ресурсов.
"""
import openpyxl
from smeta_railway.calc.estimate import EstimateCalculator
from smeta_railway.config import Section, Subsection, WorkItem
from smeta_railway.data.fgis import FGISLookup, build_fgis_lookup
from smeta_railway.models import (
LaborResource,
MachineResource,
MaterialResource,
NormResources,
)
def _form(tmp_path, rows):
"""Сплит-форма с раскладкой ФГИС: 0 код, 3 отпускная, 4 сметная, 7 текущая, 8 индекс."""
wb = openpyxl.Workbook()
ws = wb.active
for r in rows:
ws.append(r)
path = tmp_path / "form.xlsx"
wb.save(path)
return str(path)
def test_базисная_цена_материала_сметная_а_не_отпускная(tmp_path):
path = _form(tmp_path, [
["01.7.15.03-0042", "Болты", "т", 100.0, 110.0, None, None, 520.0, 4.2],
])
lookup = build_fgis_lookup(path)
assert lookup.base_price_map["01.7.15.03-0042"] == 110.0
def test_без_сметной_берётся_отпускная(tmp_path):
"""Ограждение: в форме бывают строки только с одной ценой."""
path = _form(tmp_path, [
["01.7.15.03-0043", "Шайбы", "т", 100.0, None, None, None, None, None],
])
assert build_fgis_lookup(path).base_price_map["01.7.15.03-0043"] == 100.0
def _position(materials=(), machines=()):
return {"01-01-001-01": NormResources(
norm_code="01-01-001-01", norm_name="Проба", unit="м3",
ozp=LaborResource(razryad=3.0, chel_hours=1.0),
machines=list(machines), materials=list(materials))}
def _calc(resources, strict=True):
fgis = FGISLookup(labor_price_map={"1-100-30": 600.0, "4-100-030": 700.0})
calc = EstimateCalculator(fgis=fgis, resources=resources, strict=strict)
section = Section(name="С", subsections=[Subsection(name="", items=[
WorkItem(code="01-01-001-01", name="Проба", unit="м3", qty=2.0)])])
return calc.calculate([section])
def test_материал_без_цены_в_форме_не_оценён_и_назван():
res = _calc(_position(materials=[MaterialResource(
code="02.2.05.04-2090", name="Щебень", unit="м3", qty=1.5, cost_base=900.0)]))
assert res.positions[0].mat_cost == 0.0
assert [u["code"] for u in res.unpriced] == ["02.2.05.04-2090"], res.unpriced
assert "конъюнктур" in res.unpriced[0]["reason"]
assert res.ok is True, "неоценённый ресурс — неполный итог, а не отказ от всей сметы"
def test_машина_без_цены_в_форме_не_оценена_и_названа():
res = _calc(_position(machines=[MachineResource(
code="91.05.05-015", name="Кран", unit="маш.-ч", qty=0.5, cost_base=1200.0)]))
assert res.positions[0].em_cost == 0.0
assert [u["code"] for u in res.unpriced] == ["91.05.05-015"], res.unpriced
def test_нестрогий_режим_как_раньше():
"""Ограждение: мастер ССР и нестрогие вызовы пока считают по базисной цене."""
res = _calc(_position(materials=[MaterialResource(
code="02.2.05.04-2090", name="Щебень", unit="м3", qty=1.5, cost_base=900.0)]), strict=False)
assert res.positions[0].mat_cost == round(1.5 * 2.0 * 900.0, 2)
assert not res.unpriced
def test_повторный_расчёт_не_копит_список():
"""Калькулятор переиспользуется для пересчёта: второй расчёт не наследует первый."""
fgis = FGISLookup(labor_price_map={"1-100-30": 600.0})
calc = EstimateCalculator(fgis=fgis, strict=True, resources=_position(materials=[
MaterialResource(code="02.2.05.04-2090", name="Щебень", unit="м3", qty=1.5,
cost_base=900.0)]))
section = Section(name="С", subsections=[Subsection(name="", items=[
WorkItem(code="01-01-001-01", name="Проба", unit="м3", qty=1.0)])])
calc.calculate([section])
assert len(calc.calculate([section]).unpriced) == 1
def test_индекс_зоны_без_базисной_цены_формы_не_умножается_на_чужую_базу():
"""Индекс в форме есть, базисной цены нет: умножать индекс зоны на базисную цену из ресурсных
составов нельзя — это другая база (разбор 14.09.2026, нашла зайка)."""
fgis = FGISLookup(labor_price_map={"1-100-30": 600.0}, index_map={"02.2.05.04-2090": 3.0})
calc = EstimateCalculator(fgis=fgis, strict=True, resources=_position(materials=[
MaterialResource(code="02.2.05.04-2090", name="Щебень", unit="м3", qty=1.0, cost_base=500.0)]))
section = Section(name="С", subsections=[Subsection(name="", items=[
WorkItem(code="01-01-001-01", name="Проба", unit="м3", qty=1.0)])])
res = calc.calculate([section])
assert res.positions[0].mat_cost == 0.0
assert [u["code"] for u in res.unpriced] == ["02.2.05.04-2090"]