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