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")))
|
||||
|
||||
Reference in New Issue
Block a user