Скрипт 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>
375 lines
14 KiB
Python
375 lines
14 KiB
Python
#!/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()
|