import re from dataclasses import dataclass from decimal import Decimal, InvalidOperation from pathlib import Path from typing import Any, Dict, List, Optional import openpyxl from sqlalchemy import func from sqlalchemy.orm import Session from app.models import boq @dataclass class ParsedRow: row_number: int kind: str values: Dict[str, Any] system: Optional[str] = None section: Optional[str] = None error: Optional[str] = None def _is_number(value: Any) -> bool: if isinstance(value, bool) or value is None: return False if isinstance(value, (int, float, Decimal)): return True if isinstance(value, str): try: Decimal(value.strip().replace(" ", "").replace(",", ".")) return bool(value.strip()) except InvalidOperation: return False return False def _decimal(value: Any, row_number: int, label: str, errors: List[str]) -> Optional[Decimal]: if value is None or (isinstance(value, str) and not value.strip()): return None try: return Decimal(str(value).strip().replace(" ", "").replace(",", ".")) except (InvalidOperation, ValueError): errors.append(f"Строка {row_number}: в поле «{label}» некорректное число: {value!r}") return None def _row_level(ws, row_number: int) -> int: # Excel outline/indent metadata, when present, distinguishes nested headings row_dim = ws.row_dimensions[row_number] return int(row_dim.outlineLevel or 0) * 100 + int(row_dim.thickTop or 0) def _heading_kind(cell) -> Optional[str]: """Use style/format characteristics, with style ids as workbook-specific hints.""" if cell.style_id == 21: return "system" if cell.style_id == 19: return "section" fill = cell.fill color = fill.fgColor.rgb if fill and fill.fgColor.type == "rgb" else None size = cell.font.sz indent = cell.alignment.indent or 0 if color and color[-6:].upper() in {"B4C6E7", "4472C4", "5B9BD5"} and size == 11: return "system" if color and color[-6:].upper() in {"E2EFDA", "70AD47", "A9D18E"} and size == 10 and indent > 0: return "section" return None def parse_excel_data(file_path: str, sheet_name: str, header_row: int = 5, start_row: int = 6) -> Dict[str, Any]: """Parse the A:H BOQ layout once for both preview and database import.""" wb = openpyxl.load_workbook(file_path, read_only=False, data_only=True) try: if sheet_name not in wb.sheetnames: raise ValueError(f"Лист {sheet_name!r} не найден. Доступны: {', '.join(wb.sheetnames)}") ws = wb[sheet_name] headers = [ws.cell(header_row, col).value for col in range(1, 9)] rows: List[ParsedRow] = [] errors: List[str] = [] current_system: Optional[str] = None current_section: Optional[str] = None prior_heading_level: Optional[int] = None for row_number in range(start_row, ws.max_row + 1): values = [ws.cell(row_number, col).value for col in range(1, 9)] first = values[0] if all(v is None or (isinstance(v, str) and not v.strip()) for v in values): continue first_text = str(first).strip() if first is not None else "" if re.search(r"итого\s+по\s+(разделу|ведомости)", first_text, re.IGNORECASE): rows.append(ParsedRow(row_number, "total", {"raw": values})) continue if _is_number(first): row_errors: List[str] = [] quantity = _decimal(values[5], row_number, "Кол-во", row_errors) price = _decimal(values[6], row_number, "Цена за ед.", row_errors) amount = _decimal(values[7], row_number, "Сумма", row_errors) if not str(values[1] or "").strip(): row_errors.append(f"Строка {row_number}: не заполнено обязательное поле «Наименование»") errors.extend(row_errors) rows.append(ParsedRow(row_number, "item", { "source_number": str(first_text), "name": str(values[1]).strip() if values[1] is not None else "", "model": str(values[2]).strip() if values[2] is not None else None, "manufacturer": str(values[3]).strip() if values[3] is not None else None, "unit": str(values[4]).strip() if values[4] is not None else None, "quantity": quantity, "unit_price": price, "amount": amount, }, current_system, current_section, "; ".join(row_errors) or None)) continue # A non-numeric label in column A is a hierarchy heading. Determine # nesting from Excel outline metadata when available; otherwise the # first heading establishes a system and later headings establish sections. if not first_text: continue level = _row_level(ws, row_number) merged_heading = any(r.min_row == row_number and r.max_row == row_number and r.min_col == 1 and r.max_col >= 8 for r in ws.merged_cells.ranges) heading_kind = _heading_kind(ws.cell(row_number, 1)) if merged_heading else None if heading_kind == "system" or (heading_kind is None and (current_system is None or level < (prior_heading_level or 0))): current_system, current_section = first_text, None rows.append(ParsedRow(row_number, "system", {}, current_system, None)) elif heading_kind == "section" or level > (prior_heading_level or 0): current_section = first_text rows.append(ParsedRow(row_number, "section", {}, current_system, current_section)) elif current_section is None: current_section = first_text rows.append(ParsedRow(row_number, "section", {}, current_system, current_section)) else: # Same-level sibling after a section is a new section in the current system. current_section = first_text rows.append(ParsedRow(row_number, "section", {}, current_system, current_section)) prior_heading_level = level return {"headers": headers, "rows": rows, "errors": errors, "systems_count": len({r.system for r in rows if r.kind == "system"}), "sections_count": len({(r.system, r.section) for r in rows if r.kind == "section"}), "work_items_count": sum(r.kind == "item" for r in rows), "total_amount": sum((r.values["amount"] or Decimal("0")) for r in rows if r.kind == "item").quantize(Decimal("0.01")), "excel_total": sum((Decimal(str(r.values["raw"][7])) for r in rows if r.kind == "total" and re.search(r"по\s+ведомости", str(r.values["raw"][0]), re.IGNORECASE) and isinstance(r.values["raw"][7], (int, float, Decimal))), Decimal("0"))} finally: wb.close() def get_excel_sheets(file_path: str) -> List[str]: wb = openpyxl.load_workbook(file_path, read_only=True) try: return wb.sheetnames finally: wb.close() def preview_excel_data(file_path: str, sheet_name: str, header_row: int, start_row: int) -> Dict[str, Any]: parsed = parse_excel_data(file_path, sheet_name, header_row, start_row) parsed["data"] = [r.values.get("raw", list(r.values.values())) for r in parsed["rows"][:20]] parsed["difference"] = parsed["total_amount"] - parsed["excel_total"] return parsed def import_excel_data(db: Session, file_path: str, sheet_name: str, header_row: int, start_row: int, project_id: int) -> Dict[str, Any]: parsed = parse_excel_data(file_path, sheet_name, header_row, start_row) if parsed["errors"]: raise ValueError("\n".join(parsed["errors"])) try: doc = boq.BoqDocument(project_id=project_id, name=f"Импорт ведомости — {sheet_name}", source_file=Path(file_path).name, version="1.0") db.add(doc) db.flush() systems: Dict[str, boq.System] = {} sections: Dict[tuple, boq.Section] = {} for row in parsed["rows"]: if row.kind == "system": if row.system not in systems: systems[row.system] = boq.System(project_id=project_id, name=row.system, code=None) db.add(systems[row.system]) db.flush() elif row.kind == "section": key = (row.system, row.section) if row.system not in systems: systems[row.system] = boq.System(project_id=project_id, name=row.system, code=None) db.add(systems[row.system]); db.flush() if key not in sections: sections[key] = boq.Section(system_id=systems[row.system].id, name=row.section) db.add(sections[key]); db.flush() elif row.kind == "item": item = boq.WorkItem(project_id=project_id, boq_document_id=doc.id, system_id=systems[row.system].id if row.system in systems else None, section_id=sections[(row.system, row.section)].id if (row.system, row.section) in sections else None, **row.values) db.add(item) db.flush() db.commit() except Exception: db.rollback() raise db_total = db.query(func.coalesce(func.sum(boq.WorkItem.amount), 0)).filter( boq.WorkItem.boq_document_id == doc.id ).scalar() db_total_display = Decimal(str(db_total or 0)).quantize(Decimal("0.01")) excel_total_display = parsed["excel_total"].quantize(Decimal("0.01")) return {"status": "success", "document_id": doc.id, "systems": len(systems), "sections": len(sections), "work_items": parsed["work_items_count"], "total_amount": db_total_display, "db_total": db_total_display, "excel_total": excel_total_display, "difference": db_total_display - excel_total_display}