feat: wizard-агрегатор xlsx — пошаговый мастер для сметчиков
7-шаговый wizard: загрузка ZIP+целевой → поиск по ключевому слову → выбор колонок → сопоставление → превью → применение → скачивание. FastAPI + vanilla JS (Bootstrap 5), порт 8102. Протестировано на реальных данных: 4 ресурсных ведомости → Сводка стоимости затрат труда (19 обновлений + 10 новых разрядов). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,256 @@
|
||||
"""
|
||||
FastAPI endpoints for the wizard-aggregator.
|
||||
|
||||
Session management via in-memory dict + tempdir per session.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, UploadFile, File
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .xlsx_aggregator import (
|
||||
AggConfig,
|
||||
analyze_xlsx,
|
||||
analyze_zip,
|
||||
match_and_preview,
|
||||
run_aggregation,
|
||||
search_in_sources,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Session management
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_sessions: dict[str, dict] = {}
|
||||
_MAX_AGE = 3600 # 1 hour
|
||||
|
||||
|
||||
def _cleanup():
|
||||
now = time.time()
|
||||
for sid in list(_sessions):
|
||||
if now - _sessions[sid]["created"] > _MAX_AGE:
|
||||
shutil.rmtree(_sessions[sid]["path"], ignore_errors=True)
|
||||
del _sessions[sid]
|
||||
|
||||
|
||||
def _get_session(session_id: str) -> dict:
|
||||
if session_id not in _sessions:
|
||||
raise HTTPException(410, "Сессия истекла, загрузите файлы заново")
|
||||
return _sessions[session_id]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Request/Response models
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class AnalyzeRequest(BaseModel):
|
||||
session_id: str
|
||||
search_column: str
|
||||
search_keyword: str
|
||||
source_sheet: str | None = None
|
||||
value_column: str | None = None
|
||||
|
||||
|
||||
class PreviewRequest(BaseModel):
|
||||
session_id: str
|
||||
search_keyword: str
|
||||
search_column: str
|
||||
value_column: str
|
||||
source_sheet: str | None = None
|
||||
target_sheet: str | None = None
|
||||
match_column: str
|
||||
target_write_column: str
|
||||
action: str = "sum"
|
||||
unmatched: str = "add"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload(zip_file: UploadFile = File(...), target_file: UploadFile = File(...)):
|
||||
"""Upload ZIP with sources + target xlsx. Returns session_id and file info."""
|
||||
_cleanup()
|
||||
|
||||
# Validate file types
|
||||
if not zip_file.filename.lower().endswith(".zip"):
|
||||
raise HTTPException(400, "Ожидается ZIP-архив с xlsx-источниками")
|
||||
if not target_file.filename.lower().endswith(".xlsx"):
|
||||
raise HTTPException(400, "Целевой файл должен быть .xlsx")
|
||||
|
||||
# Create session
|
||||
sid = uuid.uuid4().hex[:12]
|
||||
tmp = Path(tempfile.mkdtemp(prefix=f"wizard_{sid}_"))
|
||||
sources_dir = tmp / "sources"
|
||||
sources_dir.mkdir()
|
||||
|
||||
# Save files
|
||||
zip_path = tmp / "sources.zip"
|
||||
target_path = tmp / "target.xlsx"
|
||||
with open(zip_path, "wb") as f:
|
||||
shutil.copyfileobj(zip_file.file, f)
|
||||
with open(target_path, "wb") as f:
|
||||
shutil.copyfileobj(target_file.file, f)
|
||||
|
||||
# Analyze
|
||||
try:
|
||||
source_infos = analyze_zip(zip_path, sources_dir)
|
||||
except Exception as e:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
raise HTTPException(400, f"Ошибка чтения ZIP: {e}")
|
||||
|
||||
if not source_infos:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
raise HTTPException(400, "ZIP не содержит xlsx-файлов")
|
||||
|
||||
try:
|
||||
target_info = analyze_xlsx(target_path)
|
||||
except Exception as e:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
raise HTTPException(400, f"Ошибка чтения целевого файла: {e}")
|
||||
|
||||
_sessions[sid] = {
|
||||
"path": tmp,
|
||||
"created": time.time(),
|
||||
"sources_dir": str(sources_dir),
|
||||
"target_path": str(target_path),
|
||||
"target_filename": target_file.filename,
|
||||
}
|
||||
|
||||
def _file_info_to_dict(fi):
|
||||
return {
|
||||
"filename": fi.filename,
|
||||
"sheets": [
|
||||
{
|
||||
"name": s.name,
|
||||
"row_count": s.row_count,
|
||||
"header_row": s.header_row,
|
||||
"columns": [
|
||||
{"letter": c.letter, "header": c.header, "type": c.col_type}
|
||||
for c in s.columns
|
||||
],
|
||||
}
|
||||
for s in fi.sheets
|
||||
],
|
||||
}
|
||||
|
||||
return {
|
||||
"session_id": sid,
|
||||
"sources": [_file_info_to_dict(si) for si in source_infos],
|
||||
"target": _file_info_to_dict(target_info),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze(req: AnalyzeRequest):
|
||||
"""Search for keyword in sources, return matching rows for preview."""
|
||||
sess = _get_session(req.session_id)
|
||||
results = search_in_sources(
|
||||
sess["sources_dir"],
|
||||
req.source_sheet,
|
||||
req.search_column,
|
||||
req.search_keyword,
|
||||
req.value_column,
|
||||
max_rows=30,
|
||||
)
|
||||
# Unique keys
|
||||
keys = sorted(
|
||||
set(r["key"] for r in results if r.get("key")),
|
||||
key=lambda x: float(x.replace(",", ".")),
|
||||
)
|
||||
return {
|
||||
"found_count": len(results),
|
||||
"sample_rows": results,
|
||||
"unique_keys": keys,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/preview")
|
||||
async def preview(req: PreviewRequest):
|
||||
"""Preview aggregation results without writing."""
|
||||
sess = _get_session(req.session_id)
|
||||
config = AggConfig(
|
||||
search_keyword=req.search_keyword,
|
||||
search_column=req.search_column,
|
||||
value_column=req.value_column,
|
||||
source_sheet=req.source_sheet,
|
||||
target_sheet=req.target_sheet,
|
||||
match_column=req.match_column,
|
||||
target_write_column=req.target_write_column,
|
||||
action=req.action,
|
||||
unmatched=req.unmatched,
|
||||
)
|
||||
matches = match_and_preview(sess["sources_dir"], sess["target_path"], config)
|
||||
updates = [m for m in matches if m.status == "update"]
|
||||
adds = [m for m in matches if m.status == "add"]
|
||||
return {
|
||||
"matches": [
|
||||
{
|
||||
"target_row": m.target_row,
|
||||
"target_label": m.target_label,
|
||||
"current_value": m.current_value,
|
||||
"new_value": m.new_value,
|
||||
"status": m.status,
|
||||
}
|
||||
for m in matches
|
||||
],
|
||||
"summary": {
|
||||
"updates": len(updates),
|
||||
"adds": len(adds),
|
||||
"total_new_value": round(sum(m.new_value for m in matches), 2),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.post("/run")
|
||||
async def run(req: PreviewRequest):
|
||||
"""Execute aggregation, return download URL."""
|
||||
sess = _get_session(req.session_id)
|
||||
config = AggConfig(
|
||||
search_keyword=req.search_keyword,
|
||||
search_column=req.search_column,
|
||||
value_column=req.value_column,
|
||||
source_sheet=req.source_sheet,
|
||||
target_sheet=req.target_sheet,
|
||||
match_column=req.match_column,
|
||||
target_write_column=req.target_write_column,
|
||||
action=req.action,
|
||||
unmatched=req.unmatched,
|
||||
)
|
||||
output_path = Path(sess["path"]) / "result.xlsx"
|
||||
result = run_aggregation(sess["target_path"], output_path, sess["sources_dir"], config)
|
||||
sess["output_path"] = str(output_path)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"download_url": f"/api/wizard/download/{req.session_id}",
|
||||
"stats": {
|
||||
"updated": result.updated,
|
||||
"added": result.added,
|
||||
"skipped": result.skipped,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/download/{session_id}")
|
||||
async def download(session_id: str):
|
||||
"""Download the result xlsx."""
|
||||
sess = _get_session(session_id)
|
||||
output = sess.get("output_path")
|
||||
if not output or not Path(output).exists():
|
||||
raise HTTPException(404, "Результат не найден. Сначала выполните агрегацию.")
|
||||
fname = f"result_{sess.get('target_filename', 'output.xlsx')}"
|
||||
return FileResponse(
|
||||
output,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
filename=fname,
|
||||
)
|
||||
@@ -0,0 +1,527 @@
|
||||
"""
|
||||
Core logic for xlsx aggregation wizard.
|
||||
|
||||
Pure functions — no HTTP, no sessions. Accepts paths, returns data.
|
||||
"""
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import zipfile
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
|
||||
def fix_zip_encoding(filename: str) -> str:
|
||||
"""Fix Cyrillic filenames in ZIP archives."""
|
||||
for enc in ("utf-8", "cp866"):
|
||||
try:
|
||||
return filename.encode("cp437").decode(enc)
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
continue
|
||||
return filename
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data models
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class ColumnInfo:
|
||||
letter: str # "A", "B", ...
|
||||
header: str # Header text or letter if no header
|
||||
col_type: str # "text" | "number" | "mixed" | "empty"
|
||||
|
||||
|
||||
@dataclass
|
||||
class SheetInfo:
|
||||
name: str
|
||||
columns: list[ColumnInfo]
|
||||
row_count: int
|
||||
header_row: int # 1-based
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileInfo:
|
||||
filename: str
|
||||
sheets: list[SheetInfo]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AggConfig:
|
||||
search_keyword: str # e.g. "разряд"
|
||||
search_column: str # e.g. "E"
|
||||
value_column: str # e.g. "K"
|
||||
source_sheet: str | None # None = first sheet
|
||||
target_sheet: str | None
|
||||
match_column: str # e.g. "C" in target
|
||||
target_write_column: str # e.g. "E" in target
|
||||
action: str # "sum" | "replace" | "max" | "min"
|
||||
unmatched: str # "add" | "skip"
|
||||
|
||||
|
||||
@dataclass
|
||||
class MatchRow:
|
||||
target_row: int | None # None = unmatched (new)
|
||||
target_label: str
|
||||
current_value: float | None
|
||||
new_value: float
|
||||
status: str # "update" | "add"
|
||||
|
||||
|
||||
@dataclass
|
||||
class AggResult:
|
||||
updated: int = 0
|
||||
added: int = 0
|
||||
skipped: int = 0
|
||||
details: list[MatchRow] = field(default_factory=list)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_RAZRYAD_RE = re.compile(r"разряд[а-яё]*\s*[-–—]?\s*(\d+[.,]?\d*)", re.IGNORECASE)
|
||||
|
||||
|
||||
def _extract_key(text: str, keyword: str) -> str | None:
|
||||
"""Extract matching key from text using keyword-based regex.
|
||||
|
||||
For "разряд" keyword: extracts the decimal number (e.g. "2,4" from "разряда 2,4").
|
||||
For other keywords: extracts any number following the keyword, or uses the full
|
||||
cell text (stripped) as key if no number found.
|
||||
"""
|
||||
if not text or not keyword:
|
||||
return None
|
||||
kw = keyword.lower()
|
||||
if kw not in text.lower():
|
||||
return None
|
||||
# Special handling for "разряд" — the primary use case
|
||||
m = _RAZRYAD_RE.search(text)
|
||||
if m:
|
||||
raw = m.group(1).replace(".", ",")
|
||||
if "," not in raw:
|
||||
raw = raw + ",0"
|
||||
return raw
|
||||
# Generic fallback: extract number after keyword
|
||||
generic_re = re.compile(
|
||||
re.escape(keyword) + r"[а-яёa-z]*\s*[-–—:]*\s*(\d+[.,]?\d*)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
m = generic_re.search(text)
|
||||
if m:
|
||||
return m.group(1).replace(".", ",")
|
||||
# Last resort: use full text as key
|
||||
return text.strip().lower()
|
||||
|
||||
|
||||
def _to_float(val) -> float | None:
|
||||
"""Convert cell value to float, handling strings with commas."""
|
||||
if val is None:
|
||||
return None
|
||||
if isinstance(val, (int, float)):
|
||||
return float(val)
|
||||
try:
|
||||
return float(str(val).replace(",", ".").replace(" ", "").replace("\xa0", ""))
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _col_letter_to_idx(letter: str) -> int:
|
||||
"""Convert column letter to 0-based index. A=0, B=1, ..., Z=25, AA=26."""
|
||||
result = 0
|
||||
for ch in letter.upper():
|
||||
result = result * 26 + (ord(ch) - ord("A") + 1)
|
||||
return result - 1
|
||||
|
||||
|
||||
def _idx_to_col_letter(idx: int) -> str:
|
||||
"""Convert 0-based index to column letter."""
|
||||
result = ""
|
||||
idx += 1
|
||||
while idx > 0:
|
||||
idx, rem = divmod(idx - 1, 26)
|
||||
result = chr(rem + ord("A")) + result
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Analysis
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _detect_header_row(ws, max_scan: int = 20) -> int:
|
||||
"""Find header row = row with most non-empty TEXT cells in first max_scan rows.
|
||||
|
||||
Skips rows that look like column-number rows (1, 2, 3, ...).
|
||||
"""
|
||||
best_row = 1
|
||||
best_score = 0
|
||||
for i, row in enumerate(ws.iter_rows(max_row=max_scan, values_only=True), 1):
|
||||
non_empty = [v for v in row if v is not None and str(v).strip()]
|
||||
if not non_empty:
|
||||
continue
|
||||
# Skip rows where all values are small sequential integers (column numbers)
|
||||
if all(isinstance(v, (int, float)) and v == int(v) and 0 < v <= 30 for v in non_empty):
|
||||
continue
|
||||
# Prefer rows with more text cells
|
||||
text_count = sum(1 for v in non_empty if isinstance(v, str) and len(v.strip()) > 1)
|
||||
score = text_count * 2 + len(non_empty)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_row = i
|
||||
return best_row
|
||||
|
||||
|
||||
def _analyze_sheet(ws, sheet_name: str) -> SheetInfo:
|
||||
"""Analyze a single worksheet."""
|
||||
rows_data = list(ws.iter_rows(values_only=True))
|
||||
if not rows_data:
|
||||
return SheetInfo(name=sheet_name, columns=[], row_count=0, header_row=1)
|
||||
|
||||
header_row_idx = _detect_header_row(ws) - 1 # 0-based
|
||||
max_cols = max(len(r) for r in rows_data) if rows_data else 0
|
||||
|
||||
columns = []
|
||||
for col_idx in range(min(max_cols, 26)): # Cap at Z
|
||||
letter = _idx_to_col_letter(col_idx)
|
||||
# Header
|
||||
header = ""
|
||||
if header_row_idx < len(rows_data) and col_idx < len(rows_data[header_row_idx]):
|
||||
hv = rows_data[header_row_idx][col_idx]
|
||||
if hv is not None:
|
||||
header = str(hv).strip()[:50]
|
||||
if not header:
|
||||
header = letter
|
||||
|
||||
# Detect type from data rows (after header)
|
||||
nums, texts, total = 0, 0, 0
|
||||
for r in rows_data[header_row_idx + 1:]:
|
||||
if col_idx >= len(r):
|
||||
continue
|
||||
v = r[col_idx]
|
||||
if v is None:
|
||||
continue
|
||||
total += 1
|
||||
if isinstance(v, (int, float)):
|
||||
nums += 1
|
||||
else:
|
||||
texts += 1
|
||||
|
||||
if total == 0:
|
||||
col_type = "empty"
|
||||
elif nums > total * 0.6:
|
||||
col_type = "number"
|
||||
elif texts > total * 0.6:
|
||||
col_type = "text"
|
||||
else:
|
||||
col_type = "mixed"
|
||||
|
||||
columns.append(ColumnInfo(letter=letter, header=header, col_type=col_type))
|
||||
|
||||
# Count data rows (non-empty after header)
|
||||
data_rows = 0
|
||||
for r in rows_data[header_row_idx + 1:]:
|
||||
if any(v is not None for v in r):
|
||||
data_rows += 1
|
||||
|
||||
return SheetInfo(
|
||||
name=sheet_name,
|
||||
columns=[c for c in columns if c.col_type != "empty"],
|
||||
row_count=data_rows,
|
||||
header_row=header_row_idx + 1,
|
||||
)
|
||||
|
||||
|
||||
def analyze_xlsx(xlsx_path: str | Path) -> FileInfo:
|
||||
"""Analyze an xlsx file: sheets, columns, headers, row counts."""
|
||||
path = Path(xlsx_path)
|
||||
wb = openpyxl.load_workbook(str(path), read_only=True, data_only=True)
|
||||
sheets = []
|
||||
for sn in wb.sheetnames:
|
||||
ws = wb[sn]
|
||||
sheets.append(_analyze_sheet(ws, sn))
|
||||
wb.close()
|
||||
return FileInfo(filename=path.name, sheets=sheets)
|
||||
|
||||
|
||||
def extract_zip(zip_path: str | Path, dest_dir: str | Path) -> list[Path]:
|
||||
"""Extract xlsx files from ZIP, return list of extracted paths."""
|
||||
dest = Path(dest_dir)
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
extracted = []
|
||||
with zipfile.ZipFile(str(zip_path)) as zf:
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
fixed_name = fix_zip_encoding(info.filename)
|
||||
# Only xlsx
|
||||
if not fixed_name.lower().endswith(".xlsx"):
|
||||
continue
|
||||
# Skip hidden/temp files
|
||||
basename = Path(fixed_name).name
|
||||
if basename.startswith("~") or basename.startswith("."):
|
||||
continue
|
||||
out_path = dest / basename
|
||||
with zf.open(info) as src, open(out_path, "wb") as dst:
|
||||
shutil.copyfileobj(src, dst)
|
||||
extracted.append(out_path)
|
||||
return sorted(extracted)
|
||||
|
||||
|
||||
def analyze_zip(zip_path: str | Path, dest_dir: str | Path) -> list[FileInfo]:
|
||||
"""Extract ZIP and analyze each xlsx file."""
|
||||
paths = extract_zip(zip_path, dest_dir)
|
||||
return [analyze_xlsx(p) for p in paths]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Search & Preview
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def search_in_sources(
|
||||
sources_dir: str | Path,
|
||||
sheet_name: str | None,
|
||||
search_col: str,
|
||||
keyword: str,
|
||||
value_col: str | None = None,
|
||||
max_rows: int = 20,
|
||||
) -> list[dict]:
|
||||
"""Search for keyword in sources, return matching rows for preview."""
|
||||
sources_dir = Path(sources_dir)
|
||||
col_idx = _col_letter_to_idx(search_col)
|
||||
val_idx = _col_letter_to_idx(value_col) if value_col else None
|
||||
results = []
|
||||
|
||||
for xlsx_path in sorted(sources_dir.glob("*.xlsx")):
|
||||
if xlsx_path.name.startswith("~"):
|
||||
continue
|
||||
wb = openpyxl.load_workbook(str(xlsx_path), read_only=True, data_only=True)
|
||||
sn = sheet_name or wb.sheetnames[0]
|
||||
if sn not in wb.sheetnames:
|
||||
wb.close()
|
||||
continue
|
||||
ws = wb[sn]
|
||||
for row_num, row in enumerate(ws.iter_rows(values_only=True), 1):
|
||||
if col_idx >= len(row):
|
||||
continue
|
||||
cell_val = row[col_idx]
|
||||
if cell_val is None:
|
||||
continue
|
||||
text = str(cell_val)
|
||||
if keyword.lower() not in text.lower():
|
||||
continue
|
||||
entry = {
|
||||
"file": xlsx_path.name,
|
||||
"row": row_num,
|
||||
"search_value": text[:80],
|
||||
"key": _extract_key(text, keyword),
|
||||
}
|
||||
if val_idx is not None and val_idx < len(row):
|
||||
entry["number_value"] = _to_float(row[val_idx])
|
||||
results.append(entry)
|
||||
if len(results) >= max_rows:
|
||||
wb.close()
|
||||
return results
|
||||
wb.close()
|
||||
return results
|
||||
|
||||
|
||||
def _collect_source_values(
|
||||
sources_dir: Path,
|
||||
sheet_name: str | None,
|
||||
search_col: str,
|
||||
keyword: str,
|
||||
value_col: str,
|
||||
) -> dict[str, float]:
|
||||
"""Collect all key->value pairs from sources. Sum duplicates."""
|
||||
col_idx = _col_letter_to_idx(search_col)
|
||||
val_idx = _col_letter_to_idx(value_col)
|
||||
aggregated: dict[str, float] = {}
|
||||
|
||||
for xlsx_path in sorted(sources_dir.glob("*.xlsx")):
|
||||
if xlsx_path.name.startswith("~"):
|
||||
continue
|
||||
wb = openpyxl.load_workbook(str(xlsx_path), read_only=True, data_only=True)
|
||||
sn = sheet_name or wb.sheetnames[0]
|
||||
if sn not in wb.sheetnames:
|
||||
wb.close()
|
||||
continue
|
||||
ws = wb[sn]
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
if col_idx >= len(row):
|
||||
continue
|
||||
cell_val = row[col_idx]
|
||||
if cell_val is None:
|
||||
continue
|
||||
key = _extract_key(str(cell_val), keyword)
|
||||
if key is None:
|
||||
continue
|
||||
val = _to_float(row[val_idx]) if val_idx < len(row) else None
|
||||
if val is not None:
|
||||
aggregated[key] = aggregated.get(key, 0.0) + val
|
||||
wb.close()
|
||||
return aggregated
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Match & Preview
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def match_and_preview(
|
||||
sources_dir: str | Path,
|
||||
target_path: str | Path,
|
||||
config: AggConfig,
|
||||
) -> list[MatchRow]:
|
||||
"""Match source data to target, return preview of changes."""
|
||||
sources_dir = Path(sources_dir)
|
||||
target_path = Path(target_path)
|
||||
|
||||
# Collect aggregated values from sources
|
||||
source_vals = _collect_source_values(
|
||||
sources_dir, config.source_sheet,
|
||||
config.search_column, config.search_keyword, config.value_column,
|
||||
)
|
||||
|
||||
# Read target
|
||||
wb = openpyxl.load_workbook(str(target_path), read_only=True, data_only=True)
|
||||
sn = config.target_sheet or wb.sheetnames[0]
|
||||
ws = wb[sn]
|
||||
match_idx = _col_letter_to_idx(config.match_column)
|
||||
write_idx = _col_letter_to_idx(config.target_write_column)
|
||||
|
||||
matched_keys = set()
|
||||
results = []
|
||||
|
||||
for row_num, row in enumerate(ws.iter_rows(values_only=True), 1):
|
||||
if match_idx >= len(row):
|
||||
continue
|
||||
cell_val = row[match_idx]
|
||||
if cell_val is None:
|
||||
continue
|
||||
key = _extract_key(str(cell_val), config.search_keyword)
|
||||
if key is None:
|
||||
continue
|
||||
current = _to_float(row[write_idx]) if write_idx < len(row) else None
|
||||
source_val = source_vals.get(key)
|
||||
if source_val is not None:
|
||||
matched_keys.add(key)
|
||||
new_val = _apply_action(config.action, current, source_val)
|
||||
results.append(MatchRow(
|
||||
target_row=row_num,
|
||||
target_label=str(cell_val).strip(),
|
||||
current_value=current,
|
||||
new_value=round(new_val, 6),
|
||||
status="update",
|
||||
))
|
||||
|
||||
# Unmatched keys from sources
|
||||
if config.unmatched == "add":
|
||||
for key in sorted(source_vals.keys()):
|
||||
if key not in matched_keys:
|
||||
results.append(MatchRow(
|
||||
target_row=None,
|
||||
target_label=f"Разряд - {key}",
|
||||
current_value=None,
|
||||
new_value=round(source_vals[key], 6),
|
||||
status="add",
|
||||
))
|
||||
|
||||
wb.close()
|
||||
return results
|
||||
|
||||
|
||||
def _apply_action(action: str, current: float | None, source: float) -> float:
|
||||
cur = current or 0.0
|
||||
if action == "sum":
|
||||
return cur + source
|
||||
elif action == "replace":
|
||||
return source
|
||||
elif action == "max":
|
||||
return max(cur, source)
|
||||
elif action == "min":
|
||||
return min(cur, source) if current is not None else source
|
||||
return source
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Run aggregation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def run_aggregation(
|
||||
target_path: str | Path,
|
||||
output_path: str | Path,
|
||||
sources_dir: str | Path,
|
||||
config: AggConfig,
|
||||
) -> AggResult:
|
||||
"""Execute aggregation: write values into target xlsx, save to output_path."""
|
||||
sources_dir = Path(sources_dir)
|
||||
target_path = Path(target_path)
|
||||
output_path = Path(output_path)
|
||||
|
||||
# Copy target to output
|
||||
shutil.copy2(str(target_path), str(output_path))
|
||||
|
||||
# Collect source values
|
||||
source_vals = _collect_source_values(
|
||||
sources_dir, config.source_sheet,
|
||||
config.search_column, config.search_keyword, config.value_column,
|
||||
)
|
||||
|
||||
# Open for writing (not read_only)
|
||||
wb = openpyxl.load_workbook(str(output_path))
|
||||
sn = config.target_sheet or wb.sheetnames[0]
|
||||
ws = wb[sn]
|
||||
match_idx = _col_letter_to_idx(config.match_column)
|
||||
write_col = _col_letter_to_idx(config.target_write_column) + 1 # 1-based for ws.cell
|
||||
|
||||
matched_keys = set()
|
||||
result = AggResult()
|
||||
|
||||
for row_cells in ws.iter_rows(min_row=1, max_row=ws.max_row):
|
||||
cell_match = row_cells[match_idx] if match_idx < len(row_cells) else None
|
||||
if cell_match is None or cell_match.value is None:
|
||||
continue
|
||||
key = _extract_key(str(cell_match.value), config.search_keyword)
|
||||
if key is None:
|
||||
continue
|
||||
source_val = source_vals.get(key)
|
||||
if source_val is None:
|
||||
continue
|
||||
|
||||
matched_keys.add(key)
|
||||
row_num = cell_match.row
|
||||
current = _to_float(ws.cell(row=row_num, column=write_col).value)
|
||||
new_val = _apply_action(config.action, current, source_val)
|
||||
ws.cell(row=row_num, column=write_col, value=round(new_val, 6))
|
||||
result.updated += 1
|
||||
result.details.append(MatchRow(
|
||||
target_row=row_num,
|
||||
target_label=str(cell_match.value).strip(),
|
||||
current_value=current,
|
||||
new_value=round(new_val, 6),
|
||||
status="update",
|
||||
))
|
||||
|
||||
# Add unmatched
|
||||
if config.unmatched == "add":
|
||||
next_row = ws.max_row + 1
|
||||
for key in sorted(source_vals.keys()):
|
||||
if key not in matched_keys:
|
||||
ws.cell(row=next_row, column=_col_letter_to_idx(config.match_column) + 1,
|
||||
value=f"Разряд - {key}")
|
||||
ws.cell(row=next_row, column=write_col, value=round(source_vals[key], 6))
|
||||
result.added += 1
|
||||
result.details.append(MatchRow(
|
||||
target_row=next_row,
|
||||
target_label=f"Разряд - {key}",
|
||||
current_value=None,
|
||||
new_value=round(source_vals[key], 6),
|
||||
status="add",
|
||||
))
|
||||
next_row += 1
|
||||
|
||||
result.skipped = len(source_vals) - len(matched_keys) - result.added
|
||||
wb.save(str(output_path))
|
||||
wb.close()
|
||||
return result
|
||||
Reference in New Issue
Block a user