feat: генератор ССР — РАСПРЕДЕЛЕНИЕ + ССРСС из GGE-данных
Скрипт generate_ssr.py генерирует xlsx с двумя листами: - РАСПРЕДЕЛЕНИЕ: иерархия глава/раздел/ОС/ЛС, суммы Y-AC - ССРСС: главы 1-7 из GGE + расчётные главы 8-12 + резерв + НДС Расчётные позиции: временные (332/пр), зимнее (325/пр), стройконтроль (ПП468), авторский надзор (421/пр). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
# Промпт для продолжения работы над генератором ССР
|
||||
|
||||
Продолжай разработку генератора ССР (сводного сметного расчёта стоимости строительства).
|
||||
|
||||
## Контекст
|
||||
Прочитай файлы памяти проекта — там ВСЁ:
|
||||
- memory/project_ssr_generation.md — правила, структура шифров, зависимости, что автогенерируется
|
||||
- memory/project_raspredelenie.md — лист РАСПРЕДЕЛЕНИЕ, strikethrough = пропустить
|
||||
- memory/project_session_20260329.md — что уже сделано за прошлую сессию
|
||||
- memory/project_smeta_full_context.md — полный контекст проекта
|
||||
|
||||
## Что уже готово (Этап 1)
|
||||
- scripts/parse_gge_structure.py — парсер GGE → иерархия глава/раздел/ОС/ЛС + суммы по WorkType
|
||||
- data/user_files/project_data.json — результат парсинга 1673 смет (структурированный JSON)
|
||||
- scripts/fill_raspredelenie.py — заполнение/сверка РАСПРЕДЕЛЕНИЕ из GGE
|
||||
- scripts/verify_estimates.py — протокол сверки с Excel-выходом
|
||||
- Эталонный файл: data/user_files/Раздел ПД №9 Подраздел №1_СМ9.1.1_СМ1.ССР.СР1.xlsx (69 листов, 19MB)
|
||||
- Источники: data/user_files/source.zip (1911 GGE файлов, 60MB)
|
||||
|
||||
## Что нужно сделать (Этапы 2-5)
|
||||
|
||||
Этап 2: Генерация листа РАСПРЕДЕЛЕНИЕ из project_data.json
|
||||
- Создать xlsx с колонками: B (п/п), C (шифр), D (наименование), Y-AC (РИМ суммы)
|
||||
- Группировка по главам с заголовками "Глава N"
|
||||
- Итого по главам
|
||||
- Сверить результат с эталонным файлом
|
||||
|
||||
Этап 3: Генерация ССРСС (сводный сметный расчёт)
|
||||
- Позиции из РАСПРЕДЕЛЕНИЕ суммируются по главам
|
||||
- Колонки: стр.работы, монтаж, оборудование, прочие, всего
|
||||
- Итого по главам 1-7, 1-9, 1-12
|
||||
|
||||
Этап 4: Расчёт глав 7-12
|
||||
- Временные здания: % от СМР по 332/пр (данные в src/smeta_railway/data/temp_buildings.py)
|
||||
- Зимнее: % по 325/пр × коэф.зоны (данные в src/smeta_railway/data/winter_costs.py)
|
||||
- Стройконтроль: % по ПП468
|
||||
- НДС: 20%
|
||||
- Резерв: 2% (соц.) или 3% (произв.)
|
||||
|
||||
Этап 5: Сборка полного файла
|
||||
- Все листы в один xlsx
|
||||
- Формулы для связей между листами
|
||||
- Форматирование (шрифты, границы, ширина колонок)
|
||||
|
||||
## Ключевые правила (ОБЯЗАТЕЛЬНО)
|
||||
- Шифр сметы: ЛСР-XX-YY-Z-NNN-MM (этап-глава-раздел-ОС-номер)
|
||||
- Группа 2 (YY) = номер главы ССР (99% совпадение, проверено)
|
||||
- Группа 4 (NNN) = объектная смета (000=одиночная ЛС)
|
||||
- Префикс ЛС/ЛСР/ОС/ОСР игнорировать при сравнении
|
||||
- Зачёркнутый шрифт в колонке C = пропустить
|
||||
- GGE = источник правды для сумм
|
||||
- Суммы в GGE в рублях → делить на 1000 → тыс.руб в ССР
|
||||
- WorkType в секциях GGE: Строительные, Монтажные, Оборудование, Перевозка(→Прочие)
|
||||
- Кодировка ZIP: cp437→cp866
|
||||
|
||||
## Сервер
|
||||
- ssh server-mcp-user (192.168.87.76)
|
||||
- smeta-web: /home/mcp-user/smeta-web/
|
||||
- smeta-railway: /home/mcp-user/smeta-railway/
|
||||
- pip install -e smeta-railway (уже установлен)
|
||||
@@ -0,0 +1,374 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Заполнение листа РАСПРЕДЕЛЕНИЕ из GGE-файлов.
|
||||
|
||||
Читает GGE-файлы из ZIP, извлекает итоги по видам работ,
|
||||
заполняет колонки Y-AC (РИМ) в сводном xlsx.
|
||||
|
||||
Usage:
|
||||
python scripts/fill_raspredelenie.py source.zip summary.xlsx
|
||||
python scripts/fill_raspredelenie.py source.zip summary.xlsx --sheet "2266-04 РАСПРЕДЕЛЕНИЕ"
|
||||
python scripts/fill_raspredelenie.py source.zip summary.xlsx --dry-run # только протокол, без записи
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
|
||||
|
||||
def fix_zip_encoding(filename: str) -> str:
|
||||
for enc in ("utf-8", "cp866"):
|
||||
try:
|
||||
return filename.encode("cp437").decode(enc)
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
continue
|
||||
return filename
|
||||
|
||||
|
||||
def normalize_code(code: str) -> str:
|
||||
"""Normalize: extract only numeric part (XX-XX-X-XX-XX), ignore ЛС/ЛСР/ОС/ОСР prefix."""
|
||||
code = code.strip()
|
||||
# Remove prefix: ЛСР-, ЛС-, ОСР-, ОС-, Смета №
|
||||
code = re.sub(r"^(ЛСР|ЛС|ОСР|ОС|Смета\s*№?\s*)-?\s*", "", code)
|
||||
return code.strip()
|
||||
|
||||
|
||||
def parse_gge(content: bytes) -> dict | None:
|
||||
"""Parse GGE XML, return code + totals by work type."""
|
||||
try:
|
||||
root = ET.fromstring(content)
|
||||
except ET.ParseError:
|
||||
return None
|
||||
|
||||
est = root.find(".//Estimate")
|
||||
if est is None:
|
||||
return None
|
||||
|
||||
num_el = est.find("Num")
|
||||
name_el = est.find("Name")
|
||||
if num_el is None or not num_el.text:
|
||||
return None
|
||||
|
||||
code = num_el.text.strip()
|
||||
name = (name_el.text or "").strip()[:120]
|
||||
|
||||
# Collect totals by WorkType across all sections
|
||||
totals = {"Строительные": 0.0, "Монтажные": 0.0, "Оборудование": 0.0, "Прочие": 0.0}
|
||||
|
||||
for section in est.iter("Section"):
|
||||
# Determine WorkType for this section (from first Item)
|
||||
work_type = None
|
||||
items = section.find("Items")
|
||||
if items is not None:
|
||||
for item in items.findall("Item"):
|
||||
wt = item.find("WorkType")
|
||||
if wt is not None and wt.text:
|
||||
work_type = wt.text.strip()
|
||||
break
|
||||
|
||||
# Get section total
|
||||
sp = section.find("SectionPrice")
|
||||
if sp is not None:
|
||||
summary = sp.find("Summary")
|
||||
if summary is not None:
|
||||
total_el = summary.find("Total")
|
||||
if total_el is not None and total_el.text:
|
||||
total = float(total_el.text)
|
||||
if work_type in totals:
|
||||
totals[work_type] += total
|
||||
elif work_type == "Перевозка":
|
||||
totals["Прочие"] += total
|
||||
elif work_type:
|
||||
totals["Строительные"] += total # default
|
||||
else:
|
||||
totals["Строительные"] += total
|
||||
|
||||
grand_total = sum(totals.values())
|
||||
|
||||
# Fallback: if no sections found, use EstimatePrice/Total
|
||||
if grand_total == 0:
|
||||
for ep in est.iter("EstimatePrice"):
|
||||
t = ep.find("Total")
|
||||
if t is not None and t.text:
|
||||
grand_total = float(t.text)
|
||||
totals["Строительные"] = grand_total
|
||||
break
|
||||
|
||||
return {
|
||||
"code": code,
|
||||
"code_norm": normalize_code(code),
|
||||
"name": name,
|
||||
"str_rub": totals["Строительные"],
|
||||
"mont_rub": totals["Монтажные"],
|
||||
"equip_rub": totals["Оборудование"],
|
||||
"other_rub": totals["Прочие"],
|
||||
"total_rub": grand_total,
|
||||
# В тыс.руб
|
||||
"str_tys": totals["Строительные"] / 1000,
|
||||
"mont_tys": totals["Монтажные"] / 1000,
|
||||
"equip_tys": totals["Оборудование"] / 1000,
|
||||
"other_tys": totals["Прочие"] / 1000,
|
||||
"total_tys": grand_total / 1000,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Заполнение РАСПРЕДЕЛЕНИЕ из GGE")
|
||||
parser.add_argument("zip_file", help="ZIP с GGE-файлами")
|
||||
parser.add_argument("xlsx_file", help="Сводный XLSX")
|
||||
parser.add_argument("--sheet", default=None, help="Имя листа")
|
||||
parser.add_argument("--output", default=None, help="Выходной файл (по умолчанию: result_<исходный>.xlsx)")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Только протокол, без записи")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.exists(args.zip_file):
|
||||
print(f"ZIP not found: {args.zip_file}")
|
||||
sys.exit(1)
|
||||
if not os.path.exists(args.xlsx_file):
|
||||
print(f"XLSX not found: {args.xlsx_file}")
|
||||
sys.exit(1)
|
||||
|
||||
output = args.output or f"result_{Path(args.xlsx_file).name}"
|
||||
protocol = f"protocol_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
||||
|
||||
# 1. Parse all GGE files
|
||||
print("1. Parsing GGE files...")
|
||||
gge_by_code = {} # normalized_code → data
|
||||
with zipfile.ZipFile(args.zip_file) as z:
|
||||
gge_infos = [i for i in z.infolist() if i.filename.lower().endswith(".gge") and i.file_size > 100]
|
||||
for i, info in enumerate(gge_infos):
|
||||
if not (info.flag_bits & 0x800):
|
||||
info.filename = fix_zip_encoding(info.filename)
|
||||
content = z.read(info)
|
||||
parsed = parse_gge(content)
|
||||
if parsed:
|
||||
norm = parsed["code_norm"]
|
||||
if norm in gge_by_code:
|
||||
# Sum if duplicate code
|
||||
for key in ("str_tys", "mont_tys", "equip_tys", "other_tys", "total_tys"):
|
||||
gge_by_code[norm][key] += parsed[key]
|
||||
else:
|
||||
gge_by_code[norm] = parsed
|
||||
if (i + 1) % 300 == 0:
|
||||
print(f" {i + 1}/{len(gge_infos)}...")
|
||||
|
||||
print(f" Parsed: {len(gge_by_code)} unique codes")
|
||||
|
||||
# 2. Open XLSX and find sheet
|
||||
print("\n2. Opening XLSX...")
|
||||
if not args.dry_run:
|
||||
shutil.copy2(args.xlsx_file, output)
|
||||
wb = openpyxl.load_workbook(output)
|
||||
else:
|
||||
wb = openpyxl.load_workbook(args.xlsx_file, data_only=True)
|
||||
|
||||
# Find sheet
|
||||
if args.sheet:
|
||||
ws = wb[args.sheet]
|
||||
else:
|
||||
ws = None
|
||||
for name in wb.sheetnames:
|
||||
if "РАСПРЕДЕЛЕНИЕ" in name.upper():
|
||||
ws = wb[name]
|
||||
break
|
||||
if ws is None:
|
||||
print("Sheet not found")
|
||||
sys.exit(1)
|
||||
print(f" Sheet: {ws.title}")
|
||||
|
||||
# 3. Fill data
|
||||
print("\n3. Filling data...")
|
||||
stats = {}
|
||||
filled = 0
|
||||
skipped_strike = 0
|
||||
skipped_header = 0
|
||||
not_found = 0
|
||||
already_filled = 0
|
||||
log = []
|
||||
|
||||
for row in ws.iter_rows(min_row=9, max_row=ws.max_row):
|
||||
c_cell = row[2] # C
|
||||
if c_cell.value is None:
|
||||
continue
|
||||
|
||||
# Skip strikethrough
|
||||
if c_cell.font and c_cell.font.strikethrough:
|
||||
skipped_strike += 1
|
||||
continue
|
||||
|
||||
c_val = str(c_cell.value).strip()
|
||||
# Skip headers/totals
|
||||
if not c_val or c_val.isdigit():
|
||||
continue
|
||||
d_val = str(row[3].value or "")[:80]
|
||||
if d_val.startswith("Глава") or d_val.startswith("Итого") or "всего" in d_val.lower():
|
||||
skipped_header += 1
|
||||
continue
|
||||
|
||||
# Handle multi-line codes (take first)
|
||||
codes = [normalize_code(c) for c in c_val.split("\n") if c.strip()]
|
||||
if not codes:
|
||||
continue
|
||||
|
||||
# Try to find GGE match
|
||||
gge = None
|
||||
matched_code = None
|
||||
for code in codes:
|
||||
if code in gge_by_code:
|
||||
gge = gge_by_code[code]
|
||||
matched_code = code
|
||||
break
|
||||
|
||||
if not gge:
|
||||
not_found += 1
|
||||
log.append({
|
||||
"row": c_cell.row, "code": c_val[:30], "status": "Нет GGE",
|
||||
"y": None, "z": None, "aa": None, "ab": None, "ac": None,
|
||||
})
|
||||
continue
|
||||
|
||||
# Compare existing values with GGE (source of truth)
|
||||
gge_vals = {
|
||||
24: round(gge["str_tys"], 2) if gge["str_tys"] else 0, # Y
|
||||
25: round(gge["mont_tys"], 2) if gge["mont_tys"] else 0, # Z
|
||||
26: round(gge["equip_tys"], 2) if gge["equip_tys"] else 0, # AA
|
||||
27: round(gge["other_tys"], 2) if gge["other_tys"] else 0, # AB
|
||||
28: round(gge["total_tys"], 2), # AC
|
||||
}
|
||||
|
||||
# Check each cell: empty, correct, or wrong
|
||||
is_empty = True
|
||||
is_correct = True
|
||||
cell_diffs = {}
|
||||
for col_idx, gge_val in gge_vals.items():
|
||||
xlsx_val = row[col_idx].value
|
||||
if xlsx_val is not None and xlsx_val != "" and xlsx_val != 0:
|
||||
is_empty = False
|
||||
try:
|
||||
xlsx_num = float(xlsx_val)
|
||||
if abs(xlsx_num - gge_val) > 0.1: # tolerance 0.1 тыс.руб = 100 руб
|
||||
is_correct = False
|
||||
cell_diffs[col_idx] = {"xlsx": xlsx_num, "gge": gge_val, "diff": gge_val - xlsx_num}
|
||||
except (ValueError, TypeError):
|
||||
# Formula or text — skip overwriting
|
||||
pass
|
||||
|
||||
if is_empty:
|
||||
# Fill empty cells
|
||||
if not args.dry_run:
|
||||
for col_idx, gge_val in gge_vals.items():
|
||||
row[col_idx].value = gge_val if gge_val else None
|
||||
filled += 1
|
||||
log.append({
|
||||
"row": c_cell.row, "code": matched_code, "status": "Заполнено",
|
||||
"y": gge_vals[24], "z": gge_vals[25], "aa": gge_vals[26],
|
||||
"ab": gge_vals[27], "ac": gge_vals[28],
|
||||
})
|
||||
elif is_correct:
|
||||
already_filled += 1
|
||||
log.append({
|
||||
"row": c_cell.row, "code": matched_code, "status": "✓ Совпадает",
|
||||
"y": row[24].value, "z": row[25].value, "aa": row[26].value,
|
||||
"ab": row[27].value, "ac": row[28].value,
|
||||
"gge_y": gge_vals[24], "gge_z": gge_vals[25],
|
||||
"gge_aa": gge_vals[26], "gge_ab": gge_vals[27],
|
||||
"gge_ac": gge_vals[28],
|
||||
})
|
||||
else:
|
||||
# MISMATCH — overwrite with GGE values (source of truth)
|
||||
stats["mismatch"] = stats.get("mismatch", 0) + 1
|
||||
if not args.dry_run:
|
||||
for col_idx, gge_val in gge_vals.items():
|
||||
row[col_idx].value = gge_val if gge_val else None
|
||||
log.append({
|
||||
"row": c_cell.row, "code": matched_code, "status": "✗ ОШИБКА — исправлено",
|
||||
"y": row[24].value, "z": row[25].value, "aa": row[26].value,
|
||||
"ab": row[27].value, "ac": row[28].value,
|
||||
"gge_y": gge_vals[24], "gge_z": gge_vals[25],
|
||||
"gge_aa": gge_vals[26], "gge_ab": gge_vals[27],
|
||||
"gge_ac": gge_vals[28],
|
||||
"diffs": cell_diffs,
|
||||
})
|
||||
|
||||
filled += 1
|
||||
log.append({
|
||||
"row": c_cell.row, "code": matched_code, "status": "Заполнено",
|
||||
"y": round(gge["str_tys"], 2), "z": round(gge["mont_tys"], 2),
|
||||
"aa": round(gge["equip_tys"], 2), "ab": round(gge["other_tys"], 2),
|
||||
"ac": round(gge["total_tys"], 2),
|
||||
})
|
||||
|
||||
# 4. Save
|
||||
if not args.dry_run:
|
||||
wb.save(output)
|
||||
print(f"\n Result saved: {output}")
|
||||
wb.close()
|
||||
|
||||
# 5. Create protocol
|
||||
print(f"\n4. Creating protocol...")
|
||||
pwb = openpyxl.Workbook()
|
||||
pws = pwb.active
|
||||
pws.title = "Протокол"
|
||||
|
||||
headers = ["Строка", "Шифр", "Статус",
|
||||
"Y (стр.)", "Z (монт.)", "AA (обор.)", "AB (проч.)", "AC (всего)",
|
||||
"GGE стр.", "GGE монт.", "GGE обор.", "GGE проч.", "GGE всего"]
|
||||
for col, h in enumerate(headers, 1):
|
||||
cell = pws.cell(row=1, column=col, value=h)
|
||||
cell.font = Font(bold=True)
|
||||
|
||||
ok_fill = PatternFill("solid", fgColor="C6EFCE")
|
||||
warn_fill = PatternFill("solid", fgColor="FFEB9C")
|
||||
for i, entry in enumerate(log, 2):
|
||||
pws.cell(row=i, column=1, value=entry["row"])
|
||||
pws.cell(row=i, column=2, value=entry["code"])
|
||||
status_cell = pws.cell(row=i, column=3, value=entry["status"])
|
||||
status_cell.fill = ok_fill if entry["status"] == "Заполнено" else warn_fill
|
||||
for j, key in enumerate(["y", "z", "aa", "ab", "ac"], 4):
|
||||
pws.cell(row=i, column=j, value=entry.get(key))
|
||||
for j, key in enumerate(["gge_y", "gge_z", "gge_aa", "gge_ab", "gge_ac"], 9):
|
||||
pws.cell(row=i, column=j, value=entry.get(key))
|
||||
|
||||
# Summary sheet
|
||||
sws = pwb.create_sheet("Итоги")
|
||||
summary = [
|
||||
["Дата", datetime.now().strftime("%d.%m.%Y %H:%M")],
|
||||
["ZIP", args.zip_file],
|
||||
["XLSX", args.xlsx_file],
|
||||
["Лист", ws.title],
|
||||
["", ""],
|
||||
["Заполнено строк (новые)", filled],
|
||||
["Совпадает с GGE", already_filled],
|
||||
["ОШИБКИ (исправлено из GGE)", stats.get("mismatch", 0)],
|
||||
["Нет GGE файла", not_found],
|
||||
["Зачёркнуто (пропущено)", skipped_strike],
|
||||
["Заголовки/итого (пропущено)", skipped_header],
|
||||
["Режим", "DRY RUN" if args.dry_run else "ЗАПИСЬ"],
|
||||
]
|
||||
for r, (k, v) in enumerate(summary, 1):
|
||||
sws.cell(row=r, column=1, value=k)
|
||||
sws.cell(row=r, column=2, value=v)
|
||||
|
||||
pwb.save(protocol)
|
||||
print(f" Protocol saved: {protocol}")
|
||||
|
||||
print(f"\n=== ИТОГО ===")
|
||||
print(f" Заполнено (новые): {filled}")
|
||||
print(f" Совпадает с GGE: {already_filled}")
|
||||
print(f" ОШИБКИ исправлены: {stats.get('mismatch', 0)}")
|
||||
print(f" Нет GGE: {not_found}")
|
||||
print(f" Зачёркнуто: {skipped_strike}")
|
||||
print(f" Заголовки: {skipped_header}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,667 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generate SSR (Svodny Smetny Raschet) from project_data.json.
|
||||
|
||||
Produces xlsx with sheets:
|
||||
- РАСПРЕДЕЛЕНИЕ: all estimates grouped by chapter/section/OS
|
||||
- ССРСС: summary with chapters 1-12, totals, reserve, VAT
|
||||
|
||||
Usage:
|
||||
python scripts/generate_ssr.py data/user_files/project_data.json
|
||||
python scripts/generate_ssr.py data/user_files/project_data.json --output ssr.xlsx
|
||||
python scripts/generate_ssr.py data/user_files/project_data.json --temp-pct 6.2 --winter-pct 3.2
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
|
||||
# ── Styles ──────────────────────────────────────────────────────────────────
|
||||
|
||||
FONT_NORMAL = Font(name="Arial", size=10)
|
||||
FONT_BOLD = Font(name="Arial", size=10, bold=True)
|
||||
FONT_HEADER = Font(name="Arial", size=11, bold=True)
|
||||
FONT_TITLE = Font(name="Arial", size=12, bold=True)
|
||||
ALIGN_CENTER = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
ALIGN_LEFT = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
ALIGN_RIGHT = Alignment(horizontal="right", vertical="center")
|
||||
THIN_BORDER = Border(
|
||||
left=Side(style="thin"), right=Side(style="thin"),
|
||||
top=Side(style="thin"), bottom=Side(style="thin"),
|
||||
)
|
||||
FILL_HEADER = PatternFill("solid", fgColor="D9E1F2")
|
||||
FILL_TOTAL = PatternFill("solid", fgColor="E2EFDA")
|
||||
NUM_FMT = '#,##0.00'
|
||||
|
||||
CHAPTER_NAMES = {
|
||||
1: "Подготовка территории строительства, реконструкции, капитального ремонта",
|
||||
2: "Основные объекты строительства, реконструкции, капитального ремонта",
|
||||
3: "Объекты подсобного и обслуживающего назначения",
|
||||
4: "Объекты энергетического хозяйства",
|
||||
5: "Объекты транспортного хозяйства и связи",
|
||||
6: "Наружные сети и сооружения водоснабжения, водоотведения, теплоснабжения",
|
||||
7: "Благоустройство и озеленение территории",
|
||||
8: "Временные здания и сооружения",
|
||||
9: "Прочие работы и затраты",
|
||||
10: "Содержание службы заказчика. Строительный контроль",
|
||||
12: "Публичный технологический и ценовой аудит, подготовка обоснования инвестиций, проектные и изыскательские работы",
|
||||
}
|
||||
|
||||
SECTION_NAMES = {
|
||||
(2, 2): "Земляное полотно железнодорожных путей",
|
||||
(2, 3): "Искусственные сооружения на железнодорожных путях",
|
||||
(2, 4): "Верхнее строение пути",
|
||||
(2, 5): "Железнодорожная автоматика и телемеханика",
|
||||
(2, 6): "Железнодорожная связь",
|
||||
(2, 7): "Электрификация и электроснабжение",
|
||||
(5, 1): "Автомобильные дороги",
|
||||
(5, 2): "Связь и телекоммуникации",
|
||||
(6, 1): "Водоснабжение и водоотведение",
|
||||
(6, 2): "Дождевая канализация",
|
||||
}
|
||||
|
||||
|
||||
def _write_val(ws, row, col, value, font=FONT_NORMAL, num_fmt=None):
|
||||
"""Write value with style."""
|
||||
cell = ws.cell(row=row, column=col, value=value)
|
||||
cell.font = font
|
||||
cell.border = THIN_BORDER
|
||||
if num_fmt and isinstance(value, (int, float)):
|
||||
cell.number_format = num_fmt
|
||||
return cell
|
||||
|
||||
|
||||
# ── РАСПРЕДЕЛЕНИЕ ──────────────────────────────────────────────────────────
|
||||
|
||||
def _build_raspredelenie(wb, data):
|
||||
"""Build РАСПРЕДЕЛЕНИЕ sheet. Returns chapter totals dict."""
|
||||
ws = wb.create_sheet("РАСПРЕДЕЛЕНИЕ")
|
||||
|
||||
# Headers
|
||||
ws.merge_cells("A1:AC1")
|
||||
ws.cell(row=1, column=1, value=data.get("title", "Сводный сметный расчёт"))
|
||||
ws.cell(row=1, column=1).font = FONT_TITLE
|
||||
|
||||
# Column headers row 6-7
|
||||
headers_6 = {2: "№ п/п", 3: "Обоснование", 4: "Наименование"}
|
||||
for col, val in headers_6.items():
|
||||
ws.cell(row=6, column=col, value=val).font = FONT_BOLD
|
||||
|
||||
ws.merge_cells("Y6:AC6")
|
||||
ws.cell(row=6, column=25, value="Сметная стоимость, тыс. руб.\nресурсно-индексный метод")
|
||||
ws.cell(row=6, column=25).font = FONT_BOLD
|
||||
ws.cell(row=6, column=25).alignment = ALIGN_CENTER
|
||||
|
||||
sub_headers = {25: "строительных\nработ", 26: "монтажных\nработ",
|
||||
27: "оборудования", 28: "прочих\nзатрат", 29: "всего"}
|
||||
for col, val in sub_headers.items():
|
||||
c = ws.cell(row=7, column=col, value=val)
|
||||
c.font = FONT_BOLD
|
||||
c.alignment = ALIGN_CENTER
|
||||
c.fill = FILL_HEADER
|
||||
c.border = THIN_BORDER
|
||||
|
||||
# Row 8: column numbers
|
||||
for col, num in {1: 1, 2: 1, 3: 2, 4: 3, 25: 4, 26: 5, 27: 6, 28: 7, 29: 8}.items():
|
||||
ws.cell(row=8, column=col, value=num).font = FONT_BOLD
|
||||
|
||||
row = 9
|
||||
item_num = 0
|
||||
chapters = data["chapters"]
|
||||
chapter_totals = {} # ch_num → {str, mont, equip, other, total}
|
||||
|
||||
for ch_num in sorted(chapters.keys(), key=int):
|
||||
ch = chapters[ch_num]
|
||||
ch_int = int(ch_num)
|
||||
ch_name = CHAPTER_NAMES.get(ch_int, ch["name"])
|
||||
|
||||
# Chapter header
|
||||
ws.cell(row=row, column=4, value=f"Глава {ch_num}.\n{ch_name}").font = FONT_HEADER
|
||||
row += 1
|
||||
|
||||
ch_str = ch_mont = ch_equip = ch_other = ch_total = 0.0
|
||||
sections = ch["sections"]
|
||||
|
||||
for sec_num in sorted(sections.keys(), key=int):
|
||||
sec = sections[sec_num]
|
||||
sec_int = int(sec_num)
|
||||
|
||||
# Section header (only if chapter has >1 section)
|
||||
if len(sections) > 1:
|
||||
sec_name = SECTION_NAMES.get((ch_int, sec_int), f"Раздел {sec_num}")
|
||||
ws.cell(row=row, column=4, value=f"Раздел {sec_num}. {sec_name}").font = FONT_BOLD
|
||||
row += 1
|
||||
|
||||
sec_str = sec_mont = sec_equip = sec_other = sec_total = 0.0
|
||||
|
||||
for os_num in sorted(sec["os_groups"].keys(), key=lambda x: int(x)):
|
||||
os_data = sec["os_groups"][os_num]
|
||||
estimates = os_data["estimates"]
|
||||
os_int = int(os_num)
|
||||
|
||||
if os_int > 0 and len(estimates) > 1:
|
||||
# ОС group: header + sub-lines
|
||||
item_num += 1
|
||||
os_totals = os_data["totals_tys"]
|
||||
s = os_totals["Строительные"]
|
||||
m = os_totals["Монтажные"]
|
||||
e = os_totals["Оборудование"]
|
||||
o = os_totals["Прочие"]
|
||||
t = s + m + e + o
|
||||
|
||||
# Build OS code from first estimate
|
||||
first_code = estimates[0]["code"]
|
||||
# ЛСР-04-01-0-03-01 → ОС-04-01-0-03
|
||||
parts = first_code.split("-")
|
||||
if len(parts) >= 5:
|
||||
os_code = f"ОС-{parts[1]}-{parts[2]}-{parts[3]}-{parts[4]}"
|
||||
else:
|
||||
os_code = f"ОС-{os_num}"
|
||||
|
||||
first_name = estimates[0].get("name", "")
|
||||
# Try to get a generic name from first estimate
|
||||
os_name = first_name.split(".")[0] if "." in first_name else first_name
|
||||
|
||||
_write_val(ws, row, 2, item_num, FONT_BOLD)
|
||||
_write_val(ws, row, 3, os_code, FONT_BOLD)
|
||||
_write_val(ws, row, 4, os_name[:100], FONT_BOLD)
|
||||
_write_val(ws, row, 25, round(s, 2), FONT_BOLD, NUM_FMT)
|
||||
_write_val(ws, row, 26, round(m, 2), FONT_BOLD, NUM_FMT)
|
||||
_write_val(ws, row, 27, round(e, 2), FONT_BOLD, NUM_FMT)
|
||||
_write_val(ws, row, 28, round(o, 2), FONT_BOLD, NUM_FMT)
|
||||
_write_val(ws, row, 29, round(t, 2), FONT_BOLD, NUM_FMT)
|
||||
row += 1
|
||||
|
||||
# Sub-lines for each LS
|
||||
for i, est in enumerate(estimates, 1):
|
||||
sub_num = f"{item_num}.{i}"
|
||||
et = est["totals_tys"]
|
||||
es = et["Строительные"]
|
||||
em = et["Монтажные"]
|
||||
ee = et["Оборудование"]
|
||||
eo = et["Прочие"]
|
||||
etotal = est["grand_total_tys"]
|
||||
|
||||
_write_val(ws, row, 2, sub_num)
|
||||
_write_val(ws, row, 3, est["code"])
|
||||
_write_val(ws, row, 4, est["name"][:100])
|
||||
_write_val(ws, row, 25, round(es, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 26, round(em, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 27, round(ee, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 28, round(eo, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 29, round(etotal, 2), num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
sec_str += s; sec_mont += m; sec_equip += e
|
||||
sec_other += o; sec_total += t
|
||||
|
||||
else:
|
||||
# Single LS (os_num=0) or OS with 1 estimate
|
||||
for est in estimates:
|
||||
item_num += 1
|
||||
et = est["totals_tys"]
|
||||
es = et["Строительные"]
|
||||
em = et["Монтажные"]
|
||||
ee = et["Оборудование"]
|
||||
eo = et["Прочие"]
|
||||
etotal = est["grand_total_tys"]
|
||||
|
||||
_write_val(ws, row, 2, item_num)
|
||||
_write_val(ws, row, 3, est["code"])
|
||||
_write_val(ws, row, 4, est["name"][:100])
|
||||
_write_val(ws, row, 25, round(es, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 26, round(em, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 27, round(ee, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 28, round(eo, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 29, round(etotal, 2), num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
sec_str += es; sec_mont += em; sec_equip += ee
|
||||
sec_other += eo; sec_total += etotal
|
||||
|
||||
# Section total (if multiple sections)
|
||||
if len(sections) > 1:
|
||||
ws.cell(row=row, column=4, value=f"Итого по разделу {sec_num}").font = FONT_BOLD
|
||||
for col, val in [(25, sec_str), (26, sec_mont), (27, sec_equip),
|
||||
(28, sec_other), (29, sec_total)]:
|
||||
c = _write_val(ws, row, col, round(val, 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
ch_str += sec_str; ch_mont += sec_mont; ch_equip += sec_equip
|
||||
ch_other += sec_other; ch_total += sec_total
|
||||
|
||||
# Chapter total
|
||||
ws.cell(row=row, column=4, value=f"Итого по главе {ch_num}").font = FONT_BOLD
|
||||
for col, val in [(25, ch_str), (26, ch_mont), (27, ch_equip),
|
||||
(28, ch_other), (29, ch_total)]:
|
||||
c = _write_val(ws, row, col, round(val, 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
row += 1 # empty line
|
||||
|
||||
chapter_totals[ch_int] = {
|
||||
"str": ch_str, "mont": ch_mont, "equip": ch_equip,
|
||||
"other": ch_other, "total": ch_total,
|
||||
}
|
||||
|
||||
# Column widths
|
||||
ws.column_dimensions["B"].width = 8
|
||||
ws.column_dimensions["C"].width = 25
|
||||
ws.column_dimensions["D"].width = 55
|
||||
for col_letter in ["Y", "Z", "AA", "AB", "AC"]:
|
||||
ws.column_dimensions[col_letter].width = 16
|
||||
|
||||
return chapter_totals
|
||||
|
||||
|
||||
# ── ССРСС ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def _build_ssrss(wb, data, chapter_totals, temp_pct, winter_pct,
|
||||
control_pct, reserve_pct, avt_nadzor_pct):
|
||||
"""Build ССРСС sheet with chapters 1-12 + calculated items."""
|
||||
ws = wb.create_sheet("ССРСС")
|
||||
|
||||
# Title block
|
||||
ws.merge_cells("B5:C5")
|
||||
ws.cell(row=5, column=2, value="Сводный сметный расчёт стоимости строительства").font = FONT_TITLE
|
||||
|
||||
ws.merge_cells("B9:C9")
|
||||
ws.cell(row=9, column=2,
|
||||
value="Сводный сметный расчёт стоимости строительства №ССРСС").font = FONT_BOLD
|
||||
|
||||
ws.merge_cells("A10:H10")
|
||||
ws.cell(row=10, column=1, value=data.get("title", "")).font = FONT_NORMAL
|
||||
|
||||
# Column headers row 14-16
|
||||
h14 = {1: "№\nп/п", 2: "Обоснование", 3: "Наименование глав, объектов\nкапитального строительства",
|
||||
4: "Сметная стоимость, тыс.руб"}
|
||||
for col, val in h14.items():
|
||||
c = ws.cell(row=14, column=col, value=val)
|
||||
c.font = FONT_BOLD
|
||||
c.alignment = ALIGN_CENTER
|
||||
c.fill = FILL_HEADER
|
||||
c.border = THIN_BORDER
|
||||
|
||||
ws.merge_cells("D14:H14")
|
||||
|
||||
h15 = {4: "строитель-\nных работ", 5: "монтажных\nработ",
|
||||
6: "оборудо-\nвания", 7: "прочих\nзатрат", 8: "Всего"}
|
||||
for col, val in h15.items():
|
||||
c = ws.cell(row=15, column=col, value=val)
|
||||
c.font = FONT_BOLD
|
||||
c.alignment = ALIGN_CENTER
|
||||
c.fill = FILL_HEADER
|
||||
c.border = THIN_BORDER
|
||||
|
||||
for col, num in enumerate(range(1, 9), 1):
|
||||
ws.cell(row=16, column=col, value=num).font = FONT_BOLD
|
||||
|
||||
row = 17
|
||||
item_num = 0
|
||||
chapters = data["chapters"]
|
||||
|
||||
# Accumulate totals for milestones
|
||||
t17 = {"str": 0, "mont": 0, "equip": 0, "other": 0, "total": 0}
|
||||
|
||||
# Only chapters 1-7 in main loop (chapter 9 handled separately below)
|
||||
ch_17_keys = [k for k in chapters.keys() if int(k) <= 7]
|
||||
for ch_num in sorted(ch_17_keys, key=int):
|
||||
ch = chapters[ch_num]
|
||||
ch_int = int(ch_num)
|
||||
ch_name = CHAPTER_NAMES.get(ch_int, ch["name"])
|
||||
|
||||
# Chapter header
|
||||
ws.cell(row=row, column=3, value=f"Глава {ch_num}. {ch_name}").font = FONT_HEADER
|
||||
row += 1
|
||||
|
||||
sections = ch["sections"]
|
||||
for sec_num in sorted(sections.keys(), key=int):
|
||||
sec = sections[sec_num]
|
||||
sec_int = int(sec_num)
|
||||
|
||||
if len(sections) > 1:
|
||||
sec_name = SECTION_NAMES.get((ch_int, sec_int), f"Раздел {sec_num}")
|
||||
ws.cell(row=row, column=2, value=f"Раздел {sec_num}. {sec_name}").font = FONT_BOLD
|
||||
row += 1
|
||||
|
||||
sec_sums = [0.0, 0.0, 0.0, 0.0, 0.0] # str,mont,equip,other,total
|
||||
|
||||
for os_num in sorted(sec["os_groups"].keys(), key=lambda x: int(x)):
|
||||
os_data = sec["os_groups"][os_num]
|
||||
estimates = os_data["estimates"]
|
||||
os_int = int(os_num)
|
||||
|
||||
if os_int > 0 and len(estimates) > 1:
|
||||
# ОС line (aggregated)
|
||||
item_num += 1
|
||||
ot = os_data["totals_tys"]
|
||||
s = ot["Строительные"]; m = ot["Монтажные"]
|
||||
e = ot["Оборудование"]; o = ot["Прочие"]
|
||||
t = s + m + e + o
|
||||
|
||||
first_code = estimates[0]["code"]
|
||||
parts = first_code.split("-")
|
||||
if len(parts) >= 5:
|
||||
os_code = f"ОСР-{parts[1]}-{parts[2]}-{parts[3]}-{parts[4]}"
|
||||
else:
|
||||
os_code = f"ОС-{os_num}"
|
||||
|
||||
_write_val(ws, row, 1, item_num)
|
||||
_write_val(ws, row, 2, os_code)
|
||||
_write_val(ws, row, 3, estimates[0]["name"][:80])
|
||||
_write_val(ws, row, 4, round(s, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 5, round(m, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 6, round(e, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 7, round(o, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 8, round(t, 2), num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
sec_sums[0] += s; sec_sums[1] += m; sec_sums[2] += e
|
||||
sec_sums[3] += o; sec_sums[4] += t
|
||||
else:
|
||||
for est in estimates:
|
||||
item_num += 1
|
||||
et = est["totals_tys"]
|
||||
es = et["Строительные"]; em = et["Монтажные"]
|
||||
ee = et["Оборудование"]; eo = et["Прочие"]
|
||||
etotal = est["grand_total_tys"]
|
||||
|
||||
_write_val(ws, row, 1, item_num)
|
||||
_write_val(ws, row, 2, est["code"])
|
||||
_write_val(ws, row, 3, est["name"][:80])
|
||||
_write_val(ws, row, 4, round(es, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 5, round(em, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 6, round(ee, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 7, round(eo, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 8, round(etotal, 2), num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
sec_sums[0] += es; sec_sums[1] += em; sec_sums[2] += ee
|
||||
sec_sums[3] += eo; sec_sums[4] += etotal
|
||||
|
||||
# Section total
|
||||
if len(sections) > 1:
|
||||
ws.cell(row=row, column=2, value=f"Итого по разделу {sec_num}").font = FONT_BOLD
|
||||
for col, val in zip([4, 5, 6, 7, 8], sec_sums):
|
||||
c = _write_val(ws, row, col, round(val, 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# Chapter total
|
||||
ct = chapter_totals[ch_int]
|
||||
ws.cell(row=row, column=3, value=f"Итого по главе {ch_num}").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(ct[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
for key in ("str", "mont", "equip", "other", "total"):
|
||||
t17[key] += ct[key]
|
||||
|
||||
# ── Итого по главам 1-7 ──
|
||||
label_17 = "Итого по главам 1-7"
|
||||
ws.cell(row=row, column=3, value=label_17).font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(t17[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
smr_17 = t17["str"] + t17["mont"] # СМР = стр. + монт.
|
||||
|
||||
# ── Глава 8: Временные здания ──
|
||||
ws.cell(row=row, column=3, value=f"Глава 8. {CHAPTER_NAMES[8]}").font = FONT_HEADER
|
||||
row += 1
|
||||
item_num += 1
|
||||
|
||||
temp_str = round(t17["str"] * temp_pct / 100, 2)
|
||||
temp_mont = round(t17["mont"] * temp_pct / 100, 2)
|
||||
temp_total = temp_str + temp_mont
|
||||
_write_val(ws, row, 1, item_num)
|
||||
_write_val(ws, row, 2, "СР-10")
|
||||
_write_val(ws, row, 3,
|
||||
f"Временные здания и сооружения по нормам\n"
|
||||
f"(приказ Минстроя России №332/пр) — {temp_pct}%")
|
||||
_write_val(ws, row, 4, temp_str, num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 5, temp_mont, num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 8, temp_total, num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
ch8 = {"str": temp_str, "mont": temp_mont, "equip": 0, "other": 0, "total": temp_total}
|
||||
|
||||
ws.cell(row=row, column=3, value="Итого по главе 8").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(ch8[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# Итого 1-8
|
||||
t18 = {k: t17[k] + ch8[k] for k in t17}
|
||||
ws.cell(row=row, column=3, value=f"Итого по главам 1-8").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(t18[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# ── Глава 9: Прочие работы ──
|
||||
ws.cell(row=row, column=3, value=f"Глава 9. {CHAPTER_NAMES[9]}").font = FONT_HEADER
|
||||
row += 1
|
||||
|
||||
ch9 = {"str": 0, "mont": 0, "equip": 0, "other": 0, "total": 0}
|
||||
|
||||
# Зимнее удорожание
|
||||
item_num += 1
|
||||
winter_str = round(smr_17 * winter_pct / 100, 2) # % от СМР глав 1-7
|
||||
_write_val(ws, row, 1, item_num)
|
||||
_write_val(ws, row, 2, "СР-12")
|
||||
_write_val(ws, row, 3,
|
||||
f"Дополнительные затраты при производстве СМР\n"
|
||||
f"в зимнее время — {winter_pct}% от СМР")
|
||||
_write_val(ws, row, 4, winter_str, num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 8, winter_str, num_fmt=NUM_FMT)
|
||||
ch9["str"] += winter_str; ch9["total"] += winter_str
|
||||
row += 1
|
||||
|
||||
# Chapter 9 estimates from GGE (if any)
|
||||
if "9" in chapters:
|
||||
ch9_gge = chapter_totals.get(9, {})
|
||||
if ch9_gge:
|
||||
for sec_num in sorted(chapters["9"]["sections"].keys(), key=int):
|
||||
sec = chapters["9"]["sections"][sec_num]
|
||||
for os_num in sorted(sec["os_groups"].keys(), key=lambda x: int(x)):
|
||||
os_data = sec["os_groups"][os_num]
|
||||
for est in os_data["estimates"]:
|
||||
item_num += 1
|
||||
et = est["totals_tys"]
|
||||
es = et["Строительные"]; em = et["Монтажные"]
|
||||
ee = et["Оборудование"]; eo = et["Прочие"]
|
||||
etotal = est["grand_total_tys"]
|
||||
|
||||
_write_val(ws, row, 1, item_num)
|
||||
_write_val(ws, row, 2, est["code"])
|
||||
_write_val(ws, row, 3, est["name"][:80])
|
||||
_write_val(ws, row, 4, round(es, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 5, round(em, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 6, round(ee, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 7, round(eo, 2), num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 8, round(etotal, 2), num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
ch9["str"] += es; ch9["mont"] += em; ch9["equip"] += ee
|
||||
ch9["other"] += eo; ch9["total"] += etotal
|
||||
|
||||
ws.cell(row=row, column=3, value="Итого по главе 9").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(ch9[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# Итого 1-9
|
||||
t19 = {k: t18[k] + ch9[k] for k in t18}
|
||||
ws.cell(row=row, column=3, value="Итого по главам 1-9").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(t19[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# ── Глава 10: Стройконтроль ──
|
||||
ws.cell(row=row, column=3, value=f"Глава 10. {CHAPTER_NAMES[10]}").font = FONT_HEADER
|
||||
row += 1
|
||||
item_num += 1
|
||||
|
||||
sk_val = round(t19["total"] * control_pct / 100, 2)
|
||||
_write_val(ws, row, 1, item_num)
|
||||
_write_val(ws, row, 2, "СР-25\nПП РФ №468")
|
||||
_write_val(ws, row, 3,
|
||||
f"Строительный контроль — {control_pct}%\n"
|
||||
f"{t19['total']:,.2f}тыс.руб.*{control_pct}%")
|
||||
_write_val(ws, row, 7, sk_val, num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 8, sk_val, num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
ch10 = {"str": 0, "mont": 0, "equip": 0, "other": sk_val, "total": sk_val}
|
||||
ws.cell(row=row, column=3, value="Итого по главе 10").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(ch10[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# ── Глава 12: ПИР ──
|
||||
ws.cell(row=row, column=3, value=f"Глава 12. {CHAPTER_NAMES[12]}").font = FONT_HEADER
|
||||
row += 1
|
||||
|
||||
# Авторский надзор
|
||||
item_num += 1
|
||||
avt = round(t19["total"] * avt_nadzor_pct / 100, 2)
|
||||
_write_val(ws, row, 1, item_num)
|
||||
_write_val(ws, row, 2, "Методика\n(приказ №421/пр)\nп.173")
|
||||
_write_val(ws, row, 3,
|
||||
f"Авторский надзор — {avt_nadzor_pct}% от итого глав 1-9\n"
|
||||
f"{t19['total']:,.2f}тыс.руб.*{avt_nadzor_pct}%")
|
||||
_write_val(ws, row, 7, avt, num_fmt=NUM_FMT)
|
||||
_write_val(ws, row, 8, avt, num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
ch12 = {"str": 0, "mont": 0, "equip": 0, "other": avt, "total": avt}
|
||||
ws.cell(row=row, column=3, value="Итого по главе 12").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(ch12[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# ── Итого 1-12 ──
|
||||
t112 = {k: t19[k] + ch10[k] + ch12[k] for k in t19}
|
||||
ws.cell(row=row, column=3, value="Итого по главам 1-12").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, round(t112[key], 2), FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# ── Резерв ──
|
||||
item_num += 1
|
||||
res_vals = {k: round(t112[k] * reserve_pct / 100, 2) for k in t112}
|
||||
_write_val(ws, row, 1, item_num)
|
||||
_write_val(ws, row, 2, "Методика\n(приказ №421/пр)\nп.179")
|
||||
_write_val(ws, row, 3,
|
||||
f"Резерв средств на непредвиденные работы и затраты — {reserve_pct}%")
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
_write_val(ws, row, col, res_vals[key], num_fmt=NUM_FMT)
|
||||
row += 1
|
||||
|
||||
# ── Всего без НДС ──
|
||||
total_no_vat = {k: round(t112[k] + res_vals[k], 2) for k in t112}
|
||||
ws.cell(row=row, column=3, value="Всего по сводному сметному расчёту").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, total_no_vat[key], FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# ── НДС ──
|
||||
row += 1 # empty
|
||||
vat_vals = {k: round(total_no_vat[k] * 0.2, 2) for k in total_no_vat}
|
||||
ws.cell(row=row, column=3, value="НДС 20%").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
_write_val(ws, row, col, vat_vals[key], FONT_BOLD, NUM_FMT)
|
||||
row += 1
|
||||
|
||||
# ── Всего с НДС ──
|
||||
total_vat = {k: round(total_no_vat[k] + vat_vals[k], 2) for k in total_no_vat}
|
||||
ws.cell(row=row, column=3,
|
||||
value="Всего по сводному сметному расчёту с НДС").font = FONT_BOLD
|
||||
for col, key in [(4, "str"), (5, "mont"), (6, "equip"), (7, "other"), (8, "total")]:
|
||||
c = _write_val(ws, row, col, total_vat[key], FONT_BOLD, NUM_FMT)
|
||||
c.fill = FILL_TOTAL
|
||||
row += 1
|
||||
|
||||
# Column widths
|
||||
ws.column_dimensions["A"].width = 6
|
||||
ws.column_dimensions["B"].width = 25
|
||||
ws.column_dimensions["C"].width = 60
|
||||
for letter in ["D", "E", "F", "G", "H"]:
|
||||
ws.column_dimensions[letter].width = 18
|
||||
|
||||
return total_vat
|
||||
|
||||
|
||||
# ── Main ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Generate SSR from project_data.json")
|
||||
parser.add_argument("json_file", help="project_data.json")
|
||||
parser.add_argument("--output", default="ssr_generated.xlsx", help="Output xlsx")
|
||||
parser.add_argument("--title", default=None, help="Project title")
|
||||
parser.add_argument("--temp-pct", type=float, default=6.2,
|
||||
help="Temporary buildings %% (332/пр), default 6.2")
|
||||
parser.add_argument("--winter-pct", type=float, default=3.2,
|
||||
help="Winter costs %% (325/пр), default 3.2")
|
||||
parser.add_argument("--control-pct", type=float, default=0.55,
|
||||
help="Construction control %% (ПП468), default 0.55")
|
||||
parser.add_argument("--reserve-pct", type=float, default=1.0,
|
||||
help="Reserve %%, default 1.0")
|
||||
parser.add_argument("--avt-nadzor-pct", type=float, default=0.1,
|
||||
help="Авторский надзор %%, default 0.1")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not Path(args.json_file).exists():
|
||||
print(f"File not found: {args.json_file}")
|
||||
sys.exit(1)
|
||||
|
||||
with open(args.json_file, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
if args.title:
|
||||
data["title"] = args.title
|
||||
|
||||
print(f"Estimates: {data['total_estimates']}, Chapters: {sorted(data['chapters'].keys())}")
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
wb.remove(wb.active) # remove default sheet
|
||||
|
||||
# Sheet 1: РАСПРЕДЕЛЕНИЕ
|
||||
print("Building РАСПРЕДЕЛЕНИЕ...")
|
||||
chapter_totals = _build_raspredelenie(wb, data)
|
||||
|
||||
for ch_num in sorted(chapter_totals.keys()):
|
||||
ct = chapter_totals[ch_num]
|
||||
print(f" Глава {ch_num}: стр={ct['str']:,.2f} монт={ct['mont']:,.2f} "
|
||||
f"обор={ct['equip']:,.2f} проч={ct['other']:,.2f} итого={ct['total']:,.2f}")
|
||||
|
||||
# Sheet 2: ССРСС
|
||||
print("Building ССРСС...")
|
||||
total = _build_ssrss(wb, data, chapter_totals,
|
||||
temp_pct=args.temp_pct, winter_pct=args.winter_pct,
|
||||
control_pct=args.control_pct, reserve_pct=args.reserve_pct,
|
||||
avt_nadzor_pct=args.avt_nadzor_pct)
|
||||
|
||||
print(f"\nВсего с НДС: {total['total']:,.2f} тыс.руб.")
|
||||
|
||||
wb.save(args.output)
|
||||
print(f"Saved: {args.output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,300 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Parse GGE files from ZIP → structured project data for SSR generation.
|
||||
|
||||
Extracts from each GGE:
|
||||
- Estimate code (5 groups: etap-glava-razdel-os-num)
|
||||
- Name
|
||||
- Totals by WorkType (строительные, монтажные, оборудование, прочие)
|
||||
- Groups into chapters/sections/OS hierarchy
|
||||
|
||||
Usage:
|
||||
python scripts/parse_gge_structure.py source.zip
|
||||
python scripts/parse_gge_structure.py source.zip --output project_data.json
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def fix_zip_encoding(filename: str) -> str:
|
||||
for enc in ("utf-8", "cp866"):
|
||||
try:
|
||||
return filename.encode("cp437").decode(enc)
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
continue
|
||||
return filename
|
||||
|
||||
|
||||
def parse_code(code: str) -> dict | None:
|
||||
"""Parse estimate code into 5 groups."""
|
||||
# Remove prefix
|
||||
clean = re.sub(r"^(ЛСР|ЛС|ОСР|ОС)-", "", code.strip())
|
||||
m = re.match(r"(\d+)-(\d+)-(\d+)-(\d+)-(\d+)(?:-(\d+))?", clean)
|
||||
if not m:
|
||||
return None
|
||||
groups = m.groups()
|
||||
return {
|
||||
"etap": int(groups[0]), # 1: этап строительства
|
||||
"glava": int(groups[1]), # 2: глава ССР
|
||||
"razdel": int(groups[2]), # 3: раздел в главе
|
||||
"os_num": int(groups[3]), # 4: объектная смета (0=одиночная)
|
||||
"ls_num": int(groups[4]), # 5: порядковый номер ЛС
|
||||
"sub_num": int(groups[5]) if groups[5] else None, # 6: подномер (если есть)
|
||||
}
|
||||
|
||||
|
||||
def parse_gge(content: bytes) -> dict | None:
|
||||
"""Parse GGE XML → structured estimate data."""
|
||||
try:
|
||||
root = ET.fromstring(content)
|
||||
except ET.ParseError:
|
||||
return None
|
||||
|
||||
est = root.find(".//Estimate")
|
||||
if est is None:
|
||||
return None
|
||||
|
||||
num_el = est.find("Num")
|
||||
name_el = est.find("Name")
|
||||
if num_el is None or not num_el.text:
|
||||
return None
|
||||
|
||||
code = num_el.text.strip()
|
||||
name = (name_el.text or "").strip()
|
||||
prefix = "ЛСР" # default
|
||||
if code.startswith(("ОС-", "ОСР-")):
|
||||
prefix = code.split("-")[0]
|
||||
elif code.startswith(("ЛС-", "ЛСР-")):
|
||||
prefix = code.split("-")[0]
|
||||
|
||||
parsed_code = parse_code(code)
|
||||
if not parsed_code:
|
||||
return None
|
||||
|
||||
# Collect totals by WorkType
|
||||
totals = {"Строительные": 0.0, "Монтажные": 0.0, "Оборудование": 0.0, "Прочие": 0.0}
|
||||
|
||||
for section in est.iter("Section"):
|
||||
# Get section name
|
||||
sec_name_el = section.find("Name")
|
||||
sec_name = (sec_name_el.text or "").strip() if sec_name_el is not None else ""
|
||||
|
||||
# Determine WorkType
|
||||
work_type = None
|
||||
items = section.find("Items")
|
||||
if items is not None:
|
||||
for item in items.findall("Item"):
|
||||
wt = item.find("WorkType")
|
||||
if wt is not None and wt.text:
|
||||
work_type = wt.text.strip()
|
||||
break
|
||||
|
||||
# Get section total
|
||||
sp = section.find("SectionPrice")
|
||||
if sp is not None:
|
||||
summary = sp.find("Summary")
|
||||
if summary is not None:
|
||||
total_el = summary.find("Total")
|
||||
if total_el is not None and total_el.text:
|
||||
total = float(total_el.text)
|
||||
if work_type == "Перевозка":
|
||||
totals["Прочие"] += total
|
||||
elif work_type in totals:
|
||||
totals[work_type] += total
|
||||
else:
|
||||
totals["Строительные"] += total
|
||||
|
||||
grand_total = sum(totals.values())
|
||||
|
||||
# Fallback
|
||||
if grand_total == 0:
|
||||
for ep in est.iter("EstimatePrice"):
|
||||
t = ep.find("Total")
|
||||
if t is not None and t.text:
|
||||
grand_total = float(t.text)
|
||||
totals["Строительные"] = grand_total
|
||||
break
|
||||
|
||||
return {
|
||||
"code": code,
|
||||
"prefix": prefix,
|
||||
"name": name,
|
||||
"parsed": parsed_code,
|
||||
"totals_rub": totals,
|
||||
"totals_tys": {k: round(v / 1000, 2) for k, v in totals.items()},
|
||||
"grand_total_rub": grand_total,
|
||||
"grand_total_tys": round(grand_total / 1000, 2),
|
||||
}
|
||||
|
||||
|
||||
def build_hierarchy(estimates: list[dict]) -> dict:
|
||||
"""Build chapter → section → OS → LS hierarchy."""
|
||||
hierarchy = defaultdict(lambda: {
|
||||
"name": "",
|
||||
"razrely": defaultdict(lambda: {
|
||||
"name": "",
|
||||
"os": defaultdict(lambda: {
|
||||
"name": "",
|
||||
"estimates": [],
|
||||
"totals_tys": {"Строительные": 0, "Монтажные": 0, "Оборудование": 0, "Прочие": 0},
|
||||
}),
|
||||
}),
|
||||
"totals_tys": {"Строительные": 0, "Монтажные": 0, "Оборудование": 0, "Прочие": 0},
|
||||
})
|
||||
|
||||
chapter_names = {
|
||||
1: "Подготовка территории строительства",
|
||||
2: "Основные объекты строительства",
|
||||
3: "Объекты подсобного и обслуживающего назначения",
|
||||
4: "Объекты энергетического хозяйства",
|
||||
5: "Объекты транспортного хозяйства и связи",
|
||||
6: "Наружные сети и сооружения",
|
||||
7: "Благоустройство и озеленение территории",
|
||||
8: "Временные здания и сооружения",
|
||||
9: "Прочие работы и затраты",
|
||||
10: "Содержание службы заказчика",
|
||||
11: "Подготовка эксплуатационных кадров",
|
||||
12: "Проектные и изыскательские работы",
|
||||
}
|
||||
|
||||
for est in estimates:
|
||||
p = est["parsed"]
|
||||
ch = p["glava"]
|
||||
rz = p["razdel"]
|
||||
os_num = p["os_num"]
|
||||
|
||||
hierarchy[ch]["name"] = chapter_names.get(ch, f"Глава {ch}")
|
||||
|
||||
# Add to OS group
|
||||
os_group = hierarchy[ch]["razrely"][rz]["os"][os_num]
|
||||
os_group["estimates"].append(est)
|
||||
|
||||
# Sum totals
|
||||
for wtype, val in est["totals_tys"].items():
|
||||
os_group["totals_tys"][wtype] += val
|
||||
hierarchy[ch]["totals_tys"][wtype] += val
|
||||
|
||||
return dict(hierarchy)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Parse GGE → project structure")
|
||||
parser.add_argument("zip_file", help="ZIP с GGE-файлами")
|
||||
parser.add_argument("--output", default=None, help="Output JSON file")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not Path(args.zip_file).exists():
|
||||
print(f"ZIP not found: {args.zip_file}")
|
||||
sys.exit(1)
|
||||
|
||||
output = args.output or f"project_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
|
||||
# Parse all GGE files
|
||||
print("Parsing GGE files...")
|
||||
estimates = []
|
||||
errors = []
|
||||
with zipfile.ZipFile(args.zip_file) as z:
|
||||
gge_infos = [i for i in z.infolist()
|
||||
if i.filename.lower().endswith(".gge") and i.file_size > 100]
|
||||
for i, info in enumerate(gge_infos):
|
||||
if not (info.flag_bits & 0x800):
|
||||
info.filename = fix_zip_encoding(info.filename)
|
||||
content = z.read(info)
|
||||
parsed = parse_gge(content)
|
||||
if parsed:
|
||||
parsed["source_file"] = Path(info.filename).name
|
||||
estimates.append(parsed)
|
||||
else:
|
||||
errors.append(info.filename)
|
||||
if (i + 1) % 300 == 0:
|
||||
print(f" {i + 1}/{len(gge_infos)}...")
|
||||
|
||||
print(f"Parsed: {len(estimates)} estimates, {len(errors)} errors")
|
||||
|
||||
# Build hierarchy
|
||||
print("Building hierarchy...")
|
||||
hierarchy = build_hierarchy(estimates)
|
||||
|
||||
# Summary
|
||||
print(f"\n=== СТРУКТУРА ПРОЕКТА ===\n")
|
||||
grand_totals = {"Строительные": 0, "Монтажные": 0, "Оборудование": 0, "Прочие": 0}
|
||||
for ch_num in sorted(hierarchy):
|
||||
ch = hierarchy[ch_num]
|
||||
ch_total = sum(ch["totals_tys"].values())
|
||||
n_estimates = sum(
|
||||
len(os_data["estimates"])
|
||||
for rz in ch["razrely"].values()
|
||||
for os_data in rz["os"].values()
|
||||
)
|
||||
n_os = sum(len(rz["os"]) for rz in ch["razrely"].values())
|
||||
n_rz = len(ch["razrely"])
|
||||
|
||||
print(f" Глава {ch_num}: {ch['name']}")
|
||||
print(f" Разделов: {n_rz}, ОС: {n_os}, ЛС: {n_estimates}")
|
||||
print(f" Стр: {ch['totals_tys']['Строительные']:>12,.2f} "
|
||||
f"Монт: {ch['totals_tys']['Монтажные']:>12,.2f} "
|
||||
f"Обор: {ch['totals_tys']['Оборудование']:>12,.2f} "
|
||||
f"Проч: {ch['totals_tys']['Прочие']:>12,.2f} "
|
||||
f"ИТОГО: {ch_total:>14,.2f} тыс.руб")
|
||||
|
||||
for wtype, val in ch["totals_tys"].items():
|
||||
grand_totals[wtype] += val
|
||||
|
||||
grand = sum(grand_totals.values())
|
||||
print(f"\n ВСЕГО по главам 1-{max(hierarchy.keys())}:")
|
||||
print(f" Стр: {grand_totals['Строительные']:>12,.2f} "
|
||||
f"Монт: {grand_totals['Монтажные']:>12,.2f} "
|
||||
f"Обор: {grand_totals['Оборудование']:>12,.2f} "
|
||||
f"Проч: {grand_totals['Прочие']:>12,.2f} "
|
||||
f"ИТОГО: {grand:>14,.2f} тыс.руб")
|
||||
|
||||
# Save
|
||||
result = {
|
||||
"generated": datetime.now().isoformat(),
|
||||
"source": args.zip_file,
|
||||
"total_estimates": len(estimates),
|
||||
"total_errors": len(errors),
|
||||
"grand_totals_tys": grand_totals,
|
||||
"grand_total_tys": grand,
|
||||
"chapters": {},
|
||||
}
|
||||
# Convert hierarchy to serializable format
|
||||
for ch_num, ch_data in hierarchy.items():
|
||||
ch_dict = {
|
||||
"name": ch_data["name"],
|
||||
"totals_tys": dict(ch_data["totals_tys"]),
|
||||
"sections": {},
|
||||
}
|
||||
for rz_num, rz_data in ch_data["razrely"].items():
|
||||
rz_dict = {"os_groups": {}}
|
||||
for os_num, os_data in rz_data["os"].items():
|
||||
rz_dict["os_groups"][str(os_num)] = {
|
||||
"totals_tys": dict(os_data["totals_tys"]),
|
||||
"estimates": [
|
||||
{
|
||||
"code": e["code"],
|
||||
"name": e["name"][:100],
|
||||
"totals_tys": e["totals_tys"],
|
||||
"grand_total_tys": e["grand_total_tys"],
|
||||
}
|
||||
for e in os_data["estimates"]
|
||||
],
|
||||
}
|
||||
ch_dict["sections"][str(rz_num)] = rz_dict
|
||||
result["chapters"][str(ch_num)] = ch_dict
|
||||
|
||||
with open(output, "w", encoding="utf-8") as f:
|
||||
json.dump(result, f, ensure_ascii=False, indent=2)
|
||||
print(f"\nSaved: {output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,378 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Сверка сумм GGE-файлов с листом РАСПРЕДЕЛЕНИЕ в сводном xlsx.
|
||||
|
||||
Вход:
|
||||
- ZIP с GGE-файлами (локальные сметы)
|
||||
- XLSX сводный файл с листом "РАСПРЕДЕЛЕНИЕ" (или указать имя листа)
|
||||
|
||||
Выход:
|
||||
- Excel-протокол сверки: protocl_sverki_YYYYMMDD_HHMMSS.xlsx
|
||||
|
||||
Usage:
|
||||
python scripts/verify_estimates.py source.zip summary.xlsx
|
||||
python scripts/verify_estimates.py source.zip summary.xlsx --sheet "2266-04 РАСПРЕДЕЛЕНИЕ"
|
||||
python scripts/verify_estimates.py source.zip summary.xlsx --output protocol.xlsx
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
|
||||
def fix_zip_encoding(filename: str) -> str:
|
||||
"""Fix CP437→CP866 encoding for Russian filenames in zip."""
|
||||
try:
|
||||
return filename.encode("cp437").decode("cp866")
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
try:
|
||||
return filename.encode("cp437").decode("utf-8")
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
return filename
|
||||
|
||||
|
||||
def parse_gge_totals(content: bytes) -> dict | None:
|
||||
"""Extract estimate code and totals from GGE XML content."""
|
||||
try:
|
||||
root = ET.fromstring(content)
|
||||
except ET.ParseError:
|
||||
return None
|
||||
|
||||
est = root.find(".//Estimate")
|
||||
if est is None:
|
||||
return None
|
||||
|
||||
num_el = est.find("Num")
|
||||
name_el = est.find("Name")
|
||||
if num_el is None or not num_el.text:
|
||||
return None
|
||||
|
||||
code = num_el.text.strip()
|
||||
name = (name_el.text or "").strip()[:120]
|
||||
|
||||
# Find EstimatePrice total
|
||||
total = 0.0
|
||||
for ep in est.iter("EstimatePrice"):
|
||||
t = ep.find("Total")
|
||||
if t is not None and t.text:
|
||||
total = float(t.text)
|
||||
break
|
||||
|
||||
return {"code": code, "name": name, "total_rub": total, "total_tys": total / 1000}
|
||||
|
||||
|
||||
def read_raspredelenie(xlsx_path: str, sheet_name: str | None = None) -> dict:
|
||||
"""Read РАСПРЕДЕЛЕНИЕ sheet. Returns {code: {row, name, y, z, aa, ab, ac, strike}}."""
|
||||
wb = openpyxl.load_workbook(xlsx_path, read_only=False, data_only=True)
|
||||
|
||||
# Find sheet
|
||||
if sheet_name:
|
||||
if sheet_name not in wb.sheetnames:
|
||||
print(f"Sheet '{sheet_name}' not found. Available: {wb.sheetnames[:10]}")
|
||||
sys.exit(1)
|
||||
ws = wb[sheet_name]
|
||||
else:
|
||||
# Auto-find sheet with "РАСПРЕДЕЛЕНИЕ"
|
||||
ws = None
|
||||
for name in wb.sheetnames:
|
||||
if "РАСПРЕДЕЛЕНИЕ" in name.upper() or "РАСПРЕДЕЛ" in name.upper():
|
||||
ws = wb[name]
|
||||
break
|
||||
if ws is None:
|
||||
print(f"Sheet РАСПРЕДЕЛЕНИЕ not found. Available: {wb.sheetnames[:10]}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Reading sheet: {ws.title}")
|
||||
data = {}
|
||||
for row in ws.iter_rows(min_row=9, max_row=ws.max_row):
|
||||
c_cell = row[2] # column C
|
||||
if c_cell.value is None:
|
||||
continue
|
||||
|
||||
# Check strikethrough
|
||||
strike = False
|
||||
if c_cell.font and c_cell.font.strikethrough:
|
||||
strike = True
|
||||
|
||||
# Handle multi-line codes
|
||||
codes_raw = str(c_cell.value).strip()
|
||||
codes = [c.strip() for c in codes_raw.split("\n") if c.strip()]
|
||||
|
||||
row_num = c_cell.row
|
||||
d_val = str(row[3].value or "")[:120]
|
||||
|
||||
# Columns Y(24), Z(25), AA(26), AB(27), AC(28) — РИМ values
|
||||
def _to_float(v):
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
return float(v)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
y = _to_float(row[24].value)
|
||||
z = _to_float(row[25].value)
|
||||
aa = _to_float(row[26].value)
|
||||
ab = _to_float(row[27].value)
|
||||
ac = _to_float(row[28].value)
|
||||
|
||||
for code in codes:
|
||||
# Normalize: remove extra spaces
|
||||
code = re.sub(r"\s+", " ", code).strip()
|
||||
if not code or code.isdigit():
|
||||
continue
|
||||
data[code] = {
|
||||
"row": row_num,
|
||||
"name": d_val,
|
||||
"y_str": y,
|
||||
"z_mont": z,
|
||||
"aa_equip": aa,
|
||||
"ab_other": ab,
|
||||
"ac_total": ac,
|
||||
"strike": strike,
|
||||
}
|
||||
|
||||
wb.close()
|
||||
return data
|
||||
|
||||
|
||||
def extract_gge_from_zip(zip_path: str) -> list[dict]:
|
||||
"""Extract and parse all GGE files from ZIP."""
|
||||
results = []
|
||||
with zipfile.ZipFile(zip_path) as z:
|
||||
gge_infos = [info for info in z.infolist()
|
||||
if info.filename.lower().endswith(".gge") and info.file_size > 100]
|
||||
print(f"GGE files in ZIP: {len(gge_infos)}")
|
||||
|
||||
for i, info in enumerate(gge_infos):
|
||||
# Fix encoding
|
||||
if not (info.flag_bits & 0x800):
|
||||
info.filename = fix_zip_encoding(info.filename)
|
||||
|
||||
content = z.read(info)
|
||||
parsed = parse_gge_totals(content)
|
||||
if parsed:
|
||||
parsed["filename"] = Path(info.filename).name
|
||||
results.append(parsed)
|
||||
|
||||
if (i + 1) % 200 == 0:
|
||||
print(f" Parsed {i + 1}/{len(gge_infos)}...")
|
||||
|
||||
print(f"Parsed: {len(results)} GGE files")
|
||||
return results
|
||||
|
||||
|
||||
def create_protocol(
|
||||
xlsx_data: dict,
|
||||
gge_data: list[dict],
|
||||
output_path: str,
|
||||
):
|
||||
"""Create Excel verification protocol."""
|
||||
wb = openpyxl.Workbook()
|
||||
|
||||
# === Sheet 1: Matched ===
|
||||
ws1 = wb.active
|
||||
ws1.title = "Сверка"
|
||||
|
||||
# Styles
|
||||
header_font = Font(bold=True, size=10)
|
||||
header_fill = PatternFill("solid", fgColor="D9E1F2")
|
||||
ok_fill = PatternFill("solid", fgColor="C6EFCE")
|
||||
warn_fill = PatternFill("solid", fgColor="FFEB9C")
|
||||
err_fill = PatternFill("solid", fgColor="FFC7CE")
|
||||
strike_fill = PatternFill("solid", fgColor="D9D9D9")
|
||||
thin_border = Border(
|
||||
left=Side(style="thin"), right=Side(style="thin"),
|
||||
top=Side(style="thin"), bottom=Side(style="thin"),
|
||||
)
|
||||
num_fmt = '#,##0.00'
|
||||
|
||||
# Headers
|
||||
headers = [
|
||||
"№", "Шифр сметы", "Наименование",
|
||||
"РАСПР: Стр.работы", "РАСПР: Монтаж", "РАСПР: Оборуд.", "РАСПР: Прочие", "РАСПР: Всего",
|
||||
"GGE: Итого (тыс.руб)",
|
||||
"Разница (тыс.руб)", "Разница (%)",
|
||||
"Статус", "Строка XLSX", "GGE файл",
|
||||
]
|
||||
for col, h in enumerate(headers, 1):
|
||||
cell = ws1.cell(row=1, column=col, value=h)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.border = thin_border
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="center")
|
||||
|
||||
# Build GGE lookup
|
||||
gge_by_code = {}
|
||||
for g in gge_data:
|
||||
code = g["code"]
|
||||
if code not in gge_by_code:
|
||||
gge_by_code[code] = g
|
||||
else:
|
||||
# Multiple GGE with same code — sum totals
|
||||
gge_by_code[code]["total_tys"] += g["total_tys"]
|
||||
|
||||
# Process all XLSX codes
|
||||
row_idx = 2
|
||||
stats = {"match_exact": 0, "match_close": 0, "mismatch": 0,
|
||||
"xlsx_only": 0, "gge_only": 0, "strike_skip": 0}
|
||||
matched_gge_codes = set()
|
||||
|
||||
for code, xdata in sorted(xlsx_data.items(), key=lambda x: x[1]["row"]):
|
||||
if xdata["strike"]:
|
||||
stats["strike_skip"] += 1
|
||||
continue
|
||||
|
||||
gge = gge_by_code.get(code)
|
||||
xlsx_total = xdata["ac_total"]
|
||||
|
||||
if gge:
|
||||
matched_gge_codes.add(code)
|
||||
gge_total = gge["total_tys"]
|
||||
diff = gge_total - (xlsx_total or 0) if xlsx_total is not None else None
|
||||
pct = (diff / xlsx_total * 100) if xlsx_total and xlsx_total != 0 and diff is not None else None
|
||||
|
||||
if diff is not None and abs(diff) < 0.01:
|
||||
status = "✓ Совпадает"
|
||||
fill = ok_fill
|
||||
stats["match_exact"] += 1
|
||||
elif diff is not None and abs(diff) < 1.0:
|
||||
status = "≈ Близко"
|
||||
fill = ok_fill
|
||||
stats["match_close"] += 1
|
||||
else:
|
||||
status = "✗ Расхождение"
|
||||
fill = err_fill
|
||||
stats["mismatch"] += 1
|
||||
else:
|
||||
gge_total = None
|
||||
diff = None
|
||||
pct = None
|
||||
status = "— Нет GGE"
|
||||
fill = warn_fill
|
||||
stats["xlsx_only"] += 1
|
||||
|
||||
values = [
|
||||
row_idx - 1, code, xdata["name"],
|
||||
xdata["y_str"], xdata["z_mont"], xdata["aa_equip"], xdata["ab_other"], xlsx_total,
|
||||
gge_total,
|
||||
diff, pct,
|
||||
status, xdata["row"], gge["filename"] if gge else "",
|
||||
]
|
||||
for col, v in enumerate(values, 1):
|
||||
cell = ws1.cell(row=row_idx, column=col, value=v)
|
||||
cell.border = thin_border
|
||||
if col in (4, 5, 6, 7, 8, 9, 10):
|
||||
cell.number_format = num_fmt
|
||||
if col == 11 and pct is not None:
|
||||
cell.number_format = '0.00%'
|
||||
cell.value = pct / 100 # Excel expects fraction
|
||||
if col == 12:
|
||||
cell.fill = fill
|
||||
|
||||
row_idx += 1
|
||||
|
||||
# GGE-only (not in XLSX)
|
||||
for code, gge in sorted(gge_by_code.items()):
|
||||
if code in matched_gge_codes or code in xlsx_data:
|
||||
continue
|
||||
stats["gge_only"] += 1
|
||||
values = [
|
||||
row_idx - 1, code, gge["name"],
|
||||
None, None, None, None, None,
|
||||
gge["total_tys"],
|
||||
None, None,
|
||||
"— Нет в РАСПР", "", gge["filename"],
|
||||
]
|
||||
for col, v in enumerate(values, 1):
|
||||
cell = ws1.cell(row=row_idx, column=col, value=v)
|
||||
cell.border = thin_border
|
||||
if col in (9,):
|
||||
cell.number_format = num_fmt
|
||||
if col == 12:
|
||||
cell.fill = warn_fill
|
||||
row_idx += 1
|
||||
|
||||
# Auto-width
|
||||
for col in range(1, len(headers) + 1):
|
||||
ws1.column_dimensions[get_column_letter(col)].width = max(12, min(40, len(headers[col - 1]) + 4))
|
||||
ws1.column_dimensions["B"].width = 25
|
||||
ws1.column_dimensions["C"].width = 50
|
||||
ws1.column_dimensions["N"].width = 40
|
||||
|
||||
# Freeze
|
||||
ws1.freeze_panes = "A2"
|
||||
ws1.auto_filter.ref = f"A1:N{row_idx - 1}"
|
||||
|
||||
# === Sheet 2: Summary ===
|
||||
ws2 = wb.create_sheet("Итоги")
|
||||
summary_data = [
|
||||
["ПРОТОКОЛ СВЕРКИ", ""],
|
||||
["Дата:", datetime.now().strftime("%d.%m.%Y %H:%M")],
|
||||
["", ""],
|
||||
["Совпадает точно (< 0.01 тыс.руб)", stats["match_exact"]],
|
||||
["Совпадает приблизительно (< 1.0 тыс.руб)", stats["match_close"]],
|
||||
["Расхождения (>= 1.0 тыс.руб)", stats["mismatch"]],
|
||||
["Нет GGE файла (только в XLSX)", stats["xlsx_only"]],
|
||||
["Нет в РАСПРЕДЕЛЕНИЕ (только GGE)", stats["gge_only"]],
|
||||
["Зачёркнутые (пропущены)", stats["strike_skip"]],
|
||||
["", ""],
|
||||
["ИТОГО кодов в XLSX", len(xlsx_data)],
|
||||
["ИТОГО GGE файлов", len(gge_data)],
|
||||
["ИТОГО совпавших", stats["match_exact"] + stats["match_close"]],
|
||||
["Точность (%)", f"{(stats['match_exact'] + stats['match_close']) / max(1, stats['match_exact'] + stats['match_close'] + stats['mismatch']) * 100:.1f}%"],
|
||||
]
|
||||
for r, (label, val) in enumerate(summary_data, 1):
|
||||
ws2.cell(row=r, column=1, value=label).font = Font(bold=(r == 1))
|
||||
ws2.cell(row=r, column=2, value=val)
|
||||
ws2.column_dimensions["A"].width = 45
|
||||
ws2.column_dimensions["B"].width = 15
|
||||
|
||||
# Save
|
||||
wb.save(output_path)
|
||||
print(f"\nProtocol saved: {output_path}")
|
||||
print(f"\nСтатистика:")
|
||||
for k, v in stats.items():
|
||||
print(f" {k}: {v}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Сверка GGE-файлов с листом РАСПРЕДЕЛЕНИЕ")
|
||||
parser.add_argument("zip_file", help="ZIP с GGE-файлами")
|
||||
parser.add_argument("xlsx_file", help="Сводный XLSX с листом РАСПРЕДЕЛЕНИЕ")
|
||||
parser.add_argument("--sheet", default=None, help="Имя листа (авто-поиск если не указано)")
|
||||
parser.add_argument("--output", default=None, help="Имя выходного файла")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.exists(args.zip_file):
|
||||
print(f"ZIP not found: {args.zip_file}")
|
||||
sys.exit(1)
|
||||
if not os.path.exists(args.xlsx_file):
|
||||
print(f"XLSX not found: {args.xlsx_file}")
|
||||
sys.exit(1)
|
||||
|
||||
output = args.output or f"protocol_sverki_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
||||
|
||||
print("1. Reading РАСПРЕДЕЛЕНИЕ...")
|
||||
xlsx_data = read_raspredelenie(args.xlsx_file, args.sheet)
|
||||
print(f" Codes: {len(xlsx_data)}")
|
||||
|
||||
print("\n2. Parsing GGE files from ZIP...")
|
||||
gge_data = extract_gge_from_zip(args.zip_file)
|
||||
|
||||
print("\n3. Creating protocol...")
|
||||
create_protocol(xlsx_data, gge_data, output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user