feat: интеграция smeta-railway — агрегатор, генерация, справочники, проверка
Новые страницы: - /wizard — агрегатор xlsx (7-шаговый мастер) - /generate — генерация сметы из описания работ (4 шага → Excel) - /reference — справочники НР/СП/ГЭСН - /check — проверка YAML-конфига сметы Используют smeta-railway как библиотеку (wizard_api, generator_api, chat_api, checker). Кнопки добавлены в header чата. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -988,6 +988,162 @@ async def ssr_download(job_id: str, request: Request):
|
||||
return FileResponse(job["xlsx_path"], filename="ssr_generated.xlsx")
|
||||
|
||||
|
||||
# ── Wizard Aggregator ──────────────────────────────────────────────────────
|
||||
|
||||
def _import_smeta_railway():
|
||||
"""Ensure smeta-railway src/ is importable."""
|
||||
import sys
|
||||
for src_dir in [
|
||||
str(Path(__file__).resolve().parent / ".." / "smeta-railway" / "src"),
|
||||
str(Path.home() / "smeta-railway" / "src"),
|
||||
]:
|
||||
if Path(src_dir).exists() and src_dir not in sys.path:
|
||||
sys.path.insert(0, src_dir)
|
||||
|
||||
_import_smeta_railway()
|
||||
|
||||
|
||||
@app.get("/wizard", response_class=HTMLResponse)
|
||||
async def wizard_page():
|
||||
return Path("static/wizard.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# Import and mount smeta-railway routers
|
||||
from smeta_railway.web.wizard_api import router as _wizard_router
|
||||
from smeta_railway.web.generator_api import router as _gen_router
|
||||
from smeta_railway.web.chat_api import router as _chat_sr_router
|
||||
|
||||
app.include_router(_wizard_router, prefix="/api/wizard")
|
||||
app.include_router(_gen_router, prefix="/api/gen")
|
||||
app.include_router(_chat_sr_router, prefix="/api/ref") # /api/ref/search, /api/ref/nr, /api/ref/sp
|
||||
|
||||
|
||||
@app.get("/generate", response_class=HTMLResponse)
|
||||
async def generate_page():
|
||||
return Path("static/generate.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.get("/reference", response_class=HTMLResponse)
|
||||
async def reference_page():
|
||||
return Path("static/reference.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── Estimate Checker ──────────────────────────────────────────────────────
|
||||
|
||||
@app.get("/check", response_class=HTMLResponse)
|
||||
async def check_page():
|
||||
return Path("static/check.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.post("/api/check/yaml")
|
||||
async def check_yaml_endpoint(request: Request):
|
||||
"""Validate YAML config and return check report."""
|
||||
import tempfile
|
||||
from smeta_railway.ai.checker import check_yaml_config, format_report
|
||||
|
||||
body = await request.json()
|
||||
yaml_content = body.get("yaml", "")
|
||||
if not yaml_content.strip():
|
||||
raise HTTPException(400, "Empty YAML")
|
||||
|
||||
# Write to temp file for checker
|
||||
with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f:
|
||||
f.write(yaml_content)
|
||||
tmp_path = f.name
|
||||
|
||||
try:
|
||||
report = check_yaml_config(tmp_path)
|
||||
return {
|
||||
"errors": report.errors,
|
||||
"warnings": report.warnings,
|
||||
"info": report.info,
|
||||
"results": [
|
||||
{"level": r.level, "code": r.code, "message": r.message, "position": r.position}
|
||||
for r in report.results
|
||||
],
|
||||
"formatted": format_report(report),
|
||||
}
|
||||
except Exception as exc:
|
||||
return {"error": str(exc), "results": []}
|
||||
finally:
|
||||
Path(tmp_path).unlink(missing_ok=True)
|
||||
|
||||
|
||||
# ── Full Pipeline: YAML → Calculate → Excel ───────────────────────────────
|
||||
|
||||
@app.post("/api/gen/calculate")
|
||||
async def calculate_estimate(request: Request):
|
||||
"""Take YAML config, run calculation, generate Excel, return download link."""
|
||||
import tempfile
|
||||
import yaml as pyyaml
|
||||
|
||||
body = await request.json()
|
||||
yaml_str = body.get("yaml", "")
|
||||
if not yaml_str.strip():
|
||||
raise HTTPException(400, "Empty YAML")
|
||||
|
||||
try:
|
||||
from smeta_railway.config import ProjectConfig
|
||||
from smeta_railway.calc.estimate import EstimateCalculator
|
||||
from smeta_railway.data.fgis import FGISLookup
|
||||
from smeta_railway.output.excel_se import write_excel
|
||||
from smeta_railway.models import NormResources
|
||||
|
||||
# Parse config
|
||||
config = ProjectConfig.from_yaml_string(yaml_str)
|
||||
|
||||
# Load resources
|
||||
resources_path = Path(__file__).resolve().parent / ".." / "smeta-railway" / "resources.json"
|
||||
if not resources_path.exists():
|
||||
resources_path = Path.home() / "smeta-railway" / "resources.json"
|
||||
if not resources_path.exists():
|
||||
return {"error": "resources.json не найден — расчёт невозможен", "download_url": None}
|
||||
|
||||
import json as _json
|
||||
raw = _json.loads(resources_path.read_text(encoding="utf-8"))
|
||||
resources = {k: NormResources.from_dict(v) for k, v in raw.items()}
|
||||
|
||||
# FGIS lookup
|
||||
fgis = FGISLookup(region=config.region)
|
||||
|
||||
# Calculate
|
||||
calc = EstimateCalculator(
|
||||
fgis=fgis,
|
||||
resources=resources,
|
||||
coeff_config=config.coefficients,
|
||||
overhead_config=config.overhead,
|
||||
limited_costs_config=config.limited_costs,
|
||||
)
|
||||
result = calc.calculate(config.sections)
|
||||
|
||||
# Write Excel
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
xlsx_path = data_dir / f"estimate_{job_id}.xlsx"
|
||||
write_excel(result, str(xlsx_path), config)
|
||||
|
||||
return {
|
||||
"download_url": f"/api/gen/download/{job_id}",
|
||||
"positions": len(result.positions),
|
||||
"total": result.total if hasattr(result, "total") else None,
|
||||
"error": None,
|
||||
}
|
||||
except Exception as exc:
|
||||
import traceback
|
||||
return {"error": str(exc), "detail": traceback.format_exc()[-500:], "download_url": None}
|
||||
|
||||
|
||||
@app.get("/api/gen/download/{job_id}")
|
||||
async def download_estimate(job_id: str):
|
||||
"""Download generated Excel estimate."""
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
|
||||
xlsx_path = data_dir / f"estimate_{job_id}.xlsx"
|
||||
if not xlsx_path.exists():
|
||||
raise HTTPException(404, "Файл не найден")
|
||||
return FileResponse(str(xlsx_path), filename=f"smeta_{job_id}.xlsx")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|
||||
|
||||
+4
-1
@@ -122,7 +122,10 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
|
||||
<button id="btn-admin" style="display:none" onclick="window.open('/admin','_blank')">Админ</button>
|
||||
<button onclick="window.open('/batch3','_blank')">Пакетная</button>
|
||||
<button onclick="window.open('/ssr','_blank')">ССР</button>
|
||||
<button onclick="window.open('/wizard.html','_blank')">Wizard</button>
|
||||
<button onclick="window.open('/wizard','_blank')">Агрегатор</button>
|
||||
<button onclick="window.open('/generate','_blank')">Генерация</button>
|
||||
<button onclick="window.open('/reference','_blank')">Справочники</button>
|
||||
<button onclick="window.open('/check','_blank')">Проверка</button>
|
||||
<button onclick="showSessions()">История</button>
|
||||
<button onclick="resetSession()">Новый диалог</button>
|
||||
<button onclick="listFiles()">Файлы</button>
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Проверка сметы</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .82rem; font-family: 'SF Mono', Menlo, monospace; background: var(--bg); outline: none; resize: vertical; min-height: 200px; }
|
||||
textarea:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; background: var(--accent); color: #fff; }
|
||||
.btn:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.result-item { padding: 8px 12px; border-radius: var(--radius); margin-bottom: 6px; font-size: .88rem; display: flex; align-items: flex-start; gap: 8px; }
|
||||
.result-item.error { background: #fff1f2; border-left: 3px solid var(--danger); }
|
||||
.result-item.warning { background: #fff9db; border-left: 3px solid var(--warn); }
|
||||
.result-item.info { background: #e7f5ff; border-left: 3px solid var(--info); }
|
||||
.icon { font-size: 1rem; flex-shrink: 0; }
|
||||
.summary { display: flex; gap: 12px; margin-bottom: 16px; }
|
||||
.badge { padding: 4px 12px; border-radius: 10px; font-size: .8rem; font-weight: 600; }
|
||||
.badge-err { background: #ffe3e3; color: var(--danger); }
|
||||
.badge-warn { background: #fff3bf; color: var(--warn); }
|
||||
.badge-info { background: #dbeafe; color: var(--info); }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.or { text-align: center; color: var(--text-muted); font-size: .85rem; margin: 8px 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Проверка сметы</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<label>Загрузите YAML-файл проекта:</label>
|
||||
<input type="file" id="yamlFile" accept=".yaml,.yml" style="padding:.4rem;border:1.5px solid var(--border);border-radius:var(--radius);width:100%;font-size:.9rem;background:var(--bg)">
|
||||
<div class="or">или вставьте YAML вручную:</div>
|
||||
<textarea id="yamlInput" placeholder="sections:
|
||||
- name: Глава 1
|
||||
subsections:
|
||||
- items:
|
||||
- code: 28-01-037-02
|
||||
name: Замена шпал
|
||||
unit: шт
|
||||
qty: 100
|
||||
coefficients:
|
||||
definitions:
|
||||
- key: dvizhenie
|
||||
value: 1.40"></textarea>
|
||||
<button class="btn mt-2" onclick="check()" id="checkBtn">
|
||||
<span id="checkSpin" class="spinner d-none"></span> Проверить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="reportCard" class="card d-none">
|
||||
<div class="summary" id="summary"></div>
|
||||
<div id="report"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function $(id){return document.getElementById(id);}
|
||||
|
||||
$('yamlFile').addEventListener('change', function(e) {
|
||||
const file = e.target.files[0];
|
||||
if (file) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (ev) => $('yamlInput').value = ev.target.result;
|
||||
reader.readAsText(file);
|
||||
}
|
||||
});
|
||||
|
||||
async function check() {
|
||||
const yaml = $('yamlInput').value.trim();
|
||||
if (!yaml) return;
|
||||
$('checkSpin').classList.remove('d-none'); $('checkBtn').disabled = true;
|
||||
$('reportCard').classList.add('d-none');
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/check/yaml', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({yaml})
|
||||
});
|
||||
const d = await r.json();
|
||||
|
||||
if (d.error) {
|
||||
$('summary').innerHTML = `<span class="badge badge-err">Ошибка парсинга</span>`;
|
||||
$('report').innerHTML = `<div class="result-item error"><span class="icon">❌</span>${esc(d.error)}</div>`;
|
||||
} else {
|
||||
let sum = '';
|
||||
if (d.errors) sum += `<span class="badge badge-err">${d.errors} ошибок</span>`;
|
||||
if (d.warnings) sum += `<span class="badge badge-warn">${d.warnings} предупреждений</span>`;
|
||||
if (!d.errors && !d.warnings) sum += `<span class="badge badge-info">Всё в порядке</span>`;
|
||||
$('summary').innerHTML = sum;
|
||||
|
||||
let h = '';
|
||||
for (const r of d.results) {
|
||||
const cls = r.level;
|
||||
const icon = r.level === 'error' ? '❌' : r.level === 'warning' ? '⚠️' : 'ℹ️';
|
||||
const pos = r.position ? ` <span style="color:var(--text-muted)">[${esc(r.position)}]</span>` : '';
|
||||
h += `<div class="result-item ${cls}"><span class="icon">${icon}</span><span>${esc(r.message)}${pos}</span></div>`;
|
||||
}
|
||||
$('report').innerHTML = h;
|
||||
}
|
||||
$('reportCard').classList.remove('d-none');
|
||||
} catch(e) {
|
||||
alert(e.message);
|
||||
} finally {
|
||||
$('checkSpin').classList.add('d-none'); $('checkBtn').disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function esc(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,219 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Генерация сметы</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff; --bg-input: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); -webkit-font-smoothing: antialiased; }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
.card h2 { font-size: 1rem; font-weight: 600; margin-bottom: 12px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input[type="text"], textarea, select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; transition: border-color .2s; font-family: inherit; }
|
||||
input:focus, textarea:focus, select:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
textarea { resize: vertical; min-height: 100px; }
|
||||
.row { display: flex; gap: 12px; flex-wrap: wrap; }
|
||||
.row > * { flex: 1; min-width: 140px; }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; transition: all .15s; }
|
||||
.btn-primary { background: var(--accent); color: #fff; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.btn-outline:hover { border-color: var(--accent); color: var(--accent); }
|
||||
.btn-success { background: var(--success); color: #fff; }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.gen-step { display: none; }
|
||||
.gen-step.active { display: block; }
|
||||
.step-badge { display: inline-block; background: var(--accent); color: #fff; padding: 2px 10px; border-radius: 10px; font-size: .78rem; font-weight: 600; }
|
||||
.item { padding: 10px 14px; border: 1.5px solid var(--border-light); border-radius: var(--radius); margin-bottom: 8px; }
|
||||
.item.ok { border-left: 4px solid var(--success); }
|
||||
.item.bad { border-left: 4px solid var(--danger); }
|
||||
.item-head { display: flex; justify-content: space-between; align-items: center; }
|
||||
.item-head strong { font-size: .9rem; }
|
||||
.item-meta { font-size: .82rem; margin-top: 4px; }
|
||||
.score { display: inline-block; padding: 1px 6px; border-radius: 8px; font-size: .72rem; font-weight: 700; }
|
||||
.score-hi { background: #d3f9d8; color: var(--success); }
|
||||
.score-md { background: #fff3bf; color: var(--warn); }
|
||||
.score-lo { background: #ffe3e3; color: var(--danger); }
|
||||
.alt { font-size: .78rem; color: var(--info); cursor: pointer; margin-right: 8px; }
|
||||
.yaml-box { font-family: 'SF Mono', Menlo, monospace; font-size: .8rem; white-space: pre-wrap; background: #2c2c2c; color: #f5f0eb; padding: 16px; border-radius: var(--radius); max-height: 400px; overflow-y: auto; line-height: 1.5; }
|
||||
.error { color: var(--danger); font-size: .85rem; margin-top: 8px; }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.mb-2 { margin-bottom: 8px; }
|
||||
.chk { display: flex; align-items: center; gap: 6px; margin-top: 16px; }
|
||||
.chk input { width: auto; }
|
||||
.chk label { margin: 0; font-size: .9rem; color: var(--text); }
|
||||
.gap-2 { display: flex; gap: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Генерация сметы</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="mb-2">
|
||||
<span class="step-badge" id="stepBadge">Шаг 1 из 3</span>
|
||||
<span style="color:var(--text-muted);font-size:.85rem;margin-left:8px" id="stepLabel">Описание работ</span>
|
||||
</div>
|
||||
|
||||
<!-- Step 1 -->
|
||||
<div class="gen-step active card" id="g1">
|
||||
<h2>Опишите работы</h2>
|
||||
<textarea id="desc" placeholder="Замена 500 шпал на перегоне ст. Свиягино — ст. Ружино, очистка щебня 2 км, замена 3 пар рельсовых плетей по 800м..."></textarea>
|
||||
<div class="row mt-3">
|
||||
<div><label>Регион</label><input type="text" id="region" value="Приморский край"></div>
|
||||
<div><label>Поездов/сут</label><input type="text" id="trains" value="91-108"></div>
|
||||
</div>
|
||||
<div class="row mt-2">
|
||||
<div class="chk"><input type="checkbox" id="vl" checked><label for="vl">Зона ВЛ</label></div>
|
||||
<div class="chk"><input type="checkbox" id="okno" checked><label for="okno">В "окно"</label></div>
|
||||
</div>
|
||||
<button class="btn btn-primary mt-3" onclick="parse()" id="parseBtn">
|
||||
<span id="parseSpin" class="spinner d-none"></span> Разобрать на позиции
|
||||
</button>
|
||||
<div id="parseErr" class="error"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2 -->
|
||||
<div class="gen-step card" id="g2">
|
||||
<h2>Проверьте позиции и расценки</h2>
|
||||
<div id="items"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(1)">Назад</button>
|
||||
<button class="btn btn-primary" onclick="genYaml()" id="yamlBtn">
|
||||
<span id="yamlSpin" class="spinner d-none"></span> Сформировать смету
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3 -->
|
||||
<div class="gen-step card" id="g3">
|
||||
<h2>Конфигурация сметы</h2>
|
||||
<div id="yamlOut" class="yaml-box"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(2)">Назад</button>
|
||||
<button class="btn btn-success" onclick="calcExcel()" id="calcBtn">
|
||||
<span id="calcSpin" class="spinner d-none"></span> Рассчитать и скачать Excel
|
||||
</button>
|
||||
<button class="btn btn-outline" onclick="copy()">Скопировать YAML</button>
|
||||
</div>
|
||||
<div id="calcResult" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4 -->
|
||||
<div class="gen-step card" id="g4">
|
||||
<h2>Смета готова</h2>
|
||||
<p>Расчёт выполнен. Скачайте файл Excel.</p>
|
||||
<div id="downloadInfo" class="mt-2"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(3)">Назад к YAML</button>
|
||||
<a id="downloadLink" class="btn btn-success" href="#" style="text-decoration:none">Скачать Excel</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let matched=[], yamlStr='';
|
||||
function $(id){return document.getElementById(id);}
|
||||
function esc(s){return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}
|
||||
|
||||
function show(n){
|
||||
for(let i=1;i<=4;i++) $('g'+i).classList.toggle('active',i===n);
|
||||
$('stepBadge').textContent=`Шаг ${n} из 4`;
|
||||
const L={1:'Описание работ',2:'Проверка позиций',3:'Конфигурация',4:'Скачать Excel'};
|
||||
$('stepLabel').textContent=L[n];
|
||||
}
|
||||
|
||||
async function parse(){
|
||||
const desc=$('desc').value.trim();
|
||||
if(!desc){$('parseErr').textContent='Введите описание работ';return;}
|
||||
$('parseSpin').classList.remove('d-none'); $('parseBtn').disabled=true; $('parseErr').textContent='';
|
||||
try{
|
||||
const r1=await fetch('/api/gen/parse',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({description:desc})});
|
||||
const d1=await r1.json();
|
||||
if(d1.error){$('parseErr').textContent=d1.error;return;}
|
||||
if(!d1.items.length){$('parseErr').textContent='Не удалось разобрать описание';return;}
|
||||
|
||||
const r2=await fetch('/api/gen/match',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items:d1.items})});
|
||||
const d2=await r2.json();
|
||||
if(d2.error){$('parseErr').textContent=d2.error;return;}
|
||||
matched=d2.matched;
|
||||
|
||||
let h='';
|
||||
for(const m of matched){
|
||||
const ok=m.score>0.3;
|
||||
const sc=m.score>0.6?'score-hi':m.score>0.3?'score-md':'score-lo';
|
||||
h+=`<div class="item ${ok?'ok':'bad'}">
|
||||
<div class="item-head"><strong>${esc(m.description)}</strong><span>${esc(m.unit||'')} x ${m.qty||'?'}</span></div>
|
||||
<div class="item-meta"><span class="score ${sc}">${(m.score*100).toFixed(0)}%</span> <strong>${esc(m.gesn_code)}</strong> ${esc(m.gesn_name||'')}</div>`;
|
||||
if(m.alternatives&&m.alternatives.length){h+='<div class="mt-2">';for(const a of m.alternatives)h+=`<span class="alt">${a.code} (${(a.score*100).toFixed(0)}%)</span>`;h+='</div>';}
|
||||
if(m.note)h+=`<div style="font-size:.82rem;color:var(--text-muted);margin-top:4px">${esc(m.note)}</div>`;
|
||||
h+='</div>';
|
||||
}
|
||||
$('items').innerHTML=h;
|
||||
show(2);
|
||||
}catch(e){$('parseErr').textContent=e.message;}
|
||||
finally{$('parseSpin').classList.add('d-none');$('parseBtn').disabled=false;}
|
||||
}
|
||||
|
||||
async function genYaml(){
|
||||
$('yamlSpin').classList.remove('d-none'); $('yamlBtn').disabled=true;
|
||||
try{
|
||||
const r=await fetch('/api/gen/yaml',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({matched_items:matched,region:$('region').value,trains_per_day:$('trains').value,vl_zone:$('vl').checked,okno:$('okno').checked})});
|
||||
const d=await r.json();
|
||||
if(d.error){alert(d.error);return;}
|
||||
yamlStr=d.yaml;
|
||||
$('yamlOut').textContent=yamlStr;
|
||||
show(3);
|
||||
}catch(e){alert(e.message);}
|
||||
finally{$('yamlSpin').classList.add('d-none');$('yamlBtn').disabled=false;}
|
||||
}
|
||||
|
||||
async function calcExcel(){
|
||||
$('calcSpin').classList.remove('d-none'); $('calcBtn').disabled=true; $('calcResult').innerHTML='';
|
||||
try{
|
||||
const r=await fetch('/api/gen/calculate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({yaml:yamlStr})});
|
||||
const d=await r.json();
|
||||
if(d.error){
|
||||
$('calcResult').innerHTML=`<div style="color:var(--danger);font-size:.85rem">${esc(d.error)}</div>`;
|
||||
return;
|
||||
}
|
||||
$('downloadLink').href=d.download_url;
|
||||
$('downloadInfo').innerHTML=`<p>Позиций: ${d.positions}</p>`;
|
||||
show(4);
|
||||
}catch(e){$('calcResult').innerHTML=`<div style="color:var(--danger)">${e.message}</div>`;}
|
||||
finally{$('calcSpin').classList.add('d-none');$('calcBtn').disabled=false;}
|
||||
}
|
||||
|
||||
function copy(){
|
||||
navigator.clipboard.writeText(yamlStr).then(()=>{
|
||||
const b=event.target; b.textContent='Скопировано!'; setTimeout(()=>b.textContent='Скопировать',2000);
|
||||
});
|
||||
}
|
||||
function dl(){
|
||||
const b=new Blob([yamlStr],{type:'text/yaml'}), u=URL.createObjectURL(b), a=document.createElement('a');
|
||||
a.href=u; a.download='estimate.yaml'; a.click(); URL.revokeObjectURL(u);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,115 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Справочники</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input, select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; }
|
||||
input:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.tabs { display: flex; gap: 4px; margin-bottom: 16px; }
|
||||
.tab { padding: .5rem 1rem; border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: .85rem; font-weight: 500; color: var(--text-muted); background: transparent; transition: all .15s; }
|
||||
.tab.active { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||
.tab:hover:not(.active) { border-color: var(--accent); color: var(--accent); }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; background: var(--accent); color: #fff; }
|
||||
.btn:hover { background: var(--accent-hover); }
|
||||
.result { padding: 10px 14px; border-left: 3px solid var(--info); background: var(--bg); border-radius: 0 var(--radius) var(--radius) 0; margin-bottom: 6px; font-size: .88rem; }
|
||||
.result strong { font-weight: 700; }
|
||||
.score { display: inline-block; padding: 1px 6px; border-radius: 8px; font-size: .72rem; font-weight: 700; }
|
||||
.score-hi { background: #d3f9d8; color: var(--success); }
|
||||
.score-md { background: #fff3bf; color: var(--warn); }
|
||||
.score-lo { background: #ffe3e3; color: var(--danger); }
|
||||
.pct { font-size: 1.1rem; font-weight: 700; color: var(--accent); }
|
||||
.muted { color: var(--text-muted); font-size: .82rem; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.input-row { display: flex; gap: 8px; }
|
||||
.input-row input { flex: 1; }
|
||||
#results { min-height: 100px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Справочники</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="tabs">
|
||||
<button class="tab active" onclick="setTab('gesn')">Поиск ГЭСН</button>
|
||||
<button class="tab" onclick="setTab('nr')">НР</button>
|
||||
<button class="tab" onclick="setTab('sp')">СП</button>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="input-row">
|
||||
<input type="text" id="q" placeholder="Введите запрос..." onkeydown="if(event.key==='Enter')search()">
|
||||
<button class="btn" onclick="search()">Найти</button>
|
||||
</div>
|
||||
<div id="results" class="mt-3"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let mode = 'gesn';
|
||||
|
||||
function setTab(m) {
|
||||
mode = m;
|
||||
document.querySelectorAll('.tab').forEach((t, i) => t.classList.toggle('active', ['gesn','nr','sp'][i] === m));
|
||||
document.getElementById('q').placeholder = mode === 'gesn' ? 'Описание работ...' : 'Вид работ...';
|
||||
document.getElementById('results').innerHTML = '';
|
||||
document.getElementById('q').focus();
|
||||
}
|
||||
|
||||
async function search() {
|
||||
const q = document.getElementById('q').value.trim();
|
||||
if (!q) return;
|
||||
const url = mode === 'gesn' ? '/api/ref/search' : `/api/ref/${mode}`;
|
||||
const body = mode === 'gesn' ? {query: q, top_k: 10} : {query: q};
|
||||
const r = await fetch(url, {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)});
|
||||
const d = await r.json();
|
||||
|
||||
let h = '';
|
||||
if (mode === 'gesn') {
|
||||
if (!d.results || !d.results.length) { h = '<p class="muted">Ничего не найдено</p>'; }
|
||||
else {
|
||||
for (const r of d.results) {
|
||||
const sc = r.score > 0.6 ? 'score-hi' : r.score > 0.3 ? 'score-md' : 'score-lo';
|
||||
h += `<div class="result"><strong>ГЭСН ${esc(r.code)}</strong> <span class="score ${sc}">${(r.score*100).toFixed(0)}%</span><br>${esc(r.name)}<br><span class="muted">Ед: ${esc(r.unit)} | сб.${esc(r.collection)}</span></div>`;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!d.results || !d.results.length) { h = `<p class="muted">${d.label}: ничего не найдено</p>`; }
|
||||
else {
|
||||
h = `<p class="muted">${d.label} — найдено: ${d.count}</p>`;
|
||||
for (const r of d.results) {
|
||||
h += `<div class="result">п.${esc(r.key)}. ${esc(r.name)} — <span class="pct">${r.percent}%</span> от ФОТ</div>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
document.getElementById('results').innerHTML = h;
|
||||
}
|
||||
|
||||
function esc(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.getElementById('q').focus();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,235 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Агрегатор xlsx</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff; --bg-input: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); -webkit-font-smoothing: antialiased; }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
.card h2 { font-size: 1rem; font-weight: 600; margin-bottom: 12px; color: var(--text); }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input[type="text"], input[type="file"], select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; transition: border-color .2s; }
|
||||
input:focus, select:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.row { display: flex; gap: 12px; }
|
||||
.row > * { flex: 1; }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; transition: all .15s; }
|
||||
.btn-primary { background: var(--accent); color: #fff; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.btn-outline:hover { border-color: var(--accent); color: var(--accent); }
|
||||
.btn-success { background: var(--success); color: #fff; }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.step-bar { display: flex; gap: 4px; margin-bottom: 20px; }
|
||||
.step-dot { flex: 1; height: 5px; border-radius: 3px; background: var(--border-light); transition: background .3s; }
|
||||
.step-dot.done { background: var(--success); }
|
||||
.step-dot.current { background: var(--accent); }
|
||||
.wiz-step { display: none; }
|
||||
.wiz-step.active { display: block; }
|
||||
.preview-table { max-height: 280px; overflow-y: auto; font-size: .82rem; border: 1px solid var(--border-light); border-radius: var(--radius); }
|
||||
.preview-table table { width: 100%; border-collapse: collapse; }
|
||||
.preview-table th { background: var(--bg); font-weight: 600; position: sticky; top: 0; }
|
||||
.preview-table td, .preview-table th { padding: 6px 10px; border-bottom: 1px solid var(--border-light); white-space: nowrap; }
|
||||
.status-add { color: var(--success); font-weight: 600; }
|
||||
.status-update { color: var(--info); }
|
||||
.badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: .75rem; font-weight: 600; }
|
||||
.badge-info { background: #dbeafe; color: var(--info); }
|
||||
.badge-success { background: #d3f9d8; color: var(--success); }
|
||||
.badge-muted { background: var(--border-light); color: var(--text-muted); }
|
||||
.error { color: #e03131; font-size: .85rem; margin-top: 8px; }
|
||||
.file-list { font-size: .85rem; color: var(--text-muted); }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.mb-2 { margin-bottom: 8px; }
|
||||
.nav-bottom { display: flex; justify-content: space-between; margin-top: 16px; }
|
||||
.alert-success { background: #d3f9d8; border: 1px solid #69db7c; border-radius: var(--radius); padding: 12px; color: var(--success); }
|
||||
.alert-success a { color: var(--success); font-weight: 600; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Агрегатор xlsx</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="step-bar" id="stepBar"></div>
|
||||
|
||||
<!-- Step 1 -->
|
||||
<div class="wiz-step active card" id="s1">
|
||||
<h2>Загрузка файлов</h2>
|
||||
<div class="mb-2"><label>ZIP-архив с источниками</label><input type="file" id="fZip" accept=".zip"></div>
|
||||
<div class="mb-2"><label>Целевой файл (.xlsx)</label><input type="file" id="fTarget" accept=".xlsx"></div>
|
||||
<button class="btn btn-primary" onclick="upload()"><span id="upSpin" class="spinner d-none"></span> Загрузить</button>
|
||||
<div id="upErr" class="error"></div>
|
||||
<div id="upInfo" class="file-list mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2 -->
|
||||
<div class="wiz-step card" id="s2">
|
||||
<h2>Критерий поиска</h2>
|
||||
<div class="row mb-2">
|
||||
<div><label>Лист</label><select id="srcSheet"></select></div>
|
||||
<div><label>Колонка</label><select id="srcCol"></select></div>
|
||||
<div><label>Ключевое слово</label><input type="text" id="srcKw" value="разряд"></div>
|
||||
</div>
|
||||
<button class="btn btn-outline" onclick="analyze()">Найти</button>
|
||||
<div id="searchPrev" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3 -->
|
||||
<div class="wiz-step card" id="s3">
|
||||
<h2>Колонка значений</h2>
|
||||
<div class="mb-2"><label>Из какой колонки брать числа?</label><select id="valCol"></select></div>
|
||||
<button class="btn btn-outline" onclick="analyzeVal()">Превью</button>
|
||||
<div id="valPrev" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4 -->
|
||||
<div class="wiz-step card" id="s4">
|
||||
<h2>Сопоставление с целевым</h2>
|
||||
<div class="row"><div><label>Лист</label><select id="tgtSheet"></select></div><div><label>Колонка</label><select id="matchCol"></select></div></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 5 -->
|
||||
<div class="wiz-step card" id="s5">
|
||||
<h2>Действие</h2>
|
||||
<div class="row">
|
||||
<div><label>Операция</label><select id="action"><option value="sum">Суммировать</option><option value="replace">Заменить</option><option value="max">Максимум</option><option value="min">Минимум</option></select></div>
|
||||
<div><label>Записать в колонку</label><select id="writeCol"></select></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 6 -->
|
||||
<div class="wiz-step card" id="s6">
|
||||
<h2>Ненайденные строки</h2>
|
||||
<select id="unmatched" style="max-width:300px"><option value="add">Добавить новые строки</option><option value="skip">Пропустить</option></select>
|
||||
</div>
|
||||
|
||||
<!-- Step 7 -->
|
||||
<div class="wiz-step card" id="s7">
|
||||
<h2>Превью и подтверждение</h2>
|
||||
<div id="prevLoad" class="d-none" style="text-align:center;padding:20px"><div class="spinner"></div><p class="mt-2" style="color:var(--text-muted)">Вычисляю...</p></div>
|
||||
<div id="prevResult"></div>
|
||||
<div id="prevSummary" class="mt-2"></div>
|
||||
<button class="btn btn-success mt-3 d-none" id="runBtn" onclick="run()"><span id="runSpin" class="spinner d-none"></span> Применить и скачать</button>
|
||||
<div id="runResult" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<div class="nav-bottom">
|
||||
<button class="btn btn-outline" id="prevBtn" onclick="prev()" disabled>Назад</button>
|
||||
<button class="btn btn-primary" id="nextBtn" onclick="next()" disabled>Далее</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const N=7; let step=1,sid=null,src=null,tgt=null;
|
||||
|
||||
function ui(){
|
||||
for(let i=1;i<=N;i++) document.getElementById('s'+i).classList.toggle('active',i===step);
|
||||
document.getElementById('prevBtn').disabled=step===1;
|
||||
document.getElementById('nextBtn').disabled=!ok();
|
||||
const b=document.getElementById('stepBar'); b.innerHTML='';
|
||||
for(let i=1;i<=N;i++){const c=i<step?'done':i===step?'current':''; b.innerHTML+=`<div class="step-dot ${c}"></div>`;}
|
||||
if(step===7) loadPreview();
|
||||
}
|
||||
function ok(){
|
||||
if(step===1)return!!sid; if(step===2)return!!$('srcCol').value;
|
||||
if(step===3)return!!$('valCol').value; if(step===4)return!!$('matchCol').value;
|
||||
return step===5||step===6;
|
||||
}
|
||||
function next(){if(step<N){step++;ui();}} function prev(){if(step>1){step--;ui();}}
|
||||
function $(id){return document.getElementById(id);}
|
||||
|
||||
async function upload(){
|
||||
const z=$('fZip').files[0], t=$('fTarget').files[0];
|
||||
if(!z||!t){$('upErr').textContent='Выберите оба файла';return;}
|
||||
$('upSpin').classList.remove('d-none'); $('upErr').textContent='';
|
||||
const fd=new FormData(); fd.append('zip_file',z); fd.append('target_file',t);
|
||||
try{
|
||||
const r=await fetch('/api/wizard/upload',{method:'POST',body:fd});
|
||||
if(!r.ok){const e=await r.json();throw new Error(e.detail||'Ошибка загрузки');}
|
||||
const d=await r.json(); sid=d.session_id; src=d.sources; tgt=d.target;
|
||||
let h=`<p><strong>Источники:</strong> ${src.length} файл(ов)</p><ul>`;
|
||||
for(const s of src) h+=`<li>${s.filename} — ${s.sheets.map(sh=>sh.name+' ('+sh.row_count+')').join(', ')}</li>`;
|
||||
h+=`</ul><p><strong>Целевой:</strong> ${tgt.filename}</p>`;
|
||||
$('upInfo').innerHTML=h; popSrc(); popTgt(); ui();
|
||||
}catch(e){$('upErr').textContent=e.message;}
|
||||
finally{$('upSpin').classList.add('d-none');}
|
||||
}
|
||||
|
||||
function popSrc(){
|
||||
const ss=$('srcSheet'),sc=$('srcCol'),vc=$('valCol'); ss.innerHTML='';sc.innerHTML='';vc.innerHTML='';
|
||||
const sheets=new Set(); for(const s of src) for(const sh of s.sheets) sheets.add(sh.name);
|
||||
for(const n of sheets) ss.innerHTML+=`<option>${n}</option>`;
|
||||
const cols=src[0].sheets[0].columns;
|
||||
for(const c of cols){const l=`${c.letter}: ${c.header} (${c.type})`;sc.innerHTML+=`<option value="${c.letter}">${l}</option>`;vc.innerHTML+=`<option value="${c.letter}">${l}</option>`;}
|
||||
const tc=cols.filter(c=>c.type==='text'),nc=cols.filter(c=>c.type==='number');
|
||||
const nl=tc.find(c=>/наименован/i.test(c.header)); if(nl)sc.value=nl.letter; else if(tc.length)sc.value=tc[0].letter;
|
||||
const ql=nc.find(c=>/количеств|кол/i.test(c.header)); if(ql)vc.value=ql.letter; else if(nc.length)vc.value=nc[0].letter;
|
||||
}
|
||||
function popTgt(){
|
||||
const ts=$('tgtSheet'),mc=$('matchCol'),wc=$('writeCol'); ts.innerHTML='';mc.innerHTML='';wc.innerHTML='';
|
||||
for(const sh of tgt.sheets) ts.innerHTML+=`<option>${sh.name}</option>`;
|
||||
const cols=tgt.sheets[0].columns;
|
||||
for(const c of cols){const l=`${c.letter}: ${c.header} (${c.type})`;mc.innerHTML+=`<option value="${c.letter}">${l}</option>`;wc.innerHTML+=`<option value="${c.letter}">${l}</option>`;}
|
||||
const tc=cols.filter(c=>c.type==='text'),nc=cols.filter(c=>c.type==='number');
|
||||
const nl=tc.find(c=>/наименован/i.test(c.header)); if(nl)mc.value=nl.letter; else if(tc.length)mc.value=tc[0].letter;
|
||||
const ql=nc.find(c=>/количеств|кол/i.test(c.header)); if(ql)wc.value=ql.letter; else if(nc.length)wc.value=nc[0].letter;
|
||||
}
|
||||
|
||||
async function analyze(){
|
||||
const r=await fetch('/api/wizard/analyze',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid,search_column:$('srcCol').value,search_keyword:$('srcKw').value,source_sheet:$('srcSheet').value})});
|
||||
const d=await r.json();
|
||||
let h=`<p>Найдено: <strong>${d.found_count}</strong>, ключей: <strong>${(d.unique_keys||[]).length}</strong></p>`;
|
||||
if(d.sample_rows&&d.sample_rows.length){h+='<div class="preview-table"><table><thead><tr><th>Файл</th><th>Строка</th><th>Текст</th><th>Ключ</th></tr></thead><tbody>';for(const r of d.sample_rows.slice(0,15))h+=`<tr><td>${r.file}</td><td>${r.row}</td><td>${r.search_value}</td><td>${r.key||'-'}</td></tr>`;h+='</tbody></table></div>';}
|
||||
$('searchPrev').innerHTML=h; ui();
|
||||
}
|
||||
async function analyzeVal(){
|
||||
const r=await fetch('/api/wizard/analyze',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid,search_column:$('srcCol').value,search_keyword:$('srcKw').value,source_sheet:$('srcSheet').value,value_column:$('valCol').value})});
|
||||
const d=await r.json(); let h='';
|
||||
if(d.sample_rows&&d.sample_rows.length){h+='<div class="preview-table"><table><thead><tr><th>Файл</th><th>Ключ</th><th>Значение</th></tr></thead><tbody>';for(const r of d.sample_rows.slice(0,10))h+=`<tr><td>${r.file}</td><td>${r.key||'-'}</td><td>${r.number_value!=null?r.number_value.toFixed(2):'-'}</td></tr>`;h+='</tbody></table></div>';}
|
||||
$('valPrev').innerHTML=h;
|
||||
}
|
||||
|
||||
function cfg(){return{session_id:sid,search_keyword:$('srcKw').value,search_column:$('srcCol').value,value_column:$('valCol').value,source_sheet:$('srcSheet').value||null,target_sheet:$('tgtSheet').value||null,match_column:$('matchCol').value,target_write_column:$('writeCol').value,action:$('action').value,unmatched:$('unmatched').value};}
|
||||
|
||||
async function loadPreview(){
|
||||
$('prevLoad').classList.remove('d-none');$('prevResult').innerHTML='';$('prevSummary').innerHTML='';$('runBtn').classList.add('d-none');
|
||||
try{const r=await fetch('/api/wizard/preview',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(cfg())});const d=await r.json();
|
||||
let h='<div class="preview-table"><table><thead><tr><th>Статус</th><th>Строка</th><th>Название</th><th>Было</th><th>Станет</th></tr></thead><tbody>';
|
||||
for(const m of d.matches){const c=m.status==='add'?'status-add':'status-update',l=m.status==='add'?'НОВЫЙ':'обновл.';h+=`<tr><td class="${c}">${l}</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>`;}
|
||||
h+='</tbody></table></div>';$('prevResult').innerHTML=h;
|
||||
const s=d.summary;$('prevSummary').innerHTML=`<span class="badge badge-info">${s.updates} обновлений</span> <span class="badge badge-success">${s.adds} новых</span> <span class="badge badge-muted">Итого: ${s.total_new_value.toFixed(2)}</span>`;
|
||||
if(d.matches.length)$('runBtn').classList.remove('d-none');
|
||||
}finally{$('prevLoad').classList.add('d-none');}
|
||||
}
|
||||
|
||||
async function run(){
|
||||
$('runSpin').classList.remove('d-none');
|
||||
try{const r=await fetch('/api/wizard/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(cfg())});const d=await r.json();
|
||||
if(d.success)$('runResult').innerHTML=`<div class="alert-success">Готово! Обновлено: ${d.stats.updated}, добавлено: ${d.stats.added}<br><a href="${d.download_url}">Скачать результат</a></div>`;
|
||||
}finally{$('runSpin').classList.add('d-none');}
|
||||
}
|
||||
ui();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user