diff --git a/main.py b/main.py index c39d423..9466c0e 100644 --- a/main.py +++ b/main.py @@ -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"))) diff --git a/static/chat.html b/static/chat.html index bfa7899..b4eb570 100644 --- a/static/chat.html +++ b/static/chat.html @@ -122,7 +122,10 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo - + + + + diff --git a/static/check.html b/static/check.html new file mode 100644 index 0000000..dc4e6dd --- /dev/null +++ b/static/check.html @@ -0,0 +1,137 @@ + + + + + +Проверка сметы + + + +
+
+

Проверка сметы

+ ← Назад к чату +
+ +
+ + +
или вставьте YAML вручную:
+ + +
+ +
+
+
+
+
+ + + + diff --git a/static/generate.html b/static/generate.html new file mode 100644 index 0000000..1e5865f --- /dev/null +++ b/static/generate.html @@ -0,0 +1,219 @@ + + + + + +Генерация сметы + + + +
+
+

Генерация сметы

+ ← Назад к чату +
+ +
+ Шаг 1 из 3 + Описание работ +
+ + +
+

Опишите работы

+ +
+
+
+
+
+
+
+
+ +
+
+ + +
+

Проверьте позиции и расценки

+
+
+ + +
+
+ + +
+

Конфигурация сметы

+
+
+ + + +
+
+
+ + +
+

Смета готова

+

Расчёт выполнен. Скачайте файл Excel.

+
+
+ + Скачать Excel +
+
+
+ + + + diff --git a/static/reference.html b/static/reference.html new file mode 100644 index 0000000..ded8084 --- /dev/null +++ b/static/reference.html @@ -0,0 +1,115 @@ + + + + + +Справочники + + + +
+
+

Справочники

+ ← Назад к чату +
+ +
+ + + +
+ +
+
+ + +
+
+
+
+ + + + diff --git a/static/wizard.html b/static/wizard.html new file mode 100644 index 0000000..792e6a1 --- /dev/null +++ b/static/wizard.html @@ -0,0 +1,235 @@ + + + + + +Агрегатор xlsx + + + +
+
+

Агрегатор xlsx

+ ← Назад к чату +
+ +
+ + +
+

Загрузка файлов

+
+
+ +
+
+
+ + +
+

Критерий поиска

+
+
+
+
+
+ +
+
+ + +
+

Колонка значений

+
+ +
+
+ + +
+

Сопоставление с целевым

+
+
+ + +
+

Действие

+
+
+
+
+
+ + +
+

Ненайденные строки

+ +
+ + +
+

Превью и подтверждение

+

Вычисляю...

+
+
+ +
+
+ + +
+ + + +