#!/usr/bin/env python3 """Test batch with real smeta files using smart detection.""" import sys, re, shutil from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent)) from batch import read_xlsx_xml import openpyxl SOURCE_DIR = "/tmp/real_batch/source" TARGET_ORIG = "/tmp/Раздел ПД N 9 Том 9.1 12.0866-СМ.ССР.xlsx" TARGET_FILE = "/tmp/real_batch/result_real.xlsx" # Copy target shutil.copy2(TARGET_ORIG, TARGET_FILE) # Get source files source_files = list(Path(SOURCE_DIR).rglob("*.xlsx")) print("Source files:", len(source_files)) # Open target wb = openpyxl.load_workbook(TARGET_FILE) ws = wb["ССРСС-1 ТУЦ"] if "ССРСС-1 ТУЦ" in wb.sheetnames else wb.active print("Target sheet:", ws.title) # Build code → row mapping code_to_row = {} for r in range(1, ws.max_row + 1): v = ws.cell(r, 2).value # column B if v and str(v).startswith("ЛС-"): code_to_row[str(v).strip()] = r print("Target codes:", list(code_to_row.keys())[:5], "...") # Process each source file processed = 0 errors = [] KEYWORDS = { "строительные": "ВСЕГО строительные работы", "монтажные": "ВСЕГО монтажные работы", "оборудование": "ВСЕГО оборудование", "прочие": "ВСЕГО прочие затраты", } TARGET_COLS = {"строительные": 4, "монтажные": 5, "оборудование": 6, "прочие": 7} # D,E,F,G for f in source_files: # Extract code from filename m = re.match(r"(ЛС-\d{2}-\d{2}-\d+-\d{2}-\d{2})", f.name) if not m: errors.append("%s: no code in filename" % f.name) continue code = m.group(1) if code not in code_to_row: errors.append("%s: code %s not in target" % (f.name, code)) continue target_row = code_to_row[code] # Read file data = read_xlsx_xml(str(f), max_rows=999) if not data: errors.append("%s: can't read" % f.name) continue rows = list(data.values())[0] # Find totals by keywords (search from end) for name, kw in KEYWORDS.items(): for i in range(len(rows) - 1, max(0, len(rows) - 100), -1): found = False for j in range(len(rows[i])): v = str(rows[i][j]) if rows[i][j] else "" if kw.lower() in v.lower(): # Find numeric value on same row for vj in range(len(rows[i])): val = rows[i][vj] if val and vj != j: try: num = float(str(val).replace(",", ".").replace(" ", "")) # Convert from rubles to thousands num_tys = round(num / 1000, 2) ws.cell(target_row, TARGET_COLS[name]).value = num_tys found = True break except (ValueError, TypeError): pass break if found: break processed += 1 print(" %s → row %d: OK" % (code, target_row)) wb.save(TARGET_FILE) print("\nResult: %d/%d processed, %d errors" % (processed, len(source_files), len(errors))) for e in errors: print(" ERROR:", e) # Show result print("\nTarget values:") for code, row in sorted(code_to_row.items()): d = ws.cell(row, 4).value e = ws.cell(row, 5).value f_val = ws.cell(row, 6).value g = ws.cell(row, 7).value if d or e or f_val or g: print(" %s: СМР=%s Монт=%s Обор=%s Проч=%s" % (code, d, e, f_val, g))