Files
smeta-railway/scripts/fill_raspredelenie.py
T
anorandClaude Opus 4.6 46e14e4e62 refactor: API-функция fill_raspredelenie_from_zip + fix двойного счёта
fill_raspredelenie_from_zip() — вызов из Python без CLI.
Возвращает stats + HTML-протокол заполнения.
Исправлен баг: строки 302-308 всегда выполнялись (двойной счёт).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 05:02:06 +10:00

545 lines
20 KiB
Python
Raw 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-файлов.
Читает 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 fill_raspredelenie_from_zip(zip_path, xlsx_path, output_path, sheet_name=None):
"""Fill РАСПРЕДЕЛЕНИЕ sheet from GGE ZIP. Callable from Python.
Returns dict with stats and HTML summary.
"""
# 1. Parse GGE
gge_by_code = {}
with zipfile.ZipFile(zip_path) 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:
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
# 2. Open XLSX (copy first)
shutil.copy2(xlsx_path, output_path)
wb = openpyxl.load_workbook(output_path)
ws = None
if sheet_name:
ws = wb[sheet_name]
else:
for name in wb.sheetnames:
if "РАСПРЕДЕЛЕНИЕ" in name.upper():
ws = wb[name]
break
if ws is None:
wb.close()
return {"error": "Лист РАСПРЕДЕЛЕНИЕ не найден"}
# 3. Fill data
filled = 0
matched = 0
mismatch = 0
not_found = 0
skipped_strike = 0
log = []
for row in ws.iter_rows(min_row=9, max_row=ws.max_row):
c_cell = row[2]
if c_cell.value is None:
continue
if c_cell.font and c_cell.font.strikethrough:
skipped_strike += 1
continue
c_val = str(c_cell.value).strip()
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():
continue
codes = [normalize_code(c) for c in c_val.split("\n") if c.strip()]
if not codes:
continue
gge = None
for code in codes:
if code in gge_by_code:
gge = gge_by_code[code]
break
if not gge:
not_found += 1
log.append({"row": c_cell.row, "code": c_val[:30], "status": "Нет GGE", "total": 0})
continue
gge_vals = {
24: round(gge["str_tys"], 2) if gge["str_tys"] else 0,
25: round(gge["mont_tys"], 2) if gge["mont_tys"] else 0,
26: round(gge["equip_tys"], 2) if gge["equip_tys"] else 0,
27: round(gge["other_tys"], 2) if gge["other_tys"] else 0,
28: round(gge["total_tys"], 2),
}
is_empty = True
is_correct = True
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:
if abs(float(xlsx_val) - gge_val) > 0.1:
is_correct = False
except (ValueError, TypeError):
pass
if is_empty:
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": codes[0], "status": "Заполнено",
"total": gge_vals[28]})
elif is_correct:
matched += 1
log.append({"row": c_cell.row, "code": codes[0], "status": "Совпадает",
"total": gge_vals[28]})
else:
for col_idx, gge_val in gge_vals.items():
row[col_idx].value = gge_val if gge_val else None
mismatch += 1
log.append({"row": c_cell.row, "code": codes[0], "status": "Исправлено",
"total": gge_vals[28]})
wb.save(output_path)
wb.close()
stats = {
"gge_codes": len(gge_by_code),
"gge_files": len(gge_infos),
"filled": filled,
"matched": matched,
"mismatch": mismatch,
"not_found": not_found,
"skipped_strike": skipped_strike,
"sheet": ws.title,
}
# Generate HTML summary
html = _build_fill_html(stats, log)
return {"stats": stats, "log": log, "html": html}
def _build_fill_html(stats, log):
"""Build HTML summary for fill results."""
s = stats
html = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Протокол заполнения</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; background: #f9f9f9; }}
h1 {{ color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }}
h2 {{ color: #2c3e50; margin-top: 20px; }}
table {{ border-collapse: collapse; width: 100%; background: white; margin: 10px 0; }}
th {{ background: #3498db; color: white; padding: 8px 12px; text-align: left; }}
td {{ padding: 6px 12px; border: 1px solid #ddd; }}
tr:nth-child(even) {{ background: #f8f9fa; }}
.ok {{ color: #2d8a56; font-weight: bold; }}
.warn {{ color: #d4a017; }}
.err {{ color: #c4463a; }}
.stat {{ display: inline-block; background: #ede5db; padding: 5px 15px; border-radius: 6px; margin: 3px; }}
.stat b {{ font-size: 1.2em; }}
</style></head><body>
<h1>Протокол заполнения РАСПРЕДЕЛЕНИЕ</h1>
<p>Лист: <b>{s['sheet']}</b> | GGE-файлов: {s['gge_files']} | Уникальных кодов: {s['gge_codes']}</p>
<div style="margin:15px 0">
<span class="stat"><b class="ok">{s['filled']}</b> заполнено</span>
<span class="stat"><b class="ok">{s['matched']}</b> совпадает</span>
<span class="stat"><b class="err">{s['mismatch']}</b> исправлено</span>
<span class="stat"><b class="warn">{s['not_found']}</b> нет GGE</span>
<span class="stat">{s['skipped_strike']} зачёркнуто</span>
</div>
<h2>Детали ({len(log)} позиций)</h2>
<table>
<tr><th>Строка</th><th>Код</th><th>Статус</th><th>Итого (тыс.руб)</th></tr>
"""
for entry in log[:200]: # limit to 200 rows
cls = "ok" if entry["status"] in ("Заполнено", "Совпадает") else "err" if entry["status"] == "Исправлено" else "warn"
total = f'{entry["total"]:,.2f}' if entry["total"] else ""
html += f'<tr><td>{entry["row"]}</td><td>{entry["code"]}</td><td class="{cls}">{entry["status"]}</td><td style="text-align:right">{total}</td></tr>\n'
if len(log) > 200:
html += f'<tr><td colspan="4">... и ещё {len(log)-200} позиций</td></tr>\n'
html += "</table></body></html>"
return html
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,
})
# 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()