refactor: декомпозиция монолита в пакет smeta-railway

- Пакетная структура src/smeta_railway/ с модулями calc/, data/, output/
- Pydantic-конфиг: всё через YAML, сметчик не трогает Python
- EstimateCalculator: ядро расчёта, параметризованные коэффициенты
- FGISLookup: pickle cache (4.7с → ~50мс при повторном запуске)
- CLI: smeta generate/fetch-resources/validate (typer)
- 28 тестов (coefficients, overhead, fgis, estimate)
- Исправлен баг: НР/СП для земляных работ (92%/46% вместо 109%/65%)
- ПЗ совпадают бит-в-бит со старым генератором

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-20 18:42:19 +10:00
co-authored by Claude Opus 4.6
parent bfe5479424
commit 897d2d1b76
25 changed files with 4663 additions and 0 deletions
+18
View File
@@ -1,4 +1,22 @@
.venv/
__pycache__/
*.pyc
*.pyo
*.egg-info/
dist/
build/
# FGIS data (large, not tracked)
fgis_split_form.xlsx
fgis_cache.pkl
fgis_snapshot1.md
# Output xlsx (smeta results)
smeta_*.xlsx
# Old monolithic scripts (archived)
# generate_smeta.py
# generate_smeta_v2.py
# OS
.DS_Store
+88
View File
@@ -0,0 +1,88 @@
# smeta-railway
Генератор ресурсно-индексных смет для капремонта железнодорожного пути.
**Нормативная база:** ГЭСН-2022 (ФСНБ-2022), Сборник 28 «Железные дороги», дополнение 17.
**Регион:** Приморский край, ОАО «РЖД».
**Метод:** Ресурсно-индексный (РИМ), индексы к группам однородных ресурсов.
**Формат вывода:** 27-колоночный Excel «Строительный эксперт».
## Установка
```bash
python -m venv .venv
source .venv/bin/activate
pip install -e .
```
## Использование
### Генерация сметы
```bash
smeta generate projects/sviyagino_2026q1.yaml
```
### Загрузка ресурсов ГЭСН
```bash
smeta fetch-resources projects/sviyagino_2026q1.yaml
```
### Валидация конфига
```bash
smeta validate projects/sviyagino_2026q1.yaml
```
## Структура проекта
```
smeta-railway/
├── pyproject.toml
├── src/smeta_railway/
│ ├── cli.py # typer CLI
│ ├── config.py # Pydantic-модели YAML-конфига
│ ├── models.py # dataclasses: Norm, Resource, Machine, Material
│ ├── data/
│ │ ├── fgis.py # FGISLookup (lazy load + pickle cache)
│ │ ├── gesn.py # парсер cs.smetnoedelo.ru + JSON cache
│ │ └── prices.py # GESN_PRICES, TRANSPORT_PRICES
│ ├── calc/
│ │ ├── coefficients.py # усложняющие коэффициенты
│ │ ├── estimate.py # EstimateCalculator → EstimateResult
│ │ └── overhead.py # НР, СП расчёт
│ └── output/
│ └── excel_se.py # 27-колоночный Excel
├── data/
│ └── resources.json # кэш ГЭСН
├── tests/
├── config/
│ └── example_project.yaml
└── projects/
└── sviyagino_2026q1.yaml # конфиг проекта
```
## Конфигурация
Всё конфигурируется через YAML: регион, коэффициенты, НР/СП, состав работ, транспорт.
Сметчик меняет YAML, не Python. Пример: `config/example_project.yaml`.
## Необходимые данные
- `fgis_split_form.xlsx` — выгрузка из ФГИС ЦС (fgiscs.minstroyrf.ru)
- `resources.json` — ресурсные составы ГЭСН (создаётся командой `smeta fetch-resources`)
## Тесты
```bash
pip install -e ".[dev]"
pytest tests/ -v
```
## Нормативная база
- Приказ 421/пр (04.08.2020) — коэффициенты к ГЭСН
- Приказ 812/пр (21.12.2020) — накладные расходы
- Приказ 774/пр (11.12.2020) — сметная прибыль
- ГЭСН-2022 сб.28 — нормы на железнодорожные работы
+75
View File
@@ -0,0 +1,75 @@
# Example project config for smeta-railway
# Copy this file and modify for your project
project:
title: "ЛОКАЛЬНЫЙ СМЕТНЫЙ РАСЧЕТ (СМЕТА)"
number: "ЛС-XX-XX-X-XX-XX"
object_name: ""
section_name: ""
region:
subject: "Приморский край"
zone: 'Приморский край (ОАО "РЖД")'
price_level:
quarter: "I кв. 2026 г."
year: 2026
letter_number: "Письмо Минстроя России от 25.02.2026 №9859-ИФ/09"
dopolnenie: "Приказ Минстроя России от 17.02.2026 №91/пр"
labor_act: 'Распоряжение ОАО "РЖД" от 22.10.2021 №2281/р'
# Complication coefficients (GESN-2022, Collection 28 TC)
coefficients:
definitions:
- key: dvizhenie
code: "2022-13-ГЭСН-ПР-28-01-1.1.8-000"
name: "Выполнение работ в условиях движения поездов 91-108 п/сут"
value: 1.60
apply_zt: true
apply_em: true
apply_ztm: true
- key: vl
code: "2022-13-ГЭСН-ПР-28-01-1.2-000"
name: "Производство работ вблизи объектов под высоким напряжением"
value: 1.20
apply_zt: false
apply_em: true
apply_ztm: true
- key: okno
code: "2022-13-ГЭСН-ПР-28-01-1.3.1-000"
name: "Производство работ в «окно»"
value: 1.81
apply_zt: false
apply_em: true
apply_ztm: true
exclude_norms:
okno:
- "28-01-155-" # manual fastening work
- "28-01-043-" # rail cutting
- "28-01-044-" # insulating joints
overhead:
nr_railway: 109
sp_railway: 65
nr_earthwork: 92
sp_earthwork: 46
fgis:
xlsx_path: "../fgis_split_form.xlsx"
cache_path: "../fgis_cache.pkl"
resources_json: "../resources.json"
output:
format: se27
filename: "output.xlsx"
sections:
- name: "Раздел 1. Верхнее строение пути"
subsections:
- name: null # no subsection header
items:
- code: "ГЭСН 28-01-031-01"
name: "Выправка пути"
unit: "км"
qty: 1.0
+1599
View File
File diff suppressed because it is too large Load Diff
+319
View File
@@ -0,0 +1,319 @@
# Капремонт пути: участок Свиягино–Спасск-Дальний, 1 путь
# 3 этап. ПК 90350+00.00 - ПК 90370+17.00 (2,017 км)
# Q1 2026, ресурсно-индексный метод
project:
title: "ЛОКАЛЬНЫЙ СМЕТНЫЙ РАСЧЕТ (СМЕТА)"
number: "ЛС-03-02-4-00-01"
object_name: "Капитальный ремонт пути"
section_name: "3 этап. ПК 90350+00.00 - ПК 90370+17.00 (2,017 км)"
region:
subject: "Приморский край"
zone: 'Приморский край (ОАО "РЖД")'
price_level:
quarter: "I кв. 2026 г."
year: 2026
letter_number: "Письмо Минстроя России от 25.02.2026 №9859-ИФ/09"
dopolnenie: "Приказ Минстроя России от 17.02.2026 №91/пр"
labor_act: 'Распоряжение ОАО "РЖД" от 22.10.2021 №2281/р'
coefficients:
definitions:
- key: dvizhenie
code: "2022-13-ГЭСН-ПР-28-01-1.1.8-000"
name: "Выполнение работ в условиях движения поездов для участков с размерами движения 91-108 поездов/сут"
value: 1.60
apply_zt: true
apply_em: true
apply_ztm: true
- key: vl
code: "2022-13-ГЭСН-ПР-28-01-1.2-000"
name: "Производство работ вблизи объектов, находящихся под высоким напряжением"
value: 1.20
apply_zt: false
apply_em: true
apply_ztm: true
- key: okno
code: "2022-13-ГЭСН-ПР-28-01-1.3.1-000"
name: "Производство работ с прекращением движения поездов по перегону (в «окно»)"
value: 1.81
apply_zt: false
apply_em: true
apply_ztm: true
exclude_norms:
okno:
- "28-01-155-"
- "28-01-043-"
- "28-01-044-"
overhead:
nr_railway: 109
sp_railway: 65
nr_earthwork: 92
sp_earthwork: 46
nr_code: "812/пр_2020_прил._т._п.22_гр.3"
sp_code: "774/пр_2020_прил._т._п.22_гр.3"
nr_label: "НР (Железные дороги)"
sp_label: "СП (Железные дороги)"
fgis:
xlsx_path: "../fgis_split_form.xlsx"
cache_path: "../fgis_cache.pkl"
resources_json: "../resources.json"
output:
format: se27
filename: "../smeta_v2_q1_2026_new.xlsx"
sections:
- name: "Раздел 1. Верхнее строение пути"
subsections:
- name: "ПОДРАЗДЕЛ 1.1. Одиночная замена элементов верхнего строения пути"
items:
- code: "ГЭСН 28-01-155-01"
name: "Замена дефектных элементов скреплений КБ, 1 класс, средний ремонт (базовая)"
unit: "км"
qty: 2.017
note: "Базовая норма на замену скреплений КБ"
- code: "ГЭСН 28-01-155-11"
name: "Добавка: подкладки КБ-65 (411 шт = 4,11 × 100)"
unit: "100 шт"
qty: 4.11
note: "411 шт, вес 2,818 т"
- code: "ГЭСН 28-01-155-12"
name: "Добавка: болты закладные с гайками М-22 (2096 шт)"
unit: "100 шт"
qty: 20.96
note: "2096 шт, вес 1,595 т"
- code: "ГЭСН 28-01-155-13"
name: "Добавка: болты клеммные с гайками М-22 (921 шт)"
unit: "100 шт"
qty: 9.21
note: "921 шт, вес 0,434 т"
- code: "ГЭСН 28-01-155-14"
name: "Добавка: шайбы 2-х витковые (4375 шт)"
unit: "100 шт"
qty: 43.75
note: "4375 шт, вес 0,525 т"
- code: "ГЭСН 28-01-155-15"
name: "Добавка: клеммы ПК-65 (983 шт)"
unit: "100 шт"
qty: 9.83
note: "983 шт, вес 0,629 т"
- code: "ГЭСН 28-01-155-16"
name: "Добавка: прокладки под рельс ЦП-328 (2279 шт)"
unit: "100 шт"
qty: 22.79
note: "2279 шт, вес 1,459 т"
- code: "ГЭСН 28-01-155-17"
name: "Добавка: прокладки под подкладки ЦП-143/ЦП-74 (7552 шт)"
unit: "100 шт"
qty: 75.52
note: "7552 шт, вес 1,888 т"
- code: "ГЭСН 28-01-155-18"
name: "Добавка: втулки изолирующие ЦП-142 (1009 шт)"
unit: "100 шт"
qty: 10.09
note: "1009 шт, вес 0,045 т"
- code: "Материал"
name: "Шпала ж/б Ш1 старогодная — одиночная замена 44 шт (22 шт/км)"
unit: "шт."
qty: 44
note: "Старогодные шпалы, стоимость работ включена в 28-01-155"
- name: "ПОДРАЗДЕЛ 1.2. Замена рельсовых нитей новыми плетями (скр. КБ-65, зона ВЛ, в «окно»)"
items:
- code: "ГЭСН 28-01-043-01"
name: "Резка существующих плетей до 800 м рельсорезным станком"
unit: "пар резок"
qty: 2
note: "ПК 90359+74.01 – ПК 90370+17,00 (1042,99 м)"
- code: "ГЭСН 28-01-037-02"
name: "Замена рельсовых плетей новыми, рельсы Р-65 (ДТ350), прямые и кривые R>1200 м, скр. КБ-65, эпюра 1840 шп/км"
unit: "км пути"
qty: 1.321
note: "Вес рельсов 171,413 т. Шпалы и скрепления не разбираются"
- code: "ГЭСН 28-01-037-01"
name: "Замена рельсовых плетей новыми, рельсы Р-65 (ДТ350), кривые R≤1200 м, скр. КБ-65, эпюра 2000 шп/км"
unit: "км пути"
qty: 0.465
note: "Вес рельсов 60,338 т"
- code: "ГЭСН 28-01-037-02"
name: "Замена рельсов звеньевого пути на новые плети, рельсы Р-65 (ДТ350), кривые 1200≥R≥350 м, скр. КБ-65, эпюра 2000 шп/км"
unit: "км пути"
qty: 0.156
note: "Вес рельсов 20,243 т"
- name: "ПОДРАЗДЕЛ 1.3. Работы на железобетонном мосту ПК 90359+29,13"
items:
- code: "ГЭСН 28-01-043-01"
name: "Резка плети ПК 90358+99.01 – ПК 90359+74.01 по 25 м"
unit: "пар резок"
qty: 4
note: "Длина плети 0,075 км, ЖБМ"
- code: "ГЭСН 28-01-008-01"
name: "Демонтаж рельсовой плети на ПК 90358+99.01 – ПК 90359+74.01 (шпалы и скрепления не разбираются)"
unit: "км"
qty: 0.075
- code: "ГЭСН 28-01-037-02"
name: "Укладка инвентарных рельсов на подходах к ЖБМ, скр. КБ-65, кривые 1200≥R≥350, эпюра 2000 шп/км"
unit: "км"
qty: 0.066
note: "Вес 8,564 т"
- code: "ГЭСН 28-01-037-02"
name: "Укладка инвентарных рельсов по длине ЖБМ, скр. КБ-65, кривые 1200≥R≥350, эпюра 2000 шп/км"
unit: "км"
qty: 0.009
note: "Вес 1,168 т"
- code: "ГЭСН 28-01-054-01"
name: "Демонтаж и монтаж звеньев пути на подходах к ЖБМ, скр. КБ-65, кривые 1200≥R≥350, эпюра 2000 шп/км, шпала Ш1"
unit: "км"
qty: 0.066
note: "Вес 47,749 т"
- code: "ГЭСН 28-01-054-01"
name: "Демонтаж и монтаж звеньев пути с инвентарными рельсами по длине ЖБМ, скр. КБ-65, кривые 1200≥R≥350, эпюра 2000 шп/км, шпала Ш1"
unit: "км"
qty: 0.009
- code: "ГЭСН 28-01-075-01"
name: "Вырезка балласта на подходах к ЖБМ, бульдозером 121 кВт, перевозка ж/д транспортом 1-5 км, грунт 41б, γ=2,11 т/м³"
unit: "100 м³"
qty: 1.78
note: "178 м³, 0,066 км"
- code: "ГЭСН 28-01-073-01"
name: "Вырезка балласта по длине ЖБМ, погрузчиком на гус. ходу, грунт 41б, γ=2,11 т/м³"
unit: "м"
qty: 17
note: "0,009 км"
- code: "ГЭСН 28-01-033-01"
name: "Балластировка по длине ЖБМ, погрузчиком на гус. ходу, грунт 41б, γ=2,11 т/м³"
unit: "м³"
qty: 17
- code: "ГЭСН 28-01-037-01"
name: "Замена инвентарных рельсов новыми плетьми по длине ЖБМ, скр. КБ-65, кривые 1200≥R≥350, эпюра 2000 шп/км, шпала Ш1"
unit: "км"
qty: 0.009
note: "Вес 1,168 т"
- code: "ГЭСН 28-01-037-01"
name: "Замена инвентарных рельсов новыми плетьми на подходах к ЖБМ, скр. КБ-65, кривые 1200≥R≥350, эпюра 2000 шп/км, шпала Ш1"
unit: "км"
qty: 0.066
note: "Вес 8,564 т"
- name: "ПОДРАЗДЕЛ 1.4. Балластные работы"
items:
- code: "ГЭСН 28-01-068-07"
name: "Очистка щебеночного балласта на глубину 40 см машинами щебнеочистительными"
unit: "км"
qty: 1.942
note: "1,321 + 0,465 + 0,156 = 1,942 км"
- code: "Материал"
name: "Щебень балластный при очистке"
unit: "м³"
qty: 2866
note: "Средняя сетевая норма 1473/1483 м³/км"
- code: "Материал"
name: " - в т.ч. потери щебня при очистке балласта"
unit: "м³"
qty: 1302
note: "Бесстыковой путь"
- code: "Материал"
name: " - засорители (увозятся в отвал)"
unit: "м³"
qty: 1564
- code: "ГЭСН 28-01-075-01"
name: "Срезка щебеночного балласта"
unit: "100 м³"
qty: 1.75
note: "175 м³"
- code: "ГЭСН 28-01-027-04"
name: "Подъемка пути на щебеночный балласт"
unit: "1000 м³"
qty: 0.460
note: "390 м³ × 1,18 = 460 м³"
- code: "ГЭСН 28-01-075-02"
name: "Формирование бровки земляного полотна (вырезка балласта), грунт 41б, γ=2,11 т/м³, машиной МКТ"
unit: "100 м³"
qty: 1.00
note: "100 м³"
- code: "ГЭСН 01-02-057-02"
name: "Пересыпка междупутья балластом, щебень II кат. (фр. 25-60 мм), экскаватором ковш 0,65 м³"
unit: "100 м³"
qty: 1.77
note: "177 м³"
- code: "ГЭСН 01-01-036-01"
name: "Планировка междупутья бульдозером 121 кВт (165 л.с.) с перемещением до 10 м"
unit: "1000 м²"
qty: 0.177
- name: "ПОДРАЗДЕЛ 1.5. Выправка и отделка пути"
items:
- code: "ГЭСН 28-01-031-01"
name: "Выправка пути на ж.б. шпалах, балласт щебеночный"
unit: "км"
qty: 2.017
- code: "ГЭСН 28-01-155-11"
name: "Смазка и закрепление стыковых, клеммных, закладных болтов и шурупов"
unit: "км"
qty: 2.017
- code: "ГЭСН 28-01-076-01"
name: "Очистка кюветов машиной МКТ"
unit: "м"
qty: 927
- name: "ПОДРАЗДЕЛ 1.6. Сварочные работы"
items:
- code: "КП РСП-19"
name: "Сварка рельсов Р65 (по 25 м) на рельсосварочном предприятии РСП-19 ст. Хабаровск-II"
unit: "стык"
qty: 78
note: "Конъюнктурный анализ, КП РСП-19"
- code: "ГЭСН 28-01-041-01"
name: "Сварка рельсовых стыков машиной ПРСМ в пути"
unit: "2 стыка"
qty: 3
note: "Сварка в пути при укладке"
- name: "ПОДРАЗДЕЛ 1.7. Изолирующие стыки"
items:
- code: "ГЭСН 28-01-044-01"
name: "Устройство изолирующего стыка с металлокомпозитными накладками вварного (в РСП) проекта 2724.00.0000"
unit: "пара"
qty: 1
- name: "ПОДРАЗДЕЛ 1.8. Транспортные и погрузочно-разгрузочные работы"
items:
- code: "ФССЦпг 236019-00-0071-0080"
name: "Перевозка нового щебня балластного от карьера до объекта ХДВ, 73 км (3520 м³ × γ=1,7 = 5984 т)"
unit: "1 т груза"
qty: 5984
- code: "ФССЦпг 371051-04-0071-0080-new"
name: "Перевозка новых материалов ВСП (скрепления, шпалы) от ПМС-18 платформами, 73 км (~10 т)"
unit: "1 т груза"
qty: 10
- code: "ФССЦпг 236019-00-0001-0005"
name: "Перевозка засорителей в место выгрузки ХДВ, 5 км (1564 м³ × γ=2,11 = 3300 т)"
unit: "1 т груза"
qty: 3300
- code: "ФССЦпг 236019-00-0001-0005"
name: "Перевозка потерь и срезки балласта в место выгрузки ХДВ, 5 км (~3098 т)"
unit: "1 т груза"
qty: 3098
- code: "ФССЦпг 371051-04-0071-0080"
name: "Перевозка старогодных материалов ВСП на базу ПМС-18 платформами, 73 км (~21 т)"
unit: "1 т груза"
qty: 21
- code: "ФССЦпг 371051-05-0331-0360"
name: "Перевозка старогодных рельсовых плетей на перегон Сухановка–Гвоздево сцепом платформ, 337 км (~262 т)"
unit: "1 т груза"
qty: 262
- code: "ФССЦпг 02-15-1-03-0003"
name: "Перевозка лишнего грунта автосамосвалами в пределах полосы отвода, 3 км (~180 т)"
unit: "1 т груза"
qty: 180
- code: "ФССЦпг 01-20-3-01-0012"
name: "Перевозка демонтируемого оборудования СЦБ автобортовым в ШЧ-6 ст. Спасск-Дальний, 12 км (~5 т)"
unit: "1 т груза"
qty: 5
+24
View File
@@ -0,0 +1,24 @@
[build-system]
requires = ["setuptools>=68.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "smeta-railway"
version = "0.1.0"
description = "Resource-index estimate generator for railway capital repair (GESN-2022, FGIS CS)"
requires-python = ">=3.11"
dependencies = [
"openpyxl>=3.1",
"typer>=0.12",
"pyyaml>=6.0",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = ["pytest>=8.0"]
[project.scripts]
smeta = "smeta_railway.cli:app"
[tool.setuptools.packages.find]
where = ["src"]
+3
View File
@@ -0,0 +1,3 @@
"""smeta-railway: resource-index estimate generator for railway capital repair."""
__version__ = "0.1.0"
View File
+146
View File
@@ -0,0 +1,146 @@
"""
Complication coefficients for railway capital repair.
Technical part GESN-2022, Collection 28 "Zheleznye dorogi".
Parameterized via ProjectConfig — coefficient values and exclusion rules
come from YAML, not hardcoded.
"""
from smeta_railway.config import CoefficientConfig, CoefficientDef
from smeta_railway.models import Coefficients
# Default coefficient definitions (can be overridden via YAML)
DEFAULT_COEFFICIENTS: list[dict] = [
{
"key": "dvizhenie",
"code": "2022-13-ГЭСН-ПР-28-01-1.1.8-000",
"name": ("Выполнение работ в условиях движения поездов "
"для участков с размерами движения 91-108 поездов/сут"),
"value": 1.60,
"apply_zt": True,
"apply_em": True,
"apply_ztm": True,
},
{
"key": "vl",
"code": "2022-13-ГЭСН-ПР-28-01-1.2-000",
"name": ("Производство работ вблизи объектов, "
"находящихся под высоким напряжением"),
"value": 1.20,
"apply_zt": False,
"apply_em": True,
"apply_ztm": True,
},
{
"key": "okno",
"code": "2022-13-ГЭСН-ПР-28-01-1.3.1-000",
"name": ("Производство работ с прекращением движения "
'поездов по перегону (в «окно»)'),
"value": 1.81,
"apply_zt": False,
"apply_em": True,
"apply_ztm": True,
},
]
DEFAULT_EXCLUDE_NORMS: dict[str, list[str]] = {
"okno": [
"28-01-155-", # replacement of fastenings (manual work)
"28-01-043-", # rail cutting (manual machine)
"28-01-044-", # insulating joints (manual)
],
}
def get_default_config() -> CoefficientConfig:
"""Build default CoefficientConfig."""
defs = [CoefficientDef(**d) for d in DEFAULT_COEFFICIENTS]
return CoefficientConfig(
definitions=defs,
exclude_norms=DEFAULT_EXCLUDE_NORMS,
)
def get_coefficients(
gesn_code: str,
config: CoefficientConfig | None = None,
) -> Coefficients:
"""
Compute resulting coefficients for a GESN norm.
Args:
gesn_code: full code like "ГЭСН 28-01-037-02"
config: coefficient config from YAML (uses defaults if None)
Returns:
Coefficients dataclass with zt, em, ztm, applied list, formulas
"""
if config is None:
config = get_default_config()
code = gesn_code.replace("ГЭСН ", "").strip()
# Only apply coefficients to collection 28 norms
if not code.startswith("28-01-"):
return Coefficients(
formulas={"zt": "", "em": "", "ztm": ""},
)
zt = 1.0
em = 1.0
ztm = 1.0
applied: list[str] = []
parts_zt: list[str] = []
parts_em: list[str] = []
parts_ztm: list[str] = []
for cdef in config.definitions:
# Check exclusion rules for this coefficient
excluded_prefixes = config.exclude_norms.get(cdef.key, [])
if any(code.startswith(p) for p in excluded_prefixes):
continue
# Apply coefficient
if cdef.apply_zt:
zt *= cdef.value
parts_zt.append(f"{cdef.value:.2f}")
if cdef.apply_em:
em *= cdef.value
parts_em.append(f"{cdef.value:.2f}")
if cdef.apply_ztm:
ztm *= cdef.value
parts_ztm.append(f"{cdef.value:.2f}")
applied.append(cdef.key)
def formula(parts: list[str], result: float) -> str:
if len(parts) == 0:
return ""
if len(parts) == 1:
return parts[0]
return "*".join(parts) + f"={result:.4f}"
return Coefficients(
zt=round(zt, 4),
em=round(em, 4),
ztm=round(ztm, 4),
applied=applied,
formulas={
"zt": formula(parts_zt, zt),
"em": formula(parts_em, em),
"ztm": formula(parts_ztm, ztm),
},
)
# Backward-compatible accessors for coefficient codes/names
def get_coeff_codes(config: CoefficientConfig | None = None) -> dict[str, str]:
if config is None:
config = get_default_config()
return {d.key: d.code for d in config.definitions}
def get_coeff_names(config: CoefficientConfig | None = None) -> dict[str, str]:
if config is None:
config = get_default_config()
return {d.key: d.name for d in config.definitions}
+237
View File
@@ -0,0 +1,237 @@
"""
EstimateCalculator — core calculation engine.
Replaces generate_smeta_v2.py lines 695-1020.
Takes YAML-driven sections + FGIS lookup + resources.json
and produces EstimateResult with all positions calculated.
"""
from smeta_railway.calc.coefficients import (
get_coeff_codes,
get_coeff_names,
get_coefficients,
)
from smeta_railway.calc.overhead import calc_overhead, get_overhead_percents
from smeta_railway.config import (
CoefficientConfig,
OverheadConfig,
ProjectConfig,
Section,
WorkItem,
)
from smeta_railway.data.fgis import (
FGISLookup,
get_labor_code,
get_labor_current_price,
)
from smeta_railway.data.prices import TRANSPORT_PRICES, KP_PRICES
from smeta_railway.models import (
Coefficients,
EstimateResult,
NormResources,
PositionResult,
)
class EstimateCalculator:
"""Calculate resource-index estimate from config + data."""
def __init__(
self,
fgis: FGISLookup,
resources: dict[str, NormResources],
coeff_config: CoefficientConfig | None = None,
overhead_config: OverheadConfig | None = None,
):
self.fgis = fgis
self.resources = resources
self.coeff_config = coeff_config
self.overhead_config = overhead_config
def calculate(self, sections: list[Section]) -> EstimateResult:
"""Calculate entire estimate from sections list."""
result = EstimateResult()
for section in sections:
for subsection in section.subsections:
for item in subsection.items:
pos = self._calc_position(item)
if pos is None:
continue
result.positions.append(pos)
result.grand_pz += pos.pz
result.grand_ot += pos.ot_cost
result.grand_em += pos.em_cost
result.grand_otm += pos.otm_cost
result.grand_mat += pos.mat_cost
result.grand_transport += pos.transport_cost
result.grand_fot += pos.fot
result.grand_nr += pos.nr
result.grand_sp += pos.sp
result.grand_zt_hours += pos.zt_hours
result.grand_ztm_hours += pos.ztm_hours
result.grand_total = round(
result.grand_pz + result.grand_nr + result.grand_sp, 2
)
return result
def _calc_position(self, item: WorkItem) -> PositionResult | None:
"""Calculate a single position."""
gesn_code = item.code
qty = item.qty
is_material = gesn_code == "Материал"
is_transport = gesn_code.startswith("ФССЦпг")
is_kp = gesn_code.startswith("КП ")
if is_material:
return PositionResult(
gesn_code=gesn_code, name=item.name, unit=item.unit,
qty=qty, is_material=True,
)
if is_transport:
return self._calc_transport(item)
if is_kp:
return self._calc_kp(item)
return self._calc_gesn(item)
def _calc_transport(self, item: WorkItem) -> PositionResult:
"""Calculate transport position."""
price_key = item.code.replace("ФССЦпг ", "ФССЦпг-").strip()
price_data = TRANSPORT_PRICES.get(price_key)
current_price = price_data[2] if price_data else 0.0
total_cost = round(item.qty * current_price, 2)
return PositionResult(
gesn_code=item.code, name=item.name, unit=item.unit,
qty=item.qty, pz=total_cost, total=total_cost,
transport_cost=total_cost, is_transport=True,
)
def _calc_kp(self, item: WorkItem) -> PositionResult:
"""Calculate commercial proposal position."""
price_key = item.code.replace("КП ", "КП-").strip()
price_data = KP_PRICES.get(price_key)
current_price = price_data[2] if price_data else 0.0
total_cost = round(item.qty * current_price, 2)
return PositionResult(
gesn_code=item.code, name=item.name, unit=item.unit,
qty=item.qty, pz=total_cost, total=total_cost, is_kp=True,
)
def _calc_gesn(self, item: WorkItem) -> PositionResult:
"""Calculate GESN position with full resource expansion."""
code_key = item.code.replace("ГЭСН ", "").strip()
qty = item.qty
res = self.resources.get(code_key)
if not res:
return PositionResult(
gesn_code=item.code, name=item.name,
unit=item.unit, qty=qty,
)
coeffs = get_coefficients(item.code, self.coeff_config)
k_zt = coeffs.zt
k_em = coeffs.em
k_ztm = coeffs.ztm
# === OT(ZT) ===
ot_cost = 0.0
total_zt_hours = 0.0
if res.ozp:
razryad = res.ozp.razryad
chel_hours = res.ozp.chel_hours
labor_price = get_labor_current_price(self.fgis, razryad)
total_zt_hours = round(chel_hours * qty * k_zt, 7)
ot_cost = round(total_zt_hours * labor_price, 2)
# === EM ===
em_total_cost = 0.0
otm_total_hours = 0.0
otm_total_cost = 0.0
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)
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:
m_current = m.cost_base
else:
m_current = 0
total_m_qty = round(m.qty * qty * k_em, 7)
m_cost = round(total_m_qty * m_current, 2)
em_total_cost += m_cost
if m.razryad_mash:
mach_hours = round(m.qty * qty * k_ztm, 7)
mach_price = get_labor_current_price(
self.fgis, m.razryad_mash, is_machinist=True
)
mach_cost = round(mach_hours * mach_price, 2)
otm_total_hours += mach_hours
otm_total_cost += mach_cost
# === Materials ===
mat_total_cost = 0.0
for mat in res.materials:
if mat.code == "02.2.05.04-0061":
# Ballast — project quantity, skip here
continue
mat_index = self.fgis.get_index(mat.code)
mat_base_fgis = self.fgis.get_base_price(mat.code, 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:
mat_current = mat.cost_base
else:
mat_current = 0
total_mat_qty = round(mat.qty * qty, 7)
mat_cost = round(total_mat_qty * mat_current, 2)
mat_total_cost += mat_cost
# === Totals ===
pz = round(ot_cost + em_total_cost + mat_total_cost, 2)
fot = round(ot_cost + otm_total_cost, 2)
nr_pct, sp_pct, *_ = get_overhead_percents(
item.code, self.overhead_config
)
nr, sp = calc_overhead(fot, nr_pct, sp_pct)
total = round(pz + nr + sp, 2)
return PositionResult(
gesn_code=item.code,
name=item.name,
unit=item.unit,
qty=qty,
ot_cost=ot_cost,
em_cost=em_total_cost,
otm_cost=round(otm_total_cost, 2),
mat_cost=mat_total_cost,
pz=pz,
fot=fot,
nr=nr,
sp=sp,
total=total,
zt_hours=total_zt_hours,
ztm_hours=otm_total_hours,
)
+61
View File
@@ -0,0 +1,61 @@
"""
Overhead costs (НР) and estimated profit (СП) calculation.
Rules:
- Railway norms (28-01-xxx): НР=109% ФОТ, СП=65% ФОТ
- Earthwork norms (01-xx-xxx): НР=92% ФОТ, СП=46% ФОТ
- Transport (ФССЦпг) and commercial (КП): no overhead
"""
from smeta_railway.config import OverheadConfig
def get_overhead_percents(
gesn_code: str,
config: OverheadConfig | None = None,
) -> tuple[float, float, str, str, str, str]:
"""
Return (nr_percent, sp_percent, nr_code, nr_label, sp_code, sp_label)
for the given norm code.
"""
if config is None:
config = OverheadConfig()
code = gesn_code.replace("ГЭСН ", "").strip()
if code.startswith("01-"):
return (
config.nr_earthwork,
config.sp_earthwork,
config.nr_code,
"НР (Земляные работы)",
config.sp_code,
"СП (Земляные работы)",
)
if code.startswith("28-01-"):
return (
config.nr_railway,
config.sp_railway,
config.nr_code,
config.nr_label,
config.sp_code,
config.sp_label,
)
# Default: railway
return (
config.nr_railway,
config.sp_railway,
config.nr_code,
config.nr_label,
config.sp_code,
config.sp_label,
)
def calc_overhead(fot: float, nr_percent: float, sp_percent: float) -> tuple[float, float]:
"""Calculate НР and СП from FOT."""
nr = round(fot * nr_percent / 100, 2)
sp = round(fot * sp_percent / 100, 2)
return nr, sp
+137
View File
@@ -0,0 +1,137 @@
"""CLI interface for smeta-railway."""
import sys
from pathlib import Path
import typer
app = typer.Typer(help="Resource-index estimate generator for railway capital repair")
@app.command()
def generate(
project_yaml: Path = typer.Argument(..., help="Path to project YAML config"),
output: str | None = typer.Option(None, "--output", "-o", help="Output xlsx path"),
):
"""Generate estimate from project YAML config."""
from smeta_railway.calc.estimate import EstimateCalculator
from smeta_railway.config import ProjectConfig
from smeta_railway.data.fgis import load_fgis
from smeta_railway.data.gesn import load_resources
from smeta_railway.output.excel_se import generate_excel
if not project_yaml.exists():
typer.echo(f"Error: {project_yaml} not found", err=True)
raise typer.Exit(1)
config = ProjectConfig.from_yaml(project_yaml)
project_dir = project_yaml.parent
# Resolve paths relative to project YAML
resources_path = _resolve_path(config.resources_json, project_dir)
fgis_xlsx = _resolve_path(config.fgis.xlsx_path, project_dir)
fgis_cache = _resolve_path(config.fgis.cache_path, project_dir)
if not fgis_xlsx.exists():
typer.echo(
f"Error: FGIS split form not found: {fgis_xlsx}\n"
"Download from ФГИС ЦС (fgiscs.minstroyrf.ru) and place in project directory.",
err=True,
)
raise typer.Exit(1)
if not resources_path.exists():
typer.echo(
f"Error: resources.json not found: {resources_path}\n"
"Run: smeta fetch-resources",
err=True,
)
raise typer.Exit(1)
typer.echo("Loading FGIS data...")
fgis = load_fgis(str(fgis_xlsx), str(fgis_cache))
typer.echo("Loading resources...")
resources = load_resources(resources_path)
typer.echo("Calculating estimate...")
calculator = EstimateCalculator(
fgis=fgis,
resources=resources,
coeff_config=config.coefficients,
overhead_config=config.overhead,
)
estimate = calculator.calculate(config.sections)
output_path = output or config.output.filename
output_path = str(_resolve_path(output_path, project_dir))
typer.echo("Generating Excel...")
generate_excel(config, estimate, fgis, resources, output_path)
typer.echo(f"\n=== РЕЗУЛЬТАТ ===")
typer.echo(f"ПЗ: {estimate.grand_pz:>15,.2f}")
typer.echo(f"ОТ: {estimate.grand_ot:>15,.2f}")
typer.echo(f"ЭМ: {estimate.grand_em:>15,.2f}")
typer.echo(f"ОТм: {estimate.grand_otm:>15,.2f}")
typer.echo(f"Мат: {estimate.grand_mat:>15,.2f}")
typer.echo(f"Транспорт:{estimate.grand_transport:>14,.2f}")
typer.echo(f"ФОТ: {estimate.grand_fot:>15,.2f}")
typer.echo(f"НР: {estimate.grand_nr:>15,.2f}")
typer.echo(f"СП: {estimate.grand_sp:>15,.2f}")
typer.echo(f"ИТОГО: {estimate.grand_total:>15,.2f}")
typer.echo(f" = {estimate.grand_total / 1000:,.2f} тыс.руб.")
@app.command()
def fetch_resources(
project_yaml: Path = typer.Argument(..., help="Path to project YAML config"),
force: bool = typer.Option(False, "--force", help="Re-fetch all norms"),
):
"""Fetch GESN resource breakdowns from cs.smetnoedelo.ru."""
from smeta_railway.config import ProjectConfig
from smeta_railway.data.gesn import fetch_resources as do_fetch
config = ProjectConfig.from_yaml(project_yaml)
project_dir = project_yaml.parent
output_path = _resolve_path(config.resources_json, project_dir)
do_fetch(output_path, force=force)
@app.command()
def validate(
project_yaml: Path = typer.Argument(..., help="Path to project YAML config"),
):
"""Validate project YAML config."""
from smeta_railway.config import ProjectConfig
try:
config = ProjectConfig.from_yaml(project_yaml)
except Exception as e:
typer.echo(f"Validation FAILED: {e}", err=True)
raise typer.Exit(1)
n_sections = len(config.sections)
n_items = sum(
len(item)
for s in config.sections
for sub in s.subsections
for item in [sub.items]
)
typer.echo(f"OK: {n_sections} sections, {n_items} items")
typer.echo(f"Region: {config.region.subject}")
typer.echo(f"НР: {config.overhead.nr_railway}%, СП: {config.overhead.sp_railway}%")
typer.echo(f"Coefficients: {len(config.coefficients.definitions)}")
def _resolve_path(path_str: str, base_dir: Path) -> Path:
"""Resolve path relative to base_dir if not absolute."""
p = Path(path_str)
if p.is_absolute():
return p
return base_dir / p
if __name__ == "__main__":
app()
+110
View File
@@ -0,0 +1,110 @@
"""Pydantic models for YAML project configuration."""
from pathlib import Path
import yaml
from pydantic import BaseModel, Field
class ProjectInfo(BaseModel):
title: str = "ЛОКАЛЬНЫЙ СМЕТНЫЙ РАСЧЕТ (СМЕТА)"
number: str = "ЛС-03-02-4-00-01"
object_name: str = ""
section_name: str = ""
class RegionInfo(BaseModel):
subject: str = "Приморский край"
zone: str = 'Приморский край (ОАО "РЖД")'
class PriceLevel(BaseModel):
quarter: str = "I кв. 2026 г."
year: int = 2026
letter_number: str = "Письмо Минстроя России от 25.02.2026 №9859-ИФ/09"
dopolnenie: str = "Приказ Минстроя России от 17.02.2026 №91/пр"
labor_act: str = 'Распоряжение ОАО "РЖД" от 22.10.2021 №2281/р'
class CoefficientDef(BaseModel):
key: str # dvizhenie, vl, okno
code: str
name: str
value: float
apply_zt: bool = False
apply_em: bool = True
apply_ztm: bool = True
class CoefficientConfig(BaseModel):
definitions: list[CoefficientDef] = Field(default_factory=list)
exclude_norms: dict[str, list[str]] = Field(default_factory=dict)
# exclude_norms: {"okno": ["28-01-155-", "28-01-043-", "28-01-044-"]}
class OverheadConfig(BaseModel):
nr_railway: float = 109.0
sp_railway: float = 65.0
nr_earthwork: float = 92.0
sp_earthwork: float = 46.0
nr_code: str = "812/пр_2020_прил._т._п.22_гр.3"
sp_code: str = "774/пр_2020_прил._т._п.22_гр.3"
nr_label: str = "НР (Железные дороги)"
sp_label: str = "СП (Железные дороги)"
class WorkItem(BaseModel):
code: str # ГЭСН 28-01-037-02 | ФССЦпг ... | КП ... | Материал
name: str
unit: str
qty: float
note: str = ""
class Section(BaseModel):
name: str
subsections: list["Subsection"] = Field(default_factory=list)
class Subsection(BaseModel):
name: str | None = None
items: list[WorkItem] = Field(default_factory=list)
class TransportItem(BaseModel):
code: str
name: str
unit: str
base_price: float | None = None
current_price: float | None = None
note: str = ""
class OutputConfig(BaseModel):
format: str = "se27"
filename: str = "smeta.xlsx"
class FGISConfig(BaseModel):
xlsx_path: str = "fgis_split_form.xlsx"
cache_path: str = "fgis_cache.pkl"
class ProjectConfig(BaseModel):
project: ProjectInfo = Field(default_factory=ProjectInfo)
region: RegionInfo = Field(default_factory=RegionInfo)
price_level: PriceLevel = Field(default_factory=PriceLevel)
coefficients: CoefficientConfig = Field(default_factory=CoefficientConfig)
overhead: OverheadConfig = Field(default_factory=OverheadConfig)
sections: list[Section] = Field(default_factory=list)
transport_prices: dict[str, float] = Field(default_factory=dict)
fgis: FGISConfig = Field(default_factory=FGISConfig)
output: OutputConfig = Field(default_factory=OutputConfig)
resources_json: str = "resources.json"
gesn_prices: dict[str, list] = Field(default_factory=dict)
@classmethod
def from_yaml(cls, path: str | Path) -> "ProjectConfig":
with open(path, encoding="utf-8") as f:
data = yaml.safe_load(f)
return cls.model_validate(data)
View File
+139
View File
@@ -0,0 +1,139 @@
"""
FGIS CS (ФГИС ЦС) lookup — indices, base prices, current prices.
Loads from fgis_split_form.xlsx with pickle cache for fast restarts.
"""
import os
import pickle
import time
from dataclasses import dataclass, field
import openpyxl
@dataclass
class FGISLookup:
"""Lookup tables built from FGIS split form."""
index_map: dict[str, float] = field(default_factory=dict)
base_price_map: dict[str, float] = field(default_factory=dict)
current_price_map: dict[str, float] = field(default_factory=dict)
labor_price_map: dict[str, float] = field(default_factory=dict)
def get_index(self, code: str) -> float | None:
return self.index_map.get(code)
def get_base_price(self, code: str, fallback: float = 0) -> float:
return self.base_price_map.get(code, fallback)
def get_current_price(self, code: str) -> float | None:
return self.current_price_map.get(code)
def get_labor_price(self, code: str, default: float = 545.28) -> float:
return self.labor_price_map.get(code, default)
def _parse_float(val) -> float | None:
if val is None or val == "-":
return None
try:
return float(val)
except (ValueError, TypeError):
return None
def build_fgis_lookup(xlsx_path: str) -> FGISLookup:
"""Parse fgis_split_form.xlsx and build lookup tables."""
wb = openpyxl.load_workbook(xlsx_path, read_only=True)
ws = wb.active
lookup = FGISLookup()
for row in ws.iter_rows(min_row=1, values_only=True):
code = str(row[0]).strip() if row[0] else ""
if not code or len(code) < 5:
continue
# Labor codes: 1-100-XX or 4-100-XXX
if code.startswith("1-100-") or code.startswith("4-100-"):
price = _parse_float(row[7])
if price is not None:
lookup.labor_price_map[code] = price
continue
# Machine codes (91.xx)
if code.startswith("91."):
bp = _parse_float(row[4])
if bp is not None:
lookup.base_price_map[code] = bp
cp = _parse_float(row[7])
if cp is not None:
lookup.current_price_map[code] = cp
idx = _parse_float(row[8])
if idx is not None:
lookup.index_map[code] = idx
continue
# Material codes
for bp_col in [3, 4]:
bp = _parse_float(row[bp_col])
if bp is not None:
lookup.base_price_map[code] = bp
break
cp = _parse_float(row[7])
if cp is not None:
lookup.current_price_map[code] = cp
idx = _parse_float(row[8])
if idx is not None:
lookup.index_map[code] = idx
wb.close()
return lookup
def load_fgis(xlsx_path: str, cache_path: str | None = None) -> FGISLookup:
"""
Load FGIS lookup with pickle cache.
If cache_path is provided and exists and is newer than xlsx,
loads from pickle (~50ms). Otherwise parses xlsx and saves cache.
"""
if cache_path and os.path.exists(cache_path):
xlsx_mtime = os.path.getmtime(xlsx_path)
cache_mtime = os.path.getmtime(cache_path)
if cache_mtime > xlsx_mtime:
with open(cache_path, "rb") as f:
return pickle.load(f)
t0 = time.monotonic()
lookup = build_fgis_lookup(xlsx_path)
elapsed = time.monotonic() - t0
print(f"FGIS loaded in {elapsed:.2f}s: "
f"{len(lookup.index_map)} indices, "
f"{len(lookup.base_price_map)} base prices, "
f"{len(lookup.current_price_map)} current prices, "
f"{len(lookup.labor_price_map)} labor prices")
if cache_path:
with open(cache_path, "wb") as f:
pickle.dump(lookup, f)
return lookup
def get_labor_code(razryad: float, prefix: str = "1-100-") -> str:
"""Build labor code from razryad: 3.0 -> '1-100-30', 5.0 -> '4-100-050'."""
r = int(round(razryad * 10))
if prefix == "4-100-":
return f"4-100-0{r:02d}"
return f"1-100-{r:02d}"
def get_labor_current_price(
fgis: FGISLookup,
razryad: float,
is_machinist: bool = False,
) -> float:
"""Get current labor price from FGIS lookup."""
prefix = "4-100-" if is_machinist else "1-100-"
code = get_labor_code(razryad, prefix)
return fgis.get_labor_price(code)
+365
View File
@@ -0,0 +1,365 @@
"""
Fetch GESN resource breakdowns from cs.smetnoedelo.ru.
Parses HTML tables and saves to resources.json.
"""
import json
import os
import re
import subprocess
import sys
import time
from html.parser import HTMLParser
from pathlib import Path
from smeta_railway.models import (
LaborResource,
MachineResource,
MaterialResource,
NormResources,
)
class TableParser(HTMLParser):
"""Extract rows from the second table with class 'table-bordered'."""
def __init__(self):
super().__init__()
self.table_count = 0
self.in_target_table = False
self.in_row = False
self.in_cell = False
self.rows: list[list[str]] = []
self.current_row: list[str] = []
self.current_cell = ""
self.row_classes: list[str] = []
self.current_row_class = ""
def handle_starttag(self, tag, attrs):
attrs_dict = dict(attrs)
if tag == "table":
cls = attrs_dict.get("class", "")
if "table-bordered" in cls:
self.table_count += 1
if self.table_count == 2:
self.in_target_table = True
elif self.in_target_table:
if tag == "tr":
self.in_row = True
self.current_row = []
self.current_row_class = attrs_dict.get("class", "")
elif tag == "td" and self.in_row:
self.in_cell = True
self.current_cell = ""
def handle_endtag(self, tag):
if tag == "table" and self.in_target_table:
self.in_target_table = False
elif tag == "tr" and self.in_row and self.in_target_table:
self.rows.append(self.current_row)
self.row_classes.append(self.current_row_class)
self.in_row = False
elif tag == "td" and self.in_cell and self.in_target_table:
self.current_row.append(self.current_cell.strip())
self.in_cell = False
def handle_data(self, data):
if self.in_cell and self.in_target_table:
self.current_cell += data
def parse_number(s: str) -> float | None:
"""Parse a number like '122 149,32' or '337.28'."""
s = s.strip().replace("\xa0", " ").replace("\u00a0", " ")
if not s or s == "-":
return None
s = s.replace(" ", "").replace(",", ".")
try:
return float(s)
except ValueError:
return None
def parse_table(html: str) -> dict | None:
"""Parse the second table-bordered and extract resource breakdown."""
parser = TableParser()
parser.feed(html)
rows = parser.rows
classes = parser.row_classes
if len(rows) < 5:
return None
result = {
"norm_code": None, "norm_name": None, "unit": None,
"ozp": None, "machines": [], "materials": [], "totals": {},
}
for row in rows:
if len(row) >= 4:
m = re.search(
r"ГЭСН\s+(\d{2}-\d{2}-\d{3}-\d{2})",
row[1] if len(row) > 1 else "",
)
if m:
result["norm_code"] = m.group(1)
result["norm_name"] = row[2].strip() if len(row) > 2 else None
result["unit"] = row[3].strip() if len(row) > 3 else None
break
section = None
for i, row in enumerate(rows):
cls = classes[i] if i < len(classes) else ""
if len(row) < 3:
continue
col2 = row[2].strip() if len(row) > 2 else ""
col1 = row[1].strip() if len(row) > 1 else ""
if col2 == "ОТ(ЗТ)" and "font-weight-bold" in cls:
section = "ozp"
continue
if "Средний разряд" in col2 and section == "ozp":
razryad_match = re.search(
r"(\d+[.,]\d+|\d+)",
col2.replace("Средний разряд работы", "")
.replace("Средний разряд -", "")
.replace("Средний разряд", "").strip(),
)
razryad = razryad_match.group(1).replace(",", ".") if razryad_match else None
chel_hours = parse_number(row[4]) if len(row) > 4 else None
if chel_hours is None and len(row) > 6:
chel_hours = parse_number(row[6])
cost_base = parse_number(row[9]) if len(row) > 9 else None
result["ozp"] = {
"razryad": float(razryad) if razryad else None,
"chel_hours": chel_hours,
"cost_base": cost_base,
}
section = None
continue
if col2 == "ЭМ" and "font-weight-bold" in cls:
section = "em"
continue
if col2 in ("ОТм(ЗТм)", "ОТм(Зтм)") and "font-weight-bold" in cls:
continue
if col2 == "М" and "font-weight-bold" in cls:
section = "mat"
continue
if "Итого прямые затраты" in col2:
total_val = parse_number(row[-1]) if row else None
result["totals"]["pz"] = total_val
section = None
continue
if col2 == "ФОТ":
continue
if "text-secondary" in cls and "Средний разряд машинистов" in col2:
razryad_match = re.search(r"(\d+[.,]\d+|\d+)\s*$", col2)
if razryad_match and result["machines"]:
result["machines"][-1]["razryad_mash"] = float(
razryad_match.group(1).replace(",", ".")
)
continue
if section == "em" and len(row) >= 10:
code = col1.strip()
if re.match(r"\d{2}\.\d{2}\.\d{2}-\d{3}", code):
name = col2
unit = row[3].strip() if len(row) > 3 else ""
qty = parse_number(row[4]) if len(row) > 4 else None
if qty is None and len(row) > 6:
qty = parse_number(row[6])
cost_base = parse_number(row[9]) if len(row) > 9 else None
result["machines"].append({
"code": code, "name": name, "unit": unit,
"qty": qty, "cost_base": cost_base,
})
continue
if section == "mat" and len(row) >= 10:
code = col1.strip()
if re.match(r"\d{2}\.\d+\.\d{2}\.\d{2}-\d{4}", code):
name = col2
unit = row[3].strip() if len(row) > 3 else ""
qty = parse_number(row[4]) if len(row) > 4 else None
if qty is None and len(row) > 6:
qty = parse_number(row[6])
cost_base = parse_number(row[9]) if len(row) > 9 else None
result["materials"].append({
"code": code, "name": name, "unit": unit,
"qty": qty, "cost_base": cost_base,
})
continue
# Extract totals from bold summary rows
for i, row in enumerate(rows):
cls = classes[i] if i < len(classes) else ""
if "font-weight-bold" not in cls or len(row) < 3:
continue
col2 = row[2].strip()
val = parse_number(row[-1]) if row else None
if col2 == "ОТ(ЗТ)":
result["totals"]["ozp"] = val
elif col2 == "ЭМ":
result["totals"]["em"] = val
elif col2 in ("ОТм(ЗТм)", "ОТм(Зтм)"):
result["totals"]["em_zp"] = val
elif col2 == "М":
result["totals"]["mat"] = val
return result
def fetch_page(code: str) -> str | None:
"""Fetch HTML page from cs.smetnoedelo.ru."""
url = f"https://cs.smetnoedelo.ru/gesn2/gesn{code}.html"
try:
result = subprocess.run(
["curl", "-s", "--noproxy", "*", "--max-time", "15",
url, "-H", "User-Agent: Mozilla/5.0"],
capture_output=True, text=True,
env={k: v for k, v in os.environ.items()
if k not in ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")},
)
if result.returncode != 0:
return None
html = result.stdout
if not html or "<title>" not in html:
return None
return html
except Exception:
return None
DEFAULT_NORMS = [
"28-01-037-01", "28-01-037-02", "28-01-068-07", "28-01-031-01",
"28-01-041-01", "28-01-155-01", "28-01-155-11", "28-01-155-12",
"28-01-155-13", "28-01-155-14", "28-01-155-15", "28-01-155-16",
"28-01-155-17", "28-01-155-18", "28-01-075-01", "28-01-073-01",
"28-01-054-01", "28-01-027-04", "28-01-007-04", "28-01-043-01",
"28-01-008-01", "28-01-033-01", "28-01-076-01", "28-01-075-02",
"28-01-044-01", "01-02-057-02", "01-01-036-01",
]
def fetch_resources(
output_path: str | Path,
norms: list[str] | None = None,
force: bool = False,
) -> dict:
"""Fetch resources for norms and save to JSON."""
norms = norms or DEFAULT_NORMS
output_path = Path(output_path)
existing: dict = {}
if output_path.exists() and not force:
with open(output_path, encoding="utf-8") as f:
try:
existing = json.load(f)
except json.JSONDecodeError:
existing = {}
results = dict(existing)
fetched = skipped = errors = 0
for code in norms:
if code in results and not force:
print(f"[SKIP] {code}")
skipped += 1
continue
print(f"[FETCH] {code} ...", end=" ", flush=True)
html = fetch_page(code)
if not html:
errors += 1
results[code] = {"error": "fetch_failed"}
continue
if "404" in html and "не найден" in html.lower():
print("NOT FOUND")
errors += 1
results[code] = {"error": "not_found_404"}
time.sleep(2)
continue
parsed = parse_table(html)
if not parsed or not parsed["norm_code"]:
print("PARSE ERROR")
errors += 1
results[code] = {"error": "parse_failed"}
continue
results[code] = parsed
fetched += 1
n_m = len(parsed.get("machines", []))
n_mat = len(parsed.get("materials", []))
print(f"OK ({n_m} machines, {n_mat} materials)")
with open(output_path, "w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
if code != norms[-1]:
time.sleep(2)
with open(output_path, "w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"\nDone: {fetched} fetched, {skipped} skipped, {errors} errors")
return results
def load_resources(path: str | Path) -> dict[str, NormResources]:
"""Load resources.json and convert to NormResources."""
with open(path, encoding="utf-8") as f:
raw = json.load(f)
result: dict[str, NormResources] = {}
for code, data in raw.items():
if "error" in data:
continue
ozp = None
if data.get("ozp"):
o = data["ozp"]
ozp = LaborResource(
razryad=o.get("razryad", 3.0),
chel_hours=o.get("chel_hours", 0),
cost_base=o.get("cost_base"),
)
machines = [
MachineResource(
code=m["code"], name=m["name"], unit=m.get("unit", ""),
qty=m.get("qty", 0), cost_base=m.get("cost_base", 0),
razryad_mash=m.get("razryad_mash"),
)
for m in data.get("machines", [])
]
materials = [
MaterialResource(
code=m["code"], name=m["name"], unit=m.get("unit", ""),
qty=m.get("qty", 0), cost_base=m.get("cost_base", 0),
)
for m in data.get("materials", [])
]
result[code] = NormResources(
norm_code=data.get("norm_code", code),
norm_name=data.get("norm_name"),
unit=data.get("unit"),
ozp=ozp,
machines=machines,
materials=materials,
totals=data.get("totals", {}),
)
return result
+103
View File
@@ -0,0 +1,103 @@
"""
GESN base prices and transport prices.
Separated from monolithic prices.py for clarity.
GESN_PRICES: gesn_code -> (name, unit, base_price, ozp, em, mat, note)
TRANSPORT_PRICES: code -> (name, unit, current_price, ...)
"""
# GESN-2022 base prices (Collection 28, supplement 17)
GESN_PRICES: dict[str, tuple] = {
"28-01-037-01": ("Замена рельсов на плети, КБ, 2000 шп/км",
"км пути", 12_473_450.04, 129_722.09, 77_050.93, 12_266_677.03, ""),
"28-01-037-02": ("Замена рельсов на плети, КБ, 1840 шп/км",
"км пути", 12_464_484.16, 122_149.32, 75_657.81, 12_266_677.03, ""),
"28-01-068-07": ("Глубокая очистка щебня ЩОМ, ж/б, 1840 шп/км",
"км пути", 1_150_086.00, None, None, None, "без разд. слоя"),
"28-01-068-09": ("Глубокая очистка щебня ЩОМ самоходные, ж/б, 1840",
"км пути", 645_635.00, None, None, None, "600-800 м³/ч"),
"28-01-031-01": ("Выправка пути ВПО, 1 проход",
"км", 25_454.00, None, None, None, ""),
"28-01-031-03": ("Выправка пути ВПРМ до 2000 шп/ч, 1 проход",
"км", 70_128.00, None, None, None, ""),
"28-01-041-01": ("Сварка рельсовых плетей ПРСМ",
"2 стыка", 100_481.10, 4_966.32, 95_495.32, None, ""),
"28-01-042-01": ("Сварка стыков алюминотермитным способом",
"2 стыка", 51_406.00, None, None, None, ""),
"28-01-155-01": ("Замена скреплений КБ, 1 класс, средний",
"км", 277_544.00, None, None, None, ""),
"28-01-155-11": ("Подкладки (за 100 шт)", "100 шт", 132_005.00, None, None, None, ""),
"28-01-155-12": ("Болты закладные с гайками (за 100 шт)", "100 шт", 11_211.00, None, None, None, ""),
"28-01-155-13": ("Болты клеммные с гайками (за 100 шт)", "100 шт", 8_867.00, None, None, None, ""),
"28-01-155-14": ("Шайбы двухвитковые (за 100 шт)", "100 шт", 3_384.00, None, None, None, ""),
"28-01-155-15": ("Клеммы промежуточные (за 100 шт)", "100 шт", 11_853.00, None, None, None, ""),
"28-01-155-16": ("Прокладки под рельс (за 100 шт)", "100 шт", 6_478.00, None, None, None, ""),
"28-01-155-17": ("Прокладки под подкладки (за 100 шт)", "100 шт", 20_132.00, None, None, None, ""),
"28-01-155-18": ("Втулки изолирующие (за 100 шт)", "100 шт", 4_815.00, None, None, None, ""),
"28-01-075-01": ("Уборка срезанного балласта", "100 м³", 12_103.84, 4_084.36, 8_019.48, None, ""),
"28-01-073-01": ("Очистка балласта вручную в местах препятствий",
"м", 2_382.79, 1_498.55, 884.24, None, "глубина до 20 см"),
"28-01-054-01": ("Замена РШР бесстыкового пути с резкой плетей",
"км", 435_850.24, 96_890.17, 338_960.08, None, "2000 шп/км"),
"28-01-027-04": ("Балластировка пути, ж/б шпалы, щебень",
"1000 м³", 3_396_794.00, None, None, None, ""),
"28-01-007-04": ("Разборка пути на мостах поэлементно",
"км", 612_447.00, None, None, None, ""),
"28-01-043-01": ("Резка рельсов рельсорезным станком",
"пар резок", 8_432.00, None, None, None, ""),
"28-01-008-01": ("Демонтаж пути поэлементно",
"км", 612_447.00, None, None, None, ""),
"28-01-033-01": ("Балластировка пути на ж/б шпалах",
"м³", 3_396.79, None, None, None, ""),
"28-01-076-01": ("Очистка кюветов МКТ",
"м", 856.00, None, None, None, ""),
"28-01-075-02": ("Формирование бровки з.п., вырезка балласта",
"100 м³", 14_520.00, None, None, None, ""),
"28-01-044-01": ("Устройство изолирующего стыка вварного",
"пара", 45_800.00, None, None, None, ""),
"01-02-057-02": ("Разработка грунта экскаватором ковш 0,65 м³",
"100 м³", 7_853.00, None, None, None, ""),
"01-01-036-01": ("Планировка площадей бульдозером 121 кВт",
"1000 м²", 2_145.00, None, None, None, ""),
}
# Transport prices — FGIS CS, current Q1 2026
TRANSPORT_PRICES: dict[str, tuple] = {
"ФССЦпг-236019-00-0071-0080": (
"Перевозка ж/д транспортом балласта, ХДВ, 73 км",
"1 т груза", 815.96, None, None, None, ""),
"ФССЦпг-236019-00-0001-0005": (
"Перевозка ж/д транспортом балласта (засорители), ХДВ, 5 км",
"1 т груза", 731.17, None, None, None, ""),
"ФССЦпг-371051-04-0071-0080": (
"Перевозка ж/д транспортом металлоконструкций, платформы, 73 км",
"1 т груза", 2_887.50, None, None, None, ""),
"ФССЦпг-371051-04-0071-0080-new": (
"Перевозка ж/д транспортом металлоконструкций (новые), платформы, 73 км",
"1 т груза", 2_887.50, None, None, None, ""),
"ФССЦпг-371051-05-0331-0360": (
"Перевозка ж/д старогодных плетей, сцеп платформ, 337 км",
"1 т груза", 4_171.60, None, None, None, ""),
"ФССЦпг-02-15-1-03-0003": (
"Перевозка автосамосвалами грунта, 3 км",
"1 т груза", 116.12, None, None, None, ""),
"ФССЦпг-01-20-3-01-0012": (
"Перевозка автобортовыми оборудования СЦБ, 12 км",
"1 т груза", 865.92, None, None, None, ""),
}
# Commercial proposals (КП)
KP_PRICES: dict[str, tuple] = {
"КП-РСП-19": ("Сварка рельсов Р65 на РСП-19 ст. Хабаровск-II",
"стык", 8_129.21, None, None, None,
"КП РСП-19, цена текущая Q1 2026, конъюнктурный анализ"),
}
def get_all_prices() -> dict[str, tuple]:
"""Combined dict of all prices for backward compat."""
all_prices = {}
all_prices.update(GESN_PRICES)
all_prices.update(TRANSPORT_PRICES)
all_prices.update(KP_PRICES)
return all_prices
+91
View File
@@ -0,0 +1,91 @@
"""Domain dataclasses for estimate entities."""
from dataclasses import dataclass, field
@dataclass
class LaborResource:
razryad: float
chel_hours: float
cost_base: float | None = None
@dataclass
class MachineResource:
code: str
name: str
unit: str
qty: float
cost_base: float = 0
razryad_mash: float | None = None
@dataclass
class MaterialResource:
code: str
name: str
unit: str
qty: float
cost_base: float = 0
@dataclass
class NormResources:
norm_code: str
norm_name: str | None = None
unit: str | None = None
ozp: LaborResource | None = None
machines: list[MachineResource] = field(default_factory=list)
materials: list[MaterialResource] = field(default_factory=list)
totals: dict[str, float | None] = field(default_factory=dict)
@dataclass
class Coefficients:
zt: float = 1.0
em: float = 1.0
ztm: float = 1.0
applied: list[str] = field(default_factory=list)
formulas: dict[str, str] = field(default_factory=dict)
@dataclass
class PositionResult:
"""Result of calculating one estimate position."""
gesn_code: str
name: str
unit: str
qty: float
ot_cost: float = 0.0
em_cost: float = 0.0
otm_cost: float = 0.0
mat_cost: float = 0.0
pz: float = 0.0
fot: float = 0.0
nr: float = 0.0
sp: float = 0.0
total: float = 0.0
zt_hours: float = 0.0
ztm_hours: float = 0.0
transport_cost: float = 0.0
is_transport: bool = False
is_kp: bool = False
is_material: bool = False
@dataclass
class EstimateResult:
"""Aggregated result of the entire estimate."""
positions: list[PositionResult] = field(default_factory=list)
grand_pz: float = 0.0
grand_ot: float = 0.0
grand_em: float = 0.0
grand_otm: float = 0.0
grand_mat: float = 0.0
grand_transport: float = 0.0
grand_fot: float = 0.0
grand_nr: float = 0.0
grand_sp: float = 0.0
grand_total: float = 0.0
grand_zt_hours: float = 0.0
grand_ztm_hours: float = 0.0
+799
View File
@@ -0,0 +1,799 @@
"""
Excel output in 27-column "Stroitelnyj Ekspert" format.
Replaces generate_smeta_v2.py lines 132-590 + 1022-1160.
"""
import openpyxl
from openpyxl.styles import Alignment, Border, Font, Side
from openpyxl.worksheet.properties import PageSetupProperties
from smeta_railway.calc.coefficients import (
get_coeff_codes,
get_coeff_names,
get_coefficients,
)
from smeta_railway.calc.overhead import get_overhead_percents
from smeta_railway.config import (
CoefficientConfig,
OverheadConfig,
ProjectConfig,
Section,
)
from smeta_railway.data.fgis import (
FGISLookup,
get_labor_code,
get_labor_current_price,
)
from smeta_railway.data.prices import TRANSPORT_PRICES, KP_PRICES
from smeta_railway.models import EstimateResult, NormResources
# ============================================================
# Styles
# ============================================================
FONT = Font(name="Times New Roman", size=10)
FONT_BOLD = Font(name="Times New Roman", size=10, bold=True)
FONT_ITALIC = Font(name="Times New Roman", size=10, italic=True)
FONT_BOLD_ITALIC = Font(name="Times New Roman", size=10, bold=True, italic=True)
THIN = Side(style="thin")
BORDER_ALL = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
ALIGN_CENTER = Alignment(horizontal="center", vertical="center", wrap_text=True)
ALIGN_LEFT = Alignment(horizontal="left", vertical="top", wrap_text=True)
ALIGN_RIGHT = Alignment(horizontal="right", vertical="top")
COL_WIDTHS = {
"A": 5.5, "B": 1.5, "C": 3.5, "D": 1.5, "E": 10.5, "F": 6.5, "G": 3.5,
"H": 4.5, "I": 6.5, "J": 11.5, "K": 1.5, "L": 4.5, "M": 1.5,
"N": 4.5, "O": 6.5, "P": 13.5, "Q": 1.5, "R": 13.0, "S": 6.5,
"T": 13.0, "U": 7.5, "V": 5.5, "W": 6.5, "X": 13.0, "Y": 12.5,
"Z": 8.5, "AA": 13.5,
}
def write_data_row(ws, r, col1=None, col2=None, col8=None, col14=None,
col16=None, col17=None, col20=None, col22=None,
col24=None, col25=None, col26=None, col27=None,
font=FONT, merge_8_to_aa=False, bold_27=False):
"""Write a single data row with the 27-column merged layout."""
if merge_8_to_aa:
ws.merge_cells(start_row=r, start_column=2, end_row=r, end_column=7)
ws.merge_cells(start_row=r, start_column=8, end_row=r, end_column=27)
ws.cell(r, 1).value = col1
ws.cell(r, 1).font = font
ws.cell(r, 2).value = col2
ws.cell(r, 2).font = font
ws.cell(r, 8).value = col8
ws.cell(r, 8).font = font
ws.cell(r, 8).alignment = ALIGN_LEFT
return
ws.merge_cells(start_row=r, start_column=2, end_row=r, end_column=7)
ws.merge_cells(start_row=r, start_column=8, end_row=r, end_column=13)
ws.merge_cells(start_row=r, start_column=14, end_row=r, end_column=15)
ws.merge_cells(start_row=r, start_column=17, end_row=r, end_column=19)
ws.merge_cells(start_row=r, start_column=20, end_row=r, end_column=21)
ws.merge_cells(start_row=r, start_column=22, end_row=r, end_column=23)
cells = {
1: col1, 2: col2, 8: col8, 14: col14, 16: col16,
17: col17, 20: col20, 22: col22, 24: col24,
25: col25, 26: col26,
}
for c, v in cells.items():
ws.cell(r, c).value = v
ws.cell(r, c).font = font
ws.cell(r, 8).alignment = ALIGN_LEFT
f27 = Font(name="Times New Roman", size=10, bold=bold_27)
ws.cell(r, 27).value = col27
ws.cell(r, 27).font = f27
def write_section_row(ws, r, text):
"""Write a section header row spanning all columns."""
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
ws.cell(r, 1).value = text
ws.cell(r, 1).font = FONT_BOLD
ws.cell(r, 1).alignment = ALIGN_LEFT
def generate_excel(
config: ProjectConfig,
estimate: EstimateResult,
fgis: FGISLookup,
resources: dict[str, NormResources],
output_path: str,
) -> str:
"""Generate 27-column SE format Excel file."""
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Smeta"
for col_letter, width in COL_WIDTHS.items():
ws.column_dimensions[col_letter].width = width
r = 1
# ========== HEADER ==========
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=27)
r = 2
header_data = [
("Наименование программного продукта ",
'Программный комплекс "Строительный эксперт" (7.2.7.7796)'),
("Наименование редакции сметных нормативов ",
"ФСНБ-2022, Приказ Минстроя России от 30.12.2021 №1046/пр,\n"
"Приказ Минстроя России от 04.08.2020 №421/пр,\n"
"Приказ Минстроя России от 21.12.2020 №812/пр,\n"
"Приказ Минстроя России от 11.12.2020 №774/пр"),
("Реквизиты приказа Минстроя России об утверждении "
"дополнений и изменений к сметным нормативам ",
config.price_level.dopolnenie),
("Реквизиты письма Минстроя России об индексах изменения сметной "
"стоимости строительства, включаемые в федеральный реестр сметных "
"нормативов и размещаемые в федеральной государственной "
"информационной системе ценообразования в строительстве, "
"подготовленного в соответствии с пунктом 85 Методики расчета "
"индексов изменения сметной стоимости строительства, утвержденной "
"приказом Министерства строительства и жилищно-коммунального "
"хозяйства Российской Федерации от 5 июня 2019 г. №326/пр ",
config.price_level.letter_number),
("Реквизиты нормативно-правового акта об утверждении оплаты труда, "
"утверждаемый в соответствии с пунктом 22(1) Правилами мониторинга "
"цен, утвержденными постановлением Правительства Российской "
"Федерации от 23 декабря 2016 г. №1452 ",
config.price_level.labor_act),
("Обоснование принятых текущих цен на строительные ресурсы ",
config.price_level.letter_number),
("Наименование субъекта Российской Федерации ",
config.region.subject),
("Наименование зоны субъекта Российской Федерации ",
config.region.zone),
]
for label, value in header_data:
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=17)
ws.merge_cells(start_row=r, start_column=18, end_row=r, end_column=27)
ws.cell(r, 1).value = label
ws.cell(r, 1).font = FONT
ws.cell(r, 1).alignment = ALIGN_LEFT
ws.cell(r, 18).value = value
ws.cell(r, 18).font = FONT
ws.cell(r, 18).alignment = ALIGN_LEFT
r += 1
# Empty row
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
r += 1
# (naimenovanie strojki)
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
ws.cell(r, 1).value = "(наименование стройки)"
ws.cell(r, 1).font = FONT
ws.cell(r, 1).alignment = Alignment(horizontal="center")
r += 1
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
r += 1
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
ws.cell(r, 1).value = "(наименование объекта капитального строительства)"
ws.cell(r, 1).font = FONT
ws.cell(r, 1).alignment = Alignment(horizontal="center")
r += 1
# Title
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
ws.cell(r, 1).value = f"{config.project.title} № {config.project.number}"
ws.cell(r, 1).font = FONT_BOLD
ws.cell(r, 1).alignment = Alignment(horizontal="center")
r += 1
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
r += 1
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
ws.cell(r, 1).value = "(наименование работ и затрат)"
ws.cell(r, 1).font = FONT
ws.cell(r, 1).alignment = Alignment(horizontal="center")
r += 1
# Method
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=4)
ws.merge_cells(start_row=r, start_column=5, end_row=r, end_column=10)
ws.merge_cells(start_row=r, start_column=11, end_row=r, end_column=27)
ws.cell(r, 1).value = "Составлен "
ws.cell(r, 1).font = FONT
ws.cell(r, 5).value = "ресурсно-индексным"
ws.cell(r, 5).font = FONT
ws.cell(r, 11).value = " методом"
ws.cell(r, 11).font = FONT
r += 1
# Osnovanie
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=4)
ws.merge_cells(start_row=r, start_column=5, end_row=r, end_column=14)
ws.merge_cells(start_row=r, start_column=15, end_row=r, end_column=27)
ws.cell(r, 1).value = "Основание "
ws.cell(r, 1).font = FONT
r += 1
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=4)
ws.merge_cells(start_row=r, start_column=5, end_row=r, end_column=14)
ws.merge_cells(start_row=r, start_column=15, end_row=r, end_column=27)
ws.cell(r, 5).value = "(проектная и (или) иная техническая документация)"
ws.cell(r, 5).font = FONT
r += 1
# Price level
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=8)
ws.merge_cells(start_row=r, start_column=9, end_row=r, end_column=11)
ws.merge_cells(start_row=r, start_column=12, end_row=r, end_column=27)
ws.cell(r, 1).value = "Составлен(а) в текущем уровне цен "
ws.cell(r, 1).font = FONT
ws.cell(r, 9).value = config.price_level.quarter
ws.cell(r, 9).font = FONT
r += 1
# Total cost placeholder
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=5)
ws.merge_cells(start_row=r, start_column=6, end_row=r, end_column=9)
ws.merge_cells(start_row=r, start_column=10, end_row=r, end_column=27)
ws.cell(r, 1).value = "Сметная стоимость "
ws.cell(r, 1).font = FONT
ws.cell(r, 10).value = " тыс.руб."
ws.cell(r, 10).font = FONT
total_cost_cell_row = r
r += 1
# Summary block (OT, OTm, stroit, montazh, etc.)
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=2)
ws.merge_cells(start_row=r, start_column=3, end_row=r, end_column=12)
ws.merge_cells(start_row=r, start_column=13, end_row=r, end_column=20)
ws.merge_cells(start_row=r, start_column=21, end_row=r, end_column=22)
ws.merge_cells(start_row=r, start_column=23, end_row=r, end_column=27)
ws.cell(r, 3).value = "в том числе:"
ws.cell(r, 3).font = FONT
ws.cell(r, 13).value = "Средства на оплату труда рабочих "
ws.cell(r, 13).font = FONT
ws.cell(r, 23).value = " тыс.руб."
ws.cell(r, 23).font = FONT
ot_summary_row = r
r += 1
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=2)
ws.merge_cells(start_row=r, start_column=3, end_row=r, end_column=12)
ws.merge_cells(start_row=r, start_column=13, end_row=r, end_column=20)
ws.merge_cells(start_row=r, start_column=21, end_row=r, end_column=22)
ws.merge_cells(start_row=r, start_column=23, end_row=r, end_column=27)
ws.cell(r, 13).value = "Средства на оплату труда машинистов "
ws.cell(r, 13).font = FONT
ws.cell(r, 23).value = " тыс.руб."
ws.cell(r, 23).font = FONT
otm_summary_row = r
r += 1
for label, val_col, remark, remark_unit in [
("строительных работ ", 7, "Нормативные затраты труда рабочих ", " чел.-ч"),
("монтажных работ ", 7, "Нормативные затраты труда машинистов ", " чел.-ч"),
("оборудования ", 7, "Расчетный измеритель", ""),
("прочих затрат ", 7, "конструктивного решения ", " "),
]:
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=2)
ws.merge_cells(start_row=r, start_column=3, end_row=r, end_column=6)
ws.merge_cells(start_row=r, start_column=7, end_row=r, end_column=9)
ws.merge_cells(start_row=r, start_column=10, end_row=r, end_column=12)
ws.merge_cells(start_row=r, start_column=13, end_row=r, end_column=20)
ws.merge_cells(start_row=r, start_column=21, end_row=r, end_column=22)
ws.merge_cells(start_row=r, start_column=23, end_row=r, end_column=27)
ws.cell(r, 3).value = label
ws.cell(r, 3).font = FONT
ws.cell(r, 10).value = " тыс.руб."
ws.cell(r, 10).font = FONT
ws.cell(r, 13).value = remark
ws.cell(r, 13).font = FONT
ws.cell(r, 23).value = remark_unit
ws.cell(r, 23).font = FONT
r += 1
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
r += 1
# ========== TABLE HEADER ==========
ws.merge_cells(start_row=r, start_column=1, end_row=r + 1, end_column=1)
ws.merge_cells(start_row=r, start_column=2, end_row=r + 1, end_column=7)
ws.merge_cells(start_row=r, start_column=8, end_row=r + 1, end_column=13)
ws.merge_cells(start_row=r, start_column=14, end_row=r + 1, end_column=15)
ws.merge_cells(start_row=r, start_column=16, end_row=r, end_column=21)
ws.merge_cells(start_row=r, start_column=22, end_row=r, end_column=27)
for c, v in [(1, "№ п/п"), (2, "Обоснование"), (8, "Наименование работ и затрат"),
(14, "Единица измерения"), (16, "Количество"),
(22, "Сметная стоимость, руб")]:
ws.cell(r, c).value = v
ws.cell(r, c).font = FONT
ws.cell(r, c).alignment = ALIGN_CENTER
r += 1
# Sub-header row
for c, v in [(16, "на единицу измерения"), (20, "всего с учетом коэффициентов"),
(22, "на единицу измерения в базисном уровне цен"),
(24, "индекс"), (25, "на единицу измерения в текущем уровне цен"),
(26, "коэффициенты"), (27, "всего в текущем уровне цен")]:
ws.cell(r, c).value = v
ws.cell(r, c).font = FONT
ws.cell(r, c).alignment = ALIGN_CENTER
ws.merge_cells(start_row=r, start_column=17, end_row=r, end_column=19)
ws.cell(r, 17).value = "коэффициенты"
ws.cell(r, 17).font = FONT
ws.cell(r, 17).alignment = ALIGN_CENTER
ws.merge_cells(start_row=r, start_column=20, end_row=r, end_column=21)
ws.merge_cells(start_row=r, start_column=22, end_row=r, end_column=23)
r += 1
# Column numbers
col_nums = {1: "1", 2: "2", 8: "3", 14: "4", 16: "5", 17: "6",
20: "7", 22: "8", 24: "9", 25: "10", 26: "11", 27: "12"}
for c, v in col_nums.items():
ws.cell(r, c).value = v
ws.cell(r, c).font = FONT
ws.cell(r, c).alignment = ALIGN_CENTER
ws.merge_cells(start_row=r, start_column=2, end_row=r, end_column=7)
ws.merge_cells(start_row=r, start_column=8, end_row=r, end_column=13)
ws.merge_cells(start_row=r, start_column=14, end_row=r, end_column=15)
ws.merge_cells(start_row=r, start_column=17, end_row=r, end_column=19)
ws.merge_cells(start_row=r, start_column=20, end_row=r, end_column=21)
ws.merge_cells(start_row=r, start_column=22, end_row=r, end_column=23)
r += 2 # empty row
# SP notice
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
ws.cell(r, 1).value = ("СП применена, согласно Методике по приказу "
"Минстроя РФ № 774/пр от 11.12.2020 г.")
ws.cell(r, 1).font = FONT
r += 2
# NR notice
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=27)
ws.cell(r, 1).value = ("НР применены, согласно Методике по приказу "
"Минстроя РФ № 812/пр от 21.12.2020г.")
ws.cell(r, 1).font = FONT
r += 2
# ========== DATA ROWS ==========
coeff_codes = get_coeff_codes(config.coefficients)
coeff_names = get_coeff_names(config.coefficients)
item_num = 0
grand = estimate # shortcut
for section in config.sections:
write_section_row(ws, r, section.name)
r += 1
for subsection in section.subsections:
if subsection.name:
write_section_row(ws, r, subsection.name)
r += 1
for item in subsection.items:
gesn_code = item.code
qty = item.qty
is_material = gesn_code == "Материал"
is_transport = gesn_code.startswith("ФССЦпг")
is_kp = gesn_code.startswith("КП ")
code_key = gesn_code.replace("ГЭСН ", "").strip()
item_num += 1
# --- TRANSPORT ---
if is_transport:
price_key = gesn_code.replace("ФССЦпг ", "ФССЦпг-").strip()
price_data = TRANSPORT_PRICES.get(price_key)
current_price = price_data[2] if price_data else 0.0
total_cost = round(qty * current_price, 2)
display_code = gesn_code.replace("ФССЦпг ", "")
write_data_row(ws, r, col1=item_num, col2=display_code,
col8=item.name, col14=item.unit, col16=qty,
col20=qty, col25=current_price, col27=total_cost)
r += 1
write_data_row(ws, r)
r += 1
write_data_row(ws, r, col8="Всего по позиции",
col25=current_price, col27=total_cost)
r += 1
continue
# --- MATERIAL ---
if is_material:
write_data_row(ws, r, col1=item_num, col8=item.name,
col14=item.unit, col16=qty)
r += 1
continue
# --- KP ---
if is_kp:
price_key = gesn_code.replace("КП ", "КП-").strip()
price_data = KP_PRICES.get(price_key)
current_price = price_data[2] if price_data else 0.0
total_cost = round(qty * current_price, 2)
write_data_row(ws, r, col1=item_num, col2=gesn_code,
col8=item.name, col14=item.unit, col16=qty,
col20=qty, col25=current_price, col27=total_cost)
r += 1
write_data_row(ws, r)
r += 1
write_data_row(ws, r, col8="Всего по позиции",
col25=current_price, col27=total_cost)
r += 1
continue
# --- GESN (full resource expansion) ---
res = resources.get(code_key)
if not res:
write_data_row(ws, r, col1=item_num,
col2=f"ГЭСН {code_key}", col8=item.name,
col14=item.unit, col16=qty, col20=qty,
font=FONT_BOLD)
r += 1
continue
coeffs = get_coefficients(gesn_code, config.coefficients)
k_zt = coeffs.zt
k_em = coeffs.em
k_ztm = coeffs.ztm
# Main norm line
write_data_row(ws, r, col1=item_num,
col2=f"ГЭСН {code_key}", col8=item.name,
col14=item.unit, col16=qty, col20=qty,
font=FONT_BOLD)
r += 1
# Coefficient lines
for coeff_key in coeffs.applied:
coeff_code = coeff_codes.get(coeff_key, "")
coeff_name = coeff_names.get(coeff_key, "")
write_data_row(ws, r, col2=coeff_code, col8=coeff_name,
merge_8_to_aa=True, font=FONT_ITALIC)
r += 1
if coeffs.applied:
write_data_row(ws, r, col8="Результирующие коэффициенты",
merge_8_to_aa=True, font=FONT_BOLD_ITALIC)
r += 1
for label, formula in [
("ЭМ", coeffs.formulas.get("em", "")),
("ЗТ", coeffs.formulas.get("zt", "")),
("ЗТм", coeffs.formulas.get("ztm", "")),
]:
if formula:
write_data_row(ws, r, col8=f"{label}: {formula}",
merge_8_to_aa=True, font=FONT_ITALIC)
r += 1
# === OT(ZT) ===
ozp = res.ozp
if ozp:
razryad = ozp.razryad
chel_hours = ozp.chel_hours
labor_code = get_labor_code(razryad)
labor_price = get_labor_current_price(fgis, razryad)
total_zt_hours = round(chel_hours * qty * k_zt, 7)
ot_cost = round(total_zt_hours * labor_price, 2)
write_data_row(ws, r, col2=" 1", col8="ОТ(ЗТ)",
col14="чел.-ч", col20=total_zt_hours,
col27=ot_cost, bold_27=True)
r += 1
write_data_row(ws, r, col2=labor_code,
col8=f"Средний разряд работы {razryad:.1f}",
col14="чел.-ч", col16=chel_hours,
col17=k_zt if k_zt != 1.0 else "",
col20=total_zt_hours,
col25=labor_price, col27=ot_cost)
r += 1
else:
ot_cost = 0.0
total_zt_hours = 0.0
# === EM ===
em_total_cost = 0.0
otm_total_hours = 0.0
otm_total_cost = 0.0
machine_rows_data = []
for m in res.machines:
m_index = fgis.get_index(m.code)
m_base_fgis = fgis.get_base_price(m.code, m.cost_base)
m_current_fgis = 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:
m_current = m.cost_base
else:
m_current = 0
total_m_qty = round(m.qty * qty * k_em, 7)
m_cost = round(total_m_qty * m_current, 2)
md = {
"code": m.code, "name": m.name,
"qty_per_unit": m.qty, "total_qty": total_m_qty,
"base_price": m_base_fgis if m_base_fgis else m.cost_base,
"index": m_index, "current_price": m_current, "cost": m_cost,
"razryad_mash": m.razryad_mash,
}
em_total_cost += m_cost
if m.razryad_mash:
mach_hours = round(m.qty * qty * k_ztm, 7)
mach_price = get_labor_current_price(
fgis, m.razryad_mash, is_machinist=True
)
mach_cost = round(mach_hours * mach_price, 2)
otm_total_hours += mach_hours
otm_total_cost += mach_cost
md["mach_hours"] = mach_hours
md["mach_price"] = mach_price
md["mach_cost"] = mach_cost
machine_rows_data.append(md)
write_data_row(ws, r, col2=" 2", col8="ЭМ",
col27=em_total_cost, bold_27=True)
r += 1
write_data_row(ws, r, col8="ОТм(ЗТм)", col14="чел.-ч",
col20=round(otm_total_hours, 7),
col27=round(otm_total_cost, 2))
r += 1
for md in machine_rows_data:
write_data_row(ws, r, col2=md["code"],
col8=md["name"], col14="маш.-ч",
col16=md["qty_per_unit"],
col17=k_em if k_em != 1.0 else "",
col20=md["total_qty"],
col22=md["base_price"],
col24=md["index"] if md["index"] else "",
col25=md["current_price"],
col27=md["cost"])
r += 1
if md.get("razryad_mash"):
raz = md["razryad_mash"]
mash_labor_code = get_labor_code(raz, "4-100-")
write_data_row(
ws, r, col2=mash_labor_code,
col8=f"ОТм(ЗТм) Средний разряд машинистов {raz:.1f}",
col14="чел.-ч", col16=md["qty_per_unit"],
col17=k_ztm if k_ztm != 1.0 else "",
col20=md.get("mach_hours", 0),
col25=md.get("mach_price", 0),
col27=md.get("mach_cost", 0))
r += 1
# === Materials ===
mat_total_cost = 0.0
mat_rows_data = []
for mat in res.materials:
mat_index = fgis.get_index(mat.code)
mat_base_fgis = fgis.get_base_price(mat.code, mat.cost_base)
mat_current_fgis = fgis.get_current_price(mat.code)
if mat.code == "02.2.05.04-0061":
mat_rows_data.append({
"code": mat.code, "name": mat.name,
"unit": mat.unit, "qty": "П", "total_qty": 0,
"base_price": mat_base_fgis, "index": mat_index,
"current_price": 0, "cost": 0, "is_project": True,
})
continue
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:
mat_current = mat.cost_base
else:
mat_current = 0
total_mat_qty = round(mat.qty * qty, 7)
mat_cost = round(total_mat_qty * mat_current, 2)
mat_total_cost += mat_cost
mat_rows_data.append({
"code": mat.code, "name": mat.name,
"unit": mat.unit, "qty": mat.qty,
"total_qty": total_mat_qty, "base_price": mat_base_fgis,
"index": mat_index, "current_price": mat_current,
"cost": mat_cost, "is_project": False,
})
if res.materials:
write_data_row(ws, r, col2=" 4", col8="М",
col27=mat_total_cost, bold_27=True)
r += 1
for md in mat_rows_data:
if md["is_project"]:
write_data_row(ws, r, col2=md["code"],
col8=md["name"], col14=md["unit"],
col16="П", col20=0)
else:
write_data_row(ws, r, col2=md["code"],
col8=md["name"], col14=md["unit"],
col16=md["qty"], col20=md["total_qty"],
col22=md["base_price"],
col24=md["index"] if md["index"] else "",
col25=md["current_price"],
col27=md["cost"])
r += 1
# === Totals per position ===
pz = round(ot_cost + em_total_cost + mat_total_cost, 2)
write_data_row(ws, r, col8="Итого прямые затраты", col27=pz)
r += 1
fot = round(ot_cost + otm_total_cost, 2)
write_data_row(ws, r, col8="ФОТ", col27=fot)
r += 1
nr_pct, sp_pct, nr_code, nr_label, sp_code, sp_label = \
get_overhead_percents(gesn_code, config.overhead)
nr = round(fot * nr_pct / 100, 2)
write_data_row(ws, r, col2=nr_code, col8=nr_label,
col14="%", col16=nr_pct,
col20=nr_pct, col27=nr)
r += 1
sp = round(fot * sp_pct / 100, 2)
write_data_row(ws, r, col2=sp_code, col8=sp_label,
col14="%", col16=sp_pct,
col20=sp_pct, col27=sp)
r += 1
position_total = round(pz + nr + sp, 2)
per_unit_current = round(position_total / qty, 2) if qty else 0
write_data_row(ws, r, col8="Всего по позиции",
col25=per_unit_current, col27=position_total)
r += 1
# ========== FOOTER / GRAND TOTALS ==========
r += 1
footer_lines = [
("ВСЕГО строительные работы", grand.grand_total, True),
(" в том числе:", None, False),
(" всего прямые затраты", grand.grand_pz, False),
(" в том числе:", None, False),
(" оплата труда (ОТ)", grand.grand_ot, False),
(" эксплуатация машин и механизмов", grand.grand_em, False),
(" оплата труда машинистов (ОТм) ", grand.grand_otm, False),
(" материальные ресурсы", grand.grand_mat, False),
(" перевозка", grand.grand_transport, False),
(" всего ФОТ", grand.grand_fot, False),
(" всего накладные расходы", grand.grand_nr, False),
(" всего сметная прибыль", grand.grand_sp, False),
("ВСЕГО монтажные работы", 0, True),
(" в том числе:", None, False),
(" всего прямые затраты", 0, False),
(" в том числе:", None, False),
(" оплата труда (ОТ)", 0, False),
(" эксплуатация машин и механизмов", 0, False),
(" оплата труда машинистов (ОТм) ", 0, False),
(" материальные ресурсы", 0, False),
(" перевозка", 0, False),
(" всего ФОТ", 0, False),
(" всего накладные расходы", 0, False),
(" всего сметная прибыль", 0, False),
("ВСЕГО оборудование", 0, True),
("ВСЕГО прочие затраты", 0, True),
(" в том числе:", None, False),
(" прочие затраты", 0, False),
(" прочие работы", 0, False),
(" в том числе:", None, False),
(" всего прямые затраты", 0, False),
(" в том числе:", None, False),
(" оплата труда (ОТ)", 0, False),
(" эксплуатация машин и механизмов", 0, False),
(" оплата труда машинистов (ОТм) ", 0, False),
(" материальные ресурсы", 0, False),
(" перевозка", 0, False),
(" всего ФОТ", 0, False),
(" всего накладные расходы", 0, False),
(" всего сметная прибыль", 0, False),
("ВСЕГО по смете", grand.grand_total, True),
(" в том числе:", None, False),
(" Всего прямые затраты по смете", grand.grand_pz, False),
(" в том числе:", None, False),
(" оплата труда (ОТ)", grand.grand_ot, False),
(" эксплуатация машин и механизмов", grand.grand_em, False),
(" оплата труда машинистов (ОТм) ", grand.grand_otm, False),
(" материальные ресурсы", grand.grand_mat, False),
(" перевозка", grand.grand_transport, False),
(" Всего ФОТ", grand.grand_fot, False),
(" Всего накладные расходы", grand.grand_nr, False),
(" Всего сметная прибыль", grand.grand_sp, False),
(" Всего оборудование", 0, False),
(" Всего прочие затраты", 0, False),
]
for label, value, bold in footer_lines:
f = FONT_BOLD if bold else FONT
write_data_row(ws, r, col8=label,
col27=value if value is not None else "",
font=f, bold_27=bold)
r += 1
# Spravochno
write_data_row(ws, r, col8="Справочно", font=FONT)
r += 1
write_data_row(ws, r, col8=" материальные ресурсы, отсутствующие в ФРСН ",
col27=0, font=FONT)
r += 1
write_data_row(ws, r, col8=" оборудование, отсутствующее в ФРСН ",
col27=0, font=FONT)
r += 1
write_data_row(ws, r, col8=" затраты труда рабочих",
col20=f"{grand.grand_zt_hours:.6f}", font=FONT)
r += 1
write_data_row(ws, r, col8=" затраты труда машинистов",
col20=f"{grand.grand_ztm_hours:.7f}", font=FONT)
r += 1
# ========== Fill summary header cells ==========
total_thousands = round(grand.grand_total / 1000, 2)
ws.cell(total_cost_cell_row, 6).value = f"{total_thousands:.2f}"
ws.cell(total_cost_cell_row, 6).font = FONT
ot_thousands = round(grand.grand_ot / 1000, 2)
ws.cell(ot_summary_row, 21).value = ot_thousands
ws.cell(ot_summary_row, 21).font = FONT
otm_thousands = round(grand.grand_otm / 1000, 2)
ws.cell(otm_summary_row, 21).value = otm_thousands
ws.cell(otm_summary_row, 21).font = FONT
summary_base = ot_summary_row + 2
ws.cell(summary_base, 7).value = f"{total_thousands:.2f}"
ws.cell(summary_base, 7).font = FONT
ws.cell(summary_base + 1, 7).value = "0,00"
ws.cell(summary_base + 1, 7).font = FONT
ws.cell(summary_base + 2, 7).value = "0,00"
ws.cell(summary_base + 2, 7).font = FONT
ws.cell(summary_base + 3, 7).value = "0,00"
ws.cell(summary_base + 3, 7).font = FONT
ws.cell(summary_base, 21).value = round(grand.grand_zt_hours, 2)
ws.cell(summary_base, 21).font = FONT
ws.cell(summary_base + 1, 21).value = round(grand.grand_ztm_hours, 2)
ws.cell(summary_base + 1, 21).font = FONT
# Page setup
ws.sheet_properties.pageSetUpPr = PageSetupProperties(fitToPage=True)
ws.page_setup.orientation = "landscape"
ws.page_setup.fitToWidth = 1
ws.page_setup.fitToHeight = 0
wb.save(output_path)
print(f"\nSmeta saved: {output_path}")
print(f"Total rows: {r}, Items: {item_num}")
print(f"TOTAL: {grand.grand_total:,.2f} = {total_thousands:,.2f} тыс.руб.")
return output_path
View File
+70
View File
@@ -0,0 +1,70 @@
"""Tests for coefficient calculation."""
import pytest
from smeta_railway.calc.coefficients import get_coefficients
class TestCoefficients:
"""Test coefficient calculation for various norm codes."""
def test_full_coefficients_037(self):
"""28-01-037-02: all 3 coefficients applied."""
c = get_coefficients("ГЭСН 28-01-037-02")
assert c.zt == 1.60
assert c.em == pytest.approx(1.60 * 1.20 * 1.81, rel=1e-3)
assert c.ztm == pytest.approx(1.60 * 1.20 * 1.81, rel=1e-3)
assert set(c.applied) == {"dvizhenie", "vl", "okno"}
def test_full_coefficients_068(self):
"""28-01-068-07: all 3 coefficients (machine norm)."""
c = get_coefficients("ГЭСН 28-01-068-07")
assert c.zt == 1.60
assert c.em == pytest.approx(3.4752, rel=1e-3)
assert len(c.applied) == 3
def test_no_okno_155(self):
"""28-01-155-01: manual work, no okno coefficient."""
c = get_coefficients("ГЭСН 28-01-155-01")
assert c.zt == 1.60
assert c.em == pytest.approx(1.60 * 1.20, rel=1e-3)
assert c.ztm == pytest.approx(1.60 * 1.20, rel=1e-3)
assert "okno" not in c.applied
assert "dvizhenie" in c.applied
assert "vl" in c.applied
def test_no_okno_043(self):
"""28-01-043-01: rail cutting, no okno."""
c = get_coefficients("ГЭСН 28-01-043-01")
assert "okno" not in c.applied
assert c.em == pytest.approx(1.92, rel=1e-3)
def test_no_okno_044(self):
"""28-01-044-01: insulating joints, no okno."""
c = get_coefficients("ГЭСН 28-01-044-01")
assert "okno" not in c.applied
def test_earthwork_no_coefficients(self):
"""01-02-057-02: earthwork, no collection 28 coefficients."""
c = get_coefficients("ГЭСН 01-02-057-02")
assert c.zt == 1.0
assert c.em == 1.0
assert c.ztm == 1.0
assert c.applied == []
def test_formulas_display(self):
"""Check formula strings for display."""
c = get_coefficients("ГЭСН 28-01-037-02")
assert "1.60" in c.formulas["zt"]
assert "1.20" in c.formulas["em"]
assert "1.81" in c.formulas["em"]
def test_zt_only_dvizhenie(self):
"""ZT gets only dvizhenie (not vl, not okno)."""
c = get_coefficients("ГЭСН 28-01-037-02")
assert c.zt == 1.60 # only dvizhenie
def test_em_value(self):
"""EM = 1.60 * 1.20 * 1.81 = 3.4752."""
c = get_coefficients("ГЭСН 28-01-037-02")
assert c.em == pytest.approx(3.4752, rel=1e-4)
+195
View File
@@ -0,0 +1,195 @@
"""Tests for EstimateCalculator."""
import pytest
from smeta_railway.calc.estimate import EstimateCalculator
from smeta_railway.config import Section, Subsection, WorkItem
from smeta_railway.data.fgis import FGISLookup
from smeta_railway.models import (
LaborResource,
MachineResource,
MaterialResource,
NormResources,
)
def _make_fgis() -> FGISLookup:
"""Create a minimal FGIS lookup for testing."""
return FGISLookup(
index_map={
"91.09.03-031": 1.64,
"91.09.05-023": 1.64,
},
base_price_map={
"91.09.03-031": 3771.54,
"91.09.05-023": 2200.0,
},
current_price_map={},
labor_price_map={
"1-100-31": 550.0,
"4-100-060": 700.0,
},
)
def _make_resources() -> dict[str, NormResources]:
"""Create minimal resources for testing."""
return {
"28-01-031-01": NormResources(
norm_code="28-01-031-01",
norm_name="Выправка пути ВПО",
unit="км",
ozp=LaborResource(razryad=3.1, chel_hours=20.0),
machines=[
MachineResource(
code="91.09.03-031",
name="Платформы моторные",
unit="маш.-ч",
qty=5.0,
cost_base=3771.54,
razryad_mash=6.0,
),
],
materials=[],
),
}
class TestEstimateCalculator:
def test_single_gesn_position(self):
"""Test calculation of a single GESN position."""
fgis = _make_fgis()
resources = _make_resources()
calc = EstimateCalculator(fgis, resources)
sections = [
Section(
name="Test",
subsections=[
Subsection(items=[
WorkItem(
code="ГЭСН 28-01-031-01",
name="Выправка пути",
unit="км",
qty=2.0,
),
]),
],
),
]
result = calc.calculate(sections)
assert len(result.positions) == 1
pos = result.positions[0]
assert pos.gesn_code == "ГЭСН 28-01-031-01"
assert pos.qty == 2.0
assert pos.ot_cost > 0
assert pos.em_cost > 0
assert pos.pz > 0
assert pos.nr > 0
assert pos.sp > 0
assert pos.total > pos.pz
def test_transport_position(self):
"""Test transport position calculation."""
fgis = FGISLookup()
calc = EstimateCalculator(fgis, {})
sections = [
Section(
name="Transport",
subsections=[
Subsection(items=[
WorkItem(
code="ФССЦпг 236019-00-0071-0080",
name="Перевозка щебня",
unit="1 т груза",
qty=100,
),
]),
],
),
]
result = calc.calculate(sections)
assert len(result.positions) == 1
pos = result.positions[0]
assert pos.is_transport
assert pos.transport_cost == pytest.approx(100 * 815.96, rel=1e-3)
def test_kp_position(self):
"""Test commercial proposal position."""
fgis = FGISLookup()
calc = EstimateCalculator(fgis, {})
sections = [
Section(
name="KP",
subsections=[
Subsection(items=[
WorkItem(
code="КП РСП-19",
name="Сварка на РСП",
unit="стык",
qty=10,
),
]),
],
),
]
result = calc.calculate(sections)
pos = result.positions[0]
assert pos.is_kp
assert pos.pz == pytest.approx(10 * 8129.21, rel=1e-3)
def test_material_position_skipped(self):
"""Material positions have zero costs."""
fgis = FGISLookup()
calc = EstimateCalculator(fgis, {})
sections = [
Section(
name="Mat",
subsections=[
Subsection(items=[
WorkItem(
code="Материал",
name="Шпала Ш1",
unit="шт.",
qty=44,
),
]),
],
),
]
result = calc.calculate(sections)
pos = result.positions[0]
assert pos.is_material
assert pos.pz == 0
def test_grand_totals_accumulate(self):
"""Grand totals should accumulate across positions."""
fgis = FGISLookup()
calc = EstimateCalculator(fgis, {})
sections = [
Section(
name="Transport",
subsections=[
Subsection(items=[
WorkItem(code="ФССЦпг 236019-00-0071-0080",
name="A", unit="т", qty=100),
WorkItem(code="ФССЦпг 236019-00-0001-0005",
name="B", unit="т", qty=200),
]),
],
),
]
result = calc.calculate(sections)
expected = 100 * 815.96 + 200 * 731.17
assert result.grand_transport == pytest.approx(expected, rel=1e-3)
assert result.grand_pz == pytest.approx(expected, rel=1e-3)
+49
View File
@@ -0,0 +1,49 @@
"""Tests for FGIS lookup utilities."""
import pytest
from smeta_railway.data.fgis import FGISLookup, get_labor_code, get_labor_current_price
class TestLaborCode:
def test_razryad_30(self):
assert get_labor_code(3.0) == "1-100-30"
def test_razryad_31(self):
assert get_labor_code(3.1) == "1-100-31"
def test_razryad_50(self):
assert get_labor_code(5.0) == "1-100-50"
def test_machinist_50(self):
assert get_labor_code(5.0, "4-100-") == "4-100-050"
def test_machinist_60(self):
assert get_labor_code(6.0, "4-100-") == "4-100-060"
class TestLaborPrice:
def test_default_price(self):
"""Without FGIS data, returns default 545.28."""
fgis = FGISLookup()
price = get_labor_current_price(fgis, 3.0)
assert price == 545.28
def test_with_fgis_data(self):
fgis = FGISLookup(
labor_price_map={"1-100-30": 600.0}
)
price = get_labor_current_price(fgis, 3.0)
assert price == 600.0
class TestFGISLookup:
def test_get_index(self):
fgis = FGISLookup(index_map={"91.09.07-014": 1.64})
assert fgis.get_index("91.09.07-014") == 1.64
assert fgis.get_index("nonexistent") is None
def test_get_base_price(self):
fgis = FGISLookup(base_price_map={"91.09.07-014": 1000.0})
assert fgis.get_base_price("91.09.07-014") == 1000.0
assert fgis.get_base_price("nonexistent", 0) == 0
+35
View File
@@ -0,0 +1,35 @@
"""Tests for overhead calculation."""
import pytest
from smeta_railway.calc.overhead import calc_overhead, get_overhead_percents
class TestOverhead:
def test_railway_percents(self):
nr_pct, sp_pct, *_ = get_overhead_percents("ГЭСН 28-01-037-02")
assert nr_pct == 109
assert sp_pct == 65
def test_earthwork_percents(self):
nr_pct, sp_pct, *_ = get_overhead_percents("ГЭСН 01-02-057-02")
assert nr_pct == 92
assert sp_pct == 46
def test_calc_overhead(self):
fot = 100_000.0
nr, sp = calc_overhead(fot, 109, 65)
assert nr == 109_000.0
assert sp == 65_000.0
def test_calc_overhead_rounding(self):
fot = 12345.67
nr, sp = calc_overhead(fot, 109, 65)
assert nr == pytest.approx(13456.78, abs=0.01)
assert sp == pytest.approx(8024.69, abs=0.01)
def test_railway_labels(self):
_, _, nr_code, nr_label, sp_code, sp_label = get_overhead_percents("ГЭСН 28-01-031-01")
assert "812" in nr_code
assert "774" in sp_code
assert "Железные дороги" in nr_label