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>
This commit is contained in:
@@ -121,6 +121,184 @@ def parse_gge(content: bytes) -> dict | None:
|
||||
}
|
||||
|
||||
|
||||
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-файлами")
|
||||
@@ -299,14 +477,6 @@ def main():
|
||||
"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)
|
||||
|
||||
Reference in New Issue
Block a user