Files
anorandClaude Opus 4.6 e45a0734d8 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>
2026-03-29 23:26:37 +10:00

379 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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()