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:
anor
2026-03-30 16:30:53 +10:00
co-authored by Claude Opus 4.6
parent 46e14e4e62
commit 53236e80f5
6 changed files with 1282 additions and 0 deletions
+1
View File
@@ -17,6 +17,7 @@ dependencies = [
[project.optional-dependencies]
dev = ["pytest>=8.0"]
ai = ["faiss-cpu>=1.7", "openai>=1.0"]
web = ["fastapi>=0.115", "uvicorn[standard]>=0.32", "python-multipart>=0.0.12"]
[project.scripts]
smeta = "smeta_railway.cli:app"
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""
Wizard-aggregator web server.
Usage:
python scripts/wizard_server.py
# Open http://localhost:8102/wizard.html
"""
import sys
from pathlib import Path
# Ensure src/ is on path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from smeta_railway.web.wizard_api import router
app = FastAPI(title="Smeta Wizard Aggregator")
app.include_router(router, prefix="/api/wizard")
# Serve static files (wizard.html)
static_dir = Path(__file__).resolve().parent.parent / "static"
app.mount("/", StaticFiles(directory=str(static_dir), html=True), name="static")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8102)
View File
+256
View File
@@ -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,
)
+527
View File
@@ -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
+467
View File
@@ -0,0 +1,467 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wizard — Агрегатор xlsx</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background: #f5f6fa; }
.wizard-container { max-width: 900px; margin: 30px auto; }
.step { display: none; }
.step.active { display: block; }
.step-indicators { display: flex; gap: 4px; margin-bottom: 20px; }
.step-ind { flex: 1; height: 6px; border-radius: 3px; background: #dee2e6; transition: background .3s; }
.step-ind.done { background: #198754; }
.step-ind.current { background: #0d6efd; }
.preview-table { max-height: 350px; overflow-y: auto; font-size: 0.85rem; }
.preview-table td, .preview-table th { white-space: nowrap; }
.status-add { color: #198754; font-weight: 600; }
.status-update { color: #0d6efd; }
.file-list { font-size: 0.9rem; }
.spinner-sm { width: 1rem; height: 1rem; }
</style>
</head>
<body>
<div class="wizard-container">
<h4 class="mb-3">Агрегатор xlsx</h4>
<!-- Step indicators -->
<div class="step-indicators" id="stepIndicators"></div>
<!-- Step 1: Upload -->
<div class="step active" id="step1">
<div class="card">
<div class="card-body">
<h5 class="card-title">Шаг 1. Загрузка файлов</h5>
<div class="mb-3">
<label class="form-label">ZIP-архив с источниками (.xlsx)</label>
<input type="file" class="form-control" id="zipFile" accept=".zip">
</div>
<div class="mb-3">
<label class="form-label">Целевой файл (.xlsx)</label>
<input type="file" class="form-control" id="targetFile" accept=".xlsx">
</div>
<button class="btn btn-primary" onclick="uploadFiles()">
<span id="uploadSpinner" class="spinner-border spinner-sm d-none" role="status"></span>
Загрузить
</button>
<div id="uploadError" class="text-danger mt-2"></div>
<div id="uploadResult" class="mt-3"></div>
</div>
</div>
</div>
<!-- Step 2: Search criterion -->
<div class="step" id="step2">
<div class="card">
<div class="card-body">
<h5 class="card-title">Шаг 2. Критерий поиска в источниках</h5>
<div class="row mb-3">
<div class="col-md-4">
<label class="form-label">Лист источника</label>
<select class="form-select" id="sourceSheet"></select>
</div>
<div class="col-md-4">
<label class="form-label">Искать в колонке</label>
<select class="form-select" id="searchColumn"></select>
</div>
<div class="col-md-4">
<label class="form-label">Ключевое слово</label>
<input type="text" class="form-control" id="searchKeyword" value="разряд">
</div>
</div>
<button class="btn btn-outline-primary btn-sm" onclick="doAnalyze()">Найти</button>
<div id="searchPreview" class="mt-3"></div>
</div>
</div>
</div>
<!-- Step 3: Value column -->
<div class="step" id="step3">
<div class="card">
<div class="card-body">
<h5 class="card-title">Шаг 3. Колонка значений в источниках</h5>
<div class="mb-3">
<label class="form-label">Из какой колонки брать числа?</label>
<select class="form-select" id="valueColumn"></select>
</div>
<button class="btn btn-outline-primary btn-sm" onclick="doAnalyzeWithValue()">Показать превью</button>
<div id="valuePreview" class="mt-3"></div>
</div>
</div>
</div>
<!-- Step 4: Target matching -->
<div class="step" id="step4">
<div class="card">
<div class="card-body">
<h5 class="card-title">Шаг 4. Сопоставление с целевым</h5>
<div class="row mb-3">
<div class="col-md-4">
<label class="form-label">Лист целевого</label>
<select class="form-select" id="targetSheet"></select>
</div>
<div class="col-md-4">
<label class="form-label">Колонка сопоставления</label>
<select class="form-select" id="matchColumn"></select>
</div>
</div>
<p id="matchInfo" class="text-muted"></p>
</div>
</div>
</div>
<!-- Step 5: Action -->
<div class="step" id="step5">
<div class="card">
<div class="card-body">
<h5 class="card-title">Шаг 5. Действие</h5>
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">Операция</label>
<select class="form-select" id="actionType">
<option value="sum" selected>Суммировать</option>
<option value="replace">Заменить</option>
<option value="max">Максимум</option>
<option value="min">Минимум</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Записать в колонку</label>
<select class="form-select" id="targetWriteColumn"></select>
</div>
</div>
</div>
</div>
</div>
<!-- Step 6: Unmatched -->
<div class="step" id="step6">
<div class="card">
<div class="card-body">
<h5 class="card-title">Шаг 6. Ненайденные строки</h5>
<div class="mb-3">
<label class="form-label">Если в целевом не найден ключ:</label>
<select class="form-select" id="unmatchedAction">
<option value="add" selected>Добавить новые строки</option>
<option value="skip">Пропустить</option>
</select>
</div>
</div>
</div>
</div>
<!-- Step 7: Preview & Run -->
<div class="step" id="step7">
<div class="card">
<div class="card-body">
<h5 class="card-title">Шаг 7. Превью и подтверждение</h5>
<div id="previewLoading" class="text-center py-3 d-none">
<div class="spinner-border text-primary" role="status"></div>
<p class="mt-2">Вычисляю...</p>
</div>
<div id="previewResult"></div>
<div id="previewSummary" class="mt-3"></div>
<button class="btn btn-success mt-3 d-none" id="runBtn" onclick="runAggregation()">
<span id="runSpinner" class="spinner-border spinner-sm d-none" role="status"></span>
Применить и скачать
</button>
<div id="runResult" class="mt-3"></div>
</div>
</div>
</div>
<!-- Navigation -->
<div class="d-flex justify-content-between mt-3">
<button class="btn btn-outline-secondary" id="prevBtn" onclick="prevStep()" disabled>Назад</button>
<button class="btn btn-primary" id="nextBtn" onclick="nextStep()" disabled>Далее</button>
</div>
</div>
<script>
const TOTAL_STEPS = 7;
let currentStep = 1;
let sessionId = null;
let sourceData = null;
let targetData = null;
// --- Navigation ---
function updateStepUI() {
for (let i = 1; i <= TOTAL_STEPS; i++) {
document.getElementById('step' + i).classList.toggle('active', i === currentStep);
}
document.getElementById('prevBtn').disabled = currentStep === 1;
document.getElementById('nextBtn').disabled = !canProceed();
// Indicators
const ind = document.getElementById('stepIndicators');
ind.innerHTML = '';
for (let i = 1; i <= TOTAL_STEPS; i++) {
const cls = i < currentStep ? 'done' : i === currentStep ? 'current' : '';
ind.innerHTML += `<div class="step-ind ${cls}"></div>`;
}
// Auto-actions on step enter
if (currentStep === 7) loadPreview();
}
function canProceed() {
if (currentStep === 1) return !!sessionId;
if (currentStep === 2) return document.getElementById('searchColumn').value !== '';
if (currentStep === 3) return document.getElementById('valueColumn').value !== '';
if (currentStep === 4) return document.getElementById('matchColumn').value !== '';
if (currentStep === 5) return true;
if (currentStep === 6) return true;
return false;
}
function nextStep() {
if (currentStep < TOTAL_STEPS) { currentStep++; updateStepUI(); }
}
function prevStep() {
if (currentStep > 1) { currentStep--; updateStepUI(); }
}
// --- Step 1: Upload ---
async function uploadFiles() {
const zipFile = document.getElementById('zipFile').files[0];
const targetFile = document.getElementById('targetFile').files[0];
if (!zipFile || !targetFile) {
document.getElementById('uploadError').textContent = 'Выберите оба файла';
return;
}
document.getElementById('uploadSpinner').classList.remove('d-none');
document.getElementById('uploadError').textContent = '';
const fd = new FormData();
fd.append('zip_file', zipFile);
fd.append('target_file', targetFile);
try {
const resp = await fetch('/api/wizard/upload', { method: 'POST', body: fd });
if (!resp.ok) {
const err = await resp.json();
throw new Error(err.detail || 'Upload failed');
}
const data = await resp.json();
sessionId = data.session_id;
sourceData = data.sources;
targetData = data.target;
// Show summary
let html = '<div class="file-list">';
html += `<p><strong>Источники:</strong> ${sourceData.length} файл(ов)</p><ul>`;
for (const s of sourceData) {
html += `<li>${s.filename} — ${s.sheets.map(sh => sh.name + ' (' + sh.row_count + ' строк)').join(', ')}</li>`;
}
html += `</ul><p><strong>Целевой:</strong> ${targetData.filename}</p><ul>`;
for (const sh of targetData.sheets) {
html += `<li>${sh.name} — ${sh.row_count} строк, ${sh.columns.length} колонок</li>`;
}
html += '</ul></div>';
document.getElementById('uploadResult').innerHTML = html;
// Populate step 2 dropdowns
populateSourceDropdowns();
populateTargetDropdowns();
updateStepUI();
} catch (e) {
document.getElementById('uploadError').textContent = e.message;
} finally {
document.getElementById('uploadSpinner').classList.add('d-none');
}
}
function populateSourceDropdowns() {
// Source sheet
const sheetSel = document.getElementById('sourceSheet');
sheetSel.innerHTML = '';
const allSheets = new Set();
for (const s of sourceData) {
for (const sh of s.sheets) allSheets.add(sh.name);
}
for (const name of allSheets) {
sheetSel.innerHTML += `<option value="${name}">${name}</option>`;
}
// Source columns (from first source, first sheet)
const firstSheet = sourceData[0].sheets[0];
const colSel = document.getElementById('searchColumn');
const valSel = document.getElementById('valueColumn');
colSel.innerHTML = '';
valSel.innerHTML = '';
for (const c of firstSheet.columns) {
const label = `${c.letter}: ${c.header} (${c.type})`;
colSel.innerHTML += `<option value="${c.letter}" ${c.type === 'text' ? 'selected' : ''}>${label}</option>`;
valSel.innerHTML += `<option value="${c.letter}" ${c.type === 'number' ? 'selected' : ''}>${label}</option>`;
}
// Auto-select: prefer columns with meaningful headers
const textCols = firstSheet.columns.filter(c => c.type === 'text');
const numCols = firstSheet.columns.filter(c => c.type === 'number');
// Search column: prefer "Наименование" or first text column
const nameLike = textCols.find(c => /наименован|название/i.test(c.header));
if (nameLike) colSel.value = nameLike.letter;
else if (textCols.length) colSel.value = textCols[0].letter;
// Value column: prefer "Количество" / "Кол-во" or first number column
const qtyLike = numCols.find(c => /количеств|кол-во|кол\.во/i.test(c.header));
if (qtyLike) valSel.value = qtyLike.letter;
else if (numCols.length) valSel.value = numCols[0].letter;
}
function populateTargetDropdowns() {
const sheetSel = document.getElementById('targetSheet');
const matchSel = document.getElementById('matchColumn');
const writeSel = document.getElementById('targetWriteColumn');
sheetSel.innerHTML = '';
matchSel.innerHTML = '';
writeSel.innerHTML = '';
for (const sh of targetData.sheets) {
sheetSel.innerHTML += `<option value="${sh.name}">${sh.name}</option>`;
}
const firstSheet = targetData.sheets[0];
for (const c of firstSheet.columns) {
const label = `${c.letter}: ${c.header} (${c.type})`;
matchSel.innerHTML += `<option value="${c.letter}">${label}</option>`;
writeSel.innerHTML += `<option value="${c.letter}">${label}</option>`;
}
// Auto-select: prefer "Наименование" for match, "Количество" for write
const textCols = firstSheet.columns.filter(c => c.type === 'text');
const numCols = firstSheet.columns.filter(c => c.type === 'number');
const nameLike = textCols.find(c => /наименован|название/i.test(c.header));
if (nameLike) matchSel.value = nameLike.letter;
else if (textCols.length) matchSel.value = textCols[0].letter;
const qtyLike = numCols.find(c => /количеств|кол-во|кол\.во/i.test(c.header));
if (qtyLike) writeSel.value = qtyLike.letter;
else if (numCols.length) writeSel.value = numCols[0].letter;
}
// --- Step 2: Analyze ---
async function doAnalyze() {
const resp = await fetch('/api/wizard/analyze', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
session_id: sessionId,
search_column: document.getElementById('searchColumn').value,
search_keyword: document.getElementById('searchKeyword').value,
source_sheet: document.getElementById('sourceSheet').value,
}),
});
const data = await resp.json();
let html = `<p>Найдено строк: <strong>${data.found_count}</strong>, уникальных ключей: <strong>${data.unique_keys.length}</strong></p>`;
if (data.sample_rows.length) {
html += '<div class="preview-table"><table class="table table-sm table-striped"><thead><tr><th>Файл</th><th>Строка</th><th>Текст</th><th>Ключ</th></tr></thead><tbody>';
for (const r of data.sample_rows.slice(0, 15)) {
html += `<tr><td>${r.file}</td><td>${r.row}</td><td>${r.search_value}</td><td>${r.key || '-'}</td></tr>`;
}
html += '</tbody></table></div>';
}
document.getElementById('searchPreview').innerHTML = html;
updateStepUI();
}
// --- Step 3: Analyze with value column ---
async function doAnalyzeWithValue() {
const resp = await fetch('/api/wizard/analyze', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
session_id: sessionId,
search_column: document.getElementById('searchColumn').value,
search_keyword: document.getElementById('searchKeyword').value,
source_sheet: document.getElementById('sourceSheet').value,
value_column: document.getElementById('valueColumn').value,
}),
});
const data = await resp.json();
let html = '';
if (data.sample_rows.length) {
html += '<div class="preview-table"><table class="table table-sm table-striped"><thead><tr><th>Файл</th><th>Ключ</th><th>Значение</th></tr></thead><tbody>';
for (const r of data.sample_rows.slice(0, 10)) {
html += `<tr><td>${r.file}</td><td>${r.key || '-'}</td><td>${r.number_value != null ? r.number_value.toFixed(2) : '-'}</td></tr>`;
}
html += '</tbody></table></div>';
}
document.getElementById('valuePreview').innerHTML = html;
}
// --- Step 7: Preview ---
async function loadPreview() {
document.getElementById('previewLoading').classList.remove('d-none');
document.getElementById('previewResult').innerHTML = '';
document.getElementById('previewSummary').innerHTML = '';
document.getElementById('runBtn').classList.add('d-none');
const body = buildConfig();
try {
const resp = await fetch('/api/wizard/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const data = await resp.json();
let html = '<div class="preview-table"><table class="table table-sm table-striped"><thead><tr><th>Статус</th><th>Строка</th><th>Название</th><th>Было</th><th>Станет</th></tr></thead><tbody>';
for (const m of data.matches) {
const cls = m.status === 'add' ? 'status-add' : 'status-update';
const label = m.status === 'add' ? 'НОВЫЙ' : 'обновл.';
html += `<tr><td class="${cls}">${label}</td><td>${m.target_row || '—'}</td><td>${m.target_label}</td><td>${m.current_value != null ? m.current_value.toFixed(2) : '—'}</td><td>${m.new_value.toFixed(2)}</td></tr>`;
}
html += '</tbody></table></div>';
document.getElementById('previewResult').innerHTML = html;
const s = data.summary;
document.getElementById('previewSummary').innerHTML =
`<span class="badge bg-primary">${s.updates} обновлений</span> ` +
`<span class="badge bg-success">${s.adds} новых</span> ` +
`<span class="badge bg-secondary">Итого: ${s.total_new_value.toFixed(2)}</span>`;
if (data.matches.length > 0) {
document.getElementById('runBtn').classList.remove('d-none');
}
} finally {
document.getElementById('previewLoading').classList.add('d-none');
}
}
// --- Run ---
async function runAggregation() {
document.getElementById('runSpinner').classList.remove('d-none');
const body = buildConfig();
try {
const resp = await fetch('/api/wizard/run', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const data = await resp.json();
if (data.success) {
document.getElementById('runResult').innerHTML =
`<div class="alert alert-success">Готово! Обновлено: ${data.stats.updated}, добавлено: ${data.stats.added}` +
`<br><a href="${data.download_url}" class="btn btn-outline-success btn-sm mt-2">Скачать результат</a></div>`;
}
} finally {
document.getElementById('runSpinner').classList.add('d-none');
}
}
function buildConfig() {
return {
session_id: sessionId,
search_keyword: document.getElementById('searchKeyword').value,
search_column: document.getElementById('searchColumn').value,
value_column: document.getElementById('valueColumn').value,
source_sheet: document.getElementById('sourceSheet').value || null,
target_sheet: document.getElementById('targetSheet').value || null,
match_column: document.getElementById('matchColumn').value,
target_write_column: document.getElementById('targetWriteColumn').value,
action: document.getElementById('actionType').value,
unmatched: document.getElementById('unmatchedAction').value,
};
}
// Init
updateStepUI();
</script>
</body>
</html>