From 46e14e4e6282fdaf3f40258ab324ba972e0dc881 Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 30 Mar 2026 05:02:06 +1000 Subject: [PATCH] =?UTF-8?q?refactor:=20API-=D1=84=D1=83=D0=BD=D0=BA=D1=86?= =?UTF-8?q?=D0=B8=D1=8F=20fill=5Fraspredelenie=5Ffrom=5Fzip=20+=20fix=20?= =?UTF-8?q?=D0=B4=D0=B2=D0=BE=D0=B9=D0=BD=D0=BE=D0=B3=D0=BE=20=D1=81=D1=87?= =?UTF-8?q?=D1=91=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fill_raspredelenie_from_zip() — вызов из Python без CLI. Возвращает stats + HTML-протокол заполнения. Исправлен баг: строки 302-308 всегда выполнялись (двойной счёт). Co-Authored-By: Claude Opus 4.6 (1M context) --- scripts/fill_raspredelenie.py | 186 ++++++++++++++++++++++++++++++++-- 1 file changed, 178 insertions(+), 8 deletions(-) diff --git a/scripts/fill_raspredelenie.py b/scripts/fill_raspredelenie.py index 56b77bb..f493bf8 100644 --- a/scripts/fill_raspredelenie.py +++ b/scripts/fill_raspredelenie.py @@ -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""" +Протокол заполнения + +

Протокол заполнения РАСПРЕДЕЛЕНИЕ

+

Лист: {s['sheet']} | GGE-файлов: {s['gge_files']} | Уникальных кодов: {s['gge_codes']}

+ +
+{s['filled']} заполнено +{s['matched']} совпадает +{s['mismatch']} исправлено +{s['not_found']} нет GGE +{s['skipped_strike']} зачёркнуто +
+ +

Детали ({len(log)} позиций)

+ + +""" + 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'\n' + + if len(log) > 200: + html += f'\n' + html += "
СтрокаКодСтатусИтого (тыс.руб)
{entry["row"]}{entry["code"]}{entry["status"]}{total}
... и ещё {len(log)-200} позиций
" + 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)