fix(security): блок ② — убран депрекированный пакетный путь (exec на хосте)
По решению пользователя вместо песочницы — retire всего депрекированного пакетного пути (страницы давно заменены чатом). Устраняет P0: batch v2/v3 исполняли СГЕНЕРИРОВАННЫЙ ИИ по загруженной смете скрипт через exec() прямо в процессе сервера (prompt-injection в смете контрагента → доступ к .env/БД/файлам всех). - Удалены роуты: /api/batch-v2/*, /api/batch-v3/*, /api/ssr/*, /api/check/yaml, /api/gen/calculate, /api/gen/download + смонтированные /api/gen|ref|wizard. - Страницы /batch|batch2|batch3|ssr|wizard|generate|reference|check → 302 на /. - Удалены мёртвые модули batch.py (exec:393 + code-injection через имя листа) и batch_v3.py (три exec-точки), их HTML-страницы (заодно ушёл их XSS-surface). - get_work_dir/ownership-хелперы для batch больше не нужны, но оставлены (dead, безвредны) — точечная зачистка отдельно. Живой чат путь не затронут (batch_v3/extract_zip импортились только депрекированными эндпоинтами). Тесты: pages→302, api→404. 297 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -964,17 +964,9 @@ async def clear_files(request: Request):
|
||||
|
||||
|
||||
# === Batch processing ===
|
||||
from xlsx_utils import extract_zip
|
||||
import batch_v3
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
BATCH_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch"
|
||||
|
||||
|
||||
@app.get("/batch", response_class=HTMLResponse)
|
||||
async def batch_page():
|
||||
return Path("static/batch.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# V1 batch endpoints removed — use /api/batch-v3/* instead
|
||||
@@ -983,173 +975,6 @@ async def batch_page():
|
||||
# === Batch V2: Claude Code analysis ===
|
||||
|
||||
|
||||
@app.get("/batch2", response_class=HTMLResponse)
|
||||
async def batch2_page():
|
||||
return Path("static/batch2.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.post("/api/batch-v2/upload")
|
||||
async def batch_v2_upload(request: Request):
|
||||
"""Upload zip + target, convert xlsx→CSV, start Claude analysis (SSE stream)."""
|
||||
user = _get_user(request)
|
||||
form = await request.form()
|
||||
zip_file = form.get("zip_file")
|
||||
target_file = form.get("target_file")
|
||||
task_desc = form.get("task_description", "Перенести итоги из смет в сводный файл")
|
||||
|
||||
if not zip_file or not target_file:
|
||||
raise HTTPException(400, "Need zip_file and target_file")
|
||||
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
job_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch_v2" / user / job_id
|
||||
job_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Save target
|
||||
target_name = Path(target_file.filename).name
|
||||
target_path = job_dir / target_name
|
||||
target_content = await target_file.read()
|
||||
target_path.write_bytes(target_content)
|
||||
# Also save as target.xlsx for Claude
|
||||
(job_dir / "target.xlsx").write_bytes(target_content)
|
||||
|
||||
# Save and extract zip
|
||||
zip_path = job_dir / "source.zip"
|
||||
zip_content = await zip_file.read()
|
||||
zip_path.write_bytes(zip_content)
|
||||
source_dir = job_dir / "source"
|
||||
source_dir.mkdir(exist_ok=True)
|
||||
source_files = extract_zip(str(zip_path), str(source_dir))
|
||||
|
||||
# Convert target → CSV for Claude to read (only the target file)
|
||||
target_only_dir = job_dir / "_target_only"
|
||||
target_only_dir.mkdir(exist_ok=True)
|
||||
shutil.copy2(str(target_path), str(target_only_dir / target_name))
|
||||
target_csv_dir = str(job_dir / "target_csv")
|
||||
batch_v3.convert_all_to_csv(str(target_only_dir), target_csv_dir)
|
||||
shutil.rmtree(str(target_only_dir))
|
||||
|
||||
# Select and convert SAMPLE files (not all — could be 2000+)
|
||||
sample_info = batch_v3.prepare_samples(str(source_dir), job_dir, {})
|
||||
|
||||
# Create job
|
||||
job = batch_v3.create_job(job_id)
|
||||
job["user"] = user # владелец — для проверки доступа в analyze/run/status/download
|
||||
job["source_dir"] = str(source_dir)
|
||||
job["target_file"] = str(target_path)
|
||||
job["target_name"] = target_name
|
||||
job["job_dir"] = str(job_dir)
|
||||
job["total_files"] = len(source_files)
|
||||
job["task_description"] = task_desc
|
||||
job["sample_info"] = sample_info
|
||||
job["status"] = "uploaded"
|
||||
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"total_files": len(source_files),
|
||||
"csv_info": {
|
||||
"sample_count": sample_info["sample_csv_count"],
|
||||
"sample_bytes": sample_info["sample_bytes"],
|
||||
"estimated_tokens": int(sample_info["sample_bytes"] * 0.3),
|
||||
"xlsx_count": len(source_files),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/batch-v2/analyze/{job_id}")
|
||||
async def batch_v2_analyze(job_id: str, request: Request):
|
||||
"""Start Claude Code analysis — returns SSE stream."""
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
job_dir = Path(job["job_dir"])
|
||||
task_desc = job["task_description"]
|
||||
target_name = job["target_name"]
|
||||
total_files = job["total_files"]
|
||||
sample_info = job["sample_info"]
|
||||
|
||||
async def event_stream():
|
||||
async for event in batch_v3.run_claude_analysis(
|
||||
job_dir, task_desc, target_name, total_files, sample_info
|
||||
):
|
||||
etype = event.get("type", "")
|
||||
if etype == "text":
|
||||
yield f"event: text\ndata: {json.dumps({'text': event['text']}, ensure_ascii=False)}\n\n"
|
||||
elif etype == "tool":
|
||||
yield f"event: tool\ndata: {json.dumps({'tool': event['tool']}, ensure_ascii=False)}\n\n"
|
||||
elif etype == "done":
|
||||
script = event.get("script", "")
|
||||
summary = event.get("summary", {})
|
||||
if script:
|
||||
job["analysis"] = {"python_script": script, "summary": summary}
|
||||
job["status"] = "analyzed"
|
||||
else:
|
||||
job["analysis"] = {"error": "Claude did not generate script", "result": event.get("result", "")}
|
||||
job["status"] = "analysis_failed"
|
||||
yield f"event: done\ndata: {json.dumps({'script': script, 'summary': summary, 'status': job['status']}, ensure_ascii=False)}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/batch-v2/run/{job_id}")
|
||||
async def batch_v2_run(job_id: str, request: Request):
|
||||
"""Confirm and run the Claude-generated script."""
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
script = job.get("analysis", {}).get("python_script", "")
|
||||
if not script:
|
||||
raise HTTPException(400, "No script generated")
|
||||
|
||||
threading.Thread(
|
||||
target=batch_v3.run_batch_v2,
|
||||
args=(job_id, script, job["source_dir"], job["target_file"]),
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
return {"status": "started", "job_id": job_id}
|
||||
|
||||
|
||||
@app.get("/api/batch-v2/status/{job_id}")
|
||||
async def batch_v2_status(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
# If status is still "uploaded" but files exist on disk — Claude finished
|
||||
# but SSE didn't deliver the done event
|
||||
if job["status"] == "uploaded" and job.get("job_dir"):
|
||||
job_dir = Path(job["job_dir"])
|
||||
result_data = batch_v3._read_result_files(job_dir)
|
||||
if result_data.get("script"):
|
||||
job["analysis"] = {
|
||||
"python_script": result_data["script"],
|
||||
"summary": result_data.get("summary", {}),
|
||||
}
|
||||
job["status"] = "analyzed"
|
||||
|
||||
analysis = job.get("analysis", {})
|
||||
return {
|
||||
"status": job["status"],
|
||||
"total": job.get("total_files", 0),
|
||||
"processed": job.get("processed", 0),
|
||||
"errors": job.get("errors", [])[:20],
|
||||
"script": analysis.get("python_script", ""),
|
||||
"summary": analysis.get("summary", {}),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/batch-v2/download/{job_id}")
|
||||
async def batch_v2_download(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
if not job.get("output_file"):
|
||||
raise HTTPException(404, "Result not ready")
|
||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||
|
||||
|
||||
# === Admin: view user sessions ===
|
||||
|
||||
|
||||
@@ -1484,169 +1309,6 @@ async def admin_page(request: Request):
|
||||
|
||||
|
||||
# === Batch V3: Generate + Verify + Auto-Retry ===
|
||||
import batch_v3
|
||||
|
||||
|
||||
@app.get("/batch3", response_class=HTMLResponse)
|
||||
async def batch3_page():
|
||||
return Path("static/batch3.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.post("/api/batch-v3/upload")
|
||||
async def batch_v3_upload(request: Request):
|
||||
"""Upload zip + target — same as V2 but separate storage."""
|
||||
user = _get_user(request)
|
||||
form = await request.form()
|
||||
zip_file = form.get("zip_file")
|
||||
target_file = form.get("target_file")
|
||||
task_desc = form.get("task_description", "Перенести итоги из смет в сводный файл")
|
||||
|
||||
if not zip_file or not target_file:
|
||||
raise HTTPException(400, "Need zip_file and target_file")
|
||||
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
job_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch_v3" / user / job_id
|
||||
job_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
target_name = Path(target_file.filename).name
|
||||
target_path = job_dir / target_name
|
||||
target_content = await target_file.read()
|
||||
target_path.write_bytes(target_content)
|
||||
(job_dir / "target.xlsx").write_bytes(target_content)
|
||||
|
||||
zip_path = job_dir / "source.zip"
|
||||
zip_content = await zip_file.read()
|
||||
zip_path.write_bytes(zip_content)
|
||||
source_dir = job_dir / "source"
|
||||
source_dir.mkdir(exist_ok=True)
|
||||
source_files = extract_zip(str(zip_path), str(source_dir))
|
||||
|
||||
target_only_dir = job_dir / "_target_only"
|
||||
target_only_dir.mkdir(exist_ok=True)
|
||||
shutil.copy2(str(target_path), str(target_only_dir / target_name))
|
||||
target_csv_dir = str(job_dir / "target_csv")
|
||||
batch_v3.convert_all_to_csv(str(target_only_dir), target_csv_dir)
|
||||
shutil.rmtree(str(target_only_dir))
|
||||
|
||||
sample_info = batch_v3.prepare_samples(str(source_dir), job_dir, {})
|
||||
|
||||
job = batch_v3.create_job(job_id)
|
||||
job["user"] = user # владелец — для проверки доступа в analyze/run/status/download
|
||||
job["source_dir"] = str(source_dir)
|
||||
job["target_file"] = str(target_path)
|
||||
job["target_name"] = target_name
|
||||
job["job_dir"] = str(job_dir)
|
||||
job["total_files"] = len(source_files)
|
||||
job["task_description"] = task_desc
|
||||
job["sample_info"] = sample_info
|
||||
job["status"] = "uploaded"
|
||||
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"total_files": len(source_files),
|
||||
"csv_info": {
|
||||
"sample_count": sample_info["sample_csv_count"],
|
||||
"sample_bytes": sample_info["sample_bytes"],
|
||||
"estimated_tokens": int(sample_info["sample_bytes"] * 0.3),
|
||||
"xlsx_count": len(source_files),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/batch-v3/analyze/{job_id}")
|
||||
async def batch_v3_analyze(job_id: str, request: Request):
|
||||
"""Generate + verify + auto-retry — SSE stream."""
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
job_dir = Path(job["job_dir"])
|
||||
|
||||
async def event_stream():
|
||||
async for event in batch_v3.run_generate_and_verify(
|
||||
job_dir,
|
||||
job["task_description"],
|
||||
job["target_name"],
|
||||
job["total_files"],
|
||||
job["sample_info"],
|
||||
job["source_dir"],
|
||||
job["target_file"],
|
||||
):
|
||||
etype = event.get("type", "")
|
||||
if etype in ("text", "tool", "generation_start", "verify_start",
|
||||
"verify_ok", "verify_fail", "retry", "error"):
|
||||
yield f"event: {etype}\ndata: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
elif etype == "done":
|
||||
script = event.get("script", "")
|
||||
summary = event.get("summary", {})
|
||||
verified = event.get("verified", False)
|
||||
attempts = event.get("attempts", 0)
|
||||
if script:
|
||||
job["analysis"] = {"python_script": script, "summary": summary}
|
||||
job["status"] = "analyzed"
|
||||
job["verified"] = verified
|
||||
job["verify_attempts"] = attempts
|
||||
else:
|
||||
job["status"] = "analysis_failed"
|
||||
yield f"event: done\ndata: {json.dumps({'script': script, 'summary': summary, 'verified': verified, 'attempts': attempts, 'status': job['status']}, ensure_ascii=False)}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/batch-v3/run/{job_id}")
|
||||
async def batch_v3_run(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
script = job.get("analysis", {}).get("python_script", "")
|
||||
if not script:
|
||||
raise HTTPException(400, "No script")
|
||||
threading.Thread(
|
||||
target=batch_v3.run_batch_v3,
|
||||
args=(job_id, script, job["source_dir"], job["target_file"]),
|
||||
daemon=True,
|
||||
).start()
|
||||
return {"status": "started", "job_id": job_id}
|
||||
|
||||
|
||||
@app.get("/api/batch-v3/status/{job_id}")
|
||||
async def batch_v3_status(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
# Fallback: check disk if SSE didn't deliver
|
||||
if job["status"] == "uploaded" and job.get("job_dir"):
|
||||
result_data = batch_v3._read_result_files(Path(job["job_dir"]))
|
||||
if result_data.get("script"):
|
||||
job["analysis"] = {
|
||||
"python_script": result_data["script"],
|
||||
"summary": result_data.get("summary", {}),
|
||||
}
|
||||
job["status"] = "analyzed"
|
||||
|
||||
analysis = job.get("analysis", {})
|
||||
return {
|
||||
"status": job["status"],
|
||||
"total": job.get("total_files", 0),
|
||||
"processed": job.get("processed", 0),
|
||||
"errors": job.get("errors", [])[:20],
|
||||
"script": analysis.get("python_script", ""),
|
||||
"summary": analysis.get("summary", {}),
|
||||
"verified": job.get("verified", False),
|
||||
"verify_attempts": job.get("verify_attempts", 0),
|
||||
"verify_errors": job.get("verify_errors", []),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/batch-v3/download/{job_id}")
|
||||
async def batch_v3_download(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
if not job.get("output_file"):
|
||||
raise HTTPException(404, "Result not ready")
|
||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||
|
||||
|
||||
# ── SSR Generator ───────────────────────────────────────────────────────────
|
||||
@@ -1655,11 +1317,6 @@ async def batch_v3_download(job_id: str, request: Request):
|
||||
_ssr_jobs: dict[str, dict] = {}
|
||||
|
||||
|
||||
@app.get("/ssr", response_class=HTMLResponse)
|
||||
async def ssr_page():
|
||||
return Path("static/ssr.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _import_ssr_scripts():
|
||||
"""Import smeta-railway scripts (installed via pip install -e)."""
|
||||
import sys
|
||||
@@ -1671,113 +1328,6 @@ def _import_ssr_scripts():
|
||||
sys.path.insert(0, scripts_dir)
|
||||
|
||||
|
||||
@app.post("/api/ssr/upload")
|
||||
async def ssr_upload(request: Request):
|
||||
"""Upload ZIP (+ optional xlsx) → fill or generate SSR → return preview."""
|
||||
user = _get_user(request)
|
||||
form = await request.form()
|
||||
zip_file: UploadFile = form.get("zip_file")
|
||||
if not zip_file or not zip_file.filename.lower().endswith(".zip"):
|
||||
raise HTTPException(400, "ZIP file required")
|
||||
|
||||
xlsx_file: UploadFile = form.get("xlsx_file")
|
||||
mode = form.get("mode", "generate") # "fill" or "generate"
|
||||
|
||||
# Params (for generate mode)
|
||||
winter_pct = float(form.get("winter_pct", 3.2))
|
||||
control_pct = float(form.get("control_pct", 0.55))
|
||||
reserve_pct = float(form.get("reserve_pct", 1.0))
|
||||
vat_pct = float(form.get("vat_pct", 22.0))
|
||||
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
job_dir = data_dir / "_ssr" / user / job_id
|
||||
job_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Save ZIP
|
||||
zip_path = job_dir / "source.zip"
|
||||
zip_path.write_bytes(await zip_file.read())
|
||||
|
||||
_import_ssr_scripts()
|
||||
|
||||
if mode == "fill" and xlsx_file:
|
||||
# Mode: fill existing xlsx with GGE data
|
||||
try:
|
||||
from fill_raspredelenie import fill_raspredelenie_from_zip
|
||||
except ImportError:
|
||||
raise HTTPException(500, "smeta-railway scripts not found")
|
||||
|
||||
xlsx_path = job_dir / xlsx_file.filename
|
||||
xlsx_path.write_bytes(await xlsx_file.read())
|
||||
|
||||
output_path = str(job_dir / f"filled_{xlsx_file.filename}")
|
||||
result = fill_raspredelenie_from_zip(str(zip_path), str(xlsx_path), output_path)
|
||||
|
||||
if "error" in result:
|
||||
raise HTTPException(400, result["error"])
|
||||
|
||||
html_path = str(job_dir / "protocol.html")
|
||||
Path(html_path).write_text(result["html"], encoding="utf-8")
|
||||
|
||||
_ssr_jobs[job_id] = {
|
||||
"user": user, "job_dir": str(job_dir),
|
||||
"xlsx_path": output_path, "html_path": html_path,
|
||||
"result": result["stats"],
|
||||
}
|
||||
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"preview_html": result["html"],
|
||||
"stats": result["stats"],
|
||||
"mode": "fill",
|
||||
}
|
||||
|
||||
else:
|
||||
# Mode: generate new SSR from scratch
|
||||
try:
|
||||
from parse_gge_structure import parse_gge_from_zip
|
||||
from generate_ssr import generate_ssr_from_data
|
||||
except ImportError:
|
||||
raise HTTPException(500, "smeta-railway scripts not found")
|
||||
|
||||
data = parse_gge_from_zip(str(zip_path))
|
||||
xlsx_path = str(job_dir / "ssr.xlsx")
|
||||
html_path = str(job_dir / "ssr.html")
|
||||
result = generate_ssr_from_data(
|
||||
data, xlsx_path, html_path,
|
||||
winter_pct=winter_pct, control_pct=control_pct,
|
||||
reserve_pct=reserve_pct, vat_pct=vat_pct,
|
||||
)
|
||||
|
||||
_ssr_jobs[job_id] = {
|
||||
"user": user, "job_dir": str(job_dir),
|
||||
"xlsx_path": xlsx_path, "html_path": html_path,
|
||||
"result": result,
|
||||
}
|
||||
|
||||
preview_html = Path(html_path).read_text(encoding="utf-8")
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"preview_html": preview_html,
|
||||
"stats": result,
|
||||
"mode": "generate",
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/ssr/preview/{job_id}")
|
||||
async def ssr_preview(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(_ssr_jobs.get(job_id), user)
|
||||
return HTMLResponse(Path(job["html_path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@app.get("/api/ssr/download/{job_id}")
|
||||
async def ssr_download(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(_ssr_jobs.get(job_id), user)
|
||||
return FileResponse(job["xlsx_path"], filename="ssr_generated.xlsx")
|
||||
|
||||
|
||||
# ── Wizard Aggregator ──────────────────────────────────────────────────────
|
||||
|
||||
def _import_smeta_railway():
|
||||
@@ -1793,166 +1343,32 @@ def _import_smeta_railway():
|
||||
_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
|
||||
|
||||
# Смонтированные роутеры не имели auth вообще → аноним жёг LLM/RAG-бюджет и грузил
|
||||
# файлы (Fable verify). Гейт на уровне монтирования — БЕЗ правки чужого пакета smeta_railway.
|
||||
# Живой чат их не использует (только депрекированные generate/reference/wizard).
|
||||
app.include_router(_wizard_router, prefix="/api/wizard", dependencies=[Depends(_auth_dep)])
|
||||
app.include_router(_gen_router, prefix="/api/gen", dependencies=[Depends(_auth_dep)])
|
||||
app.include_router(_chat_sr_router, prefix="/api/ref", dependencies=[Depends(_auth_dep)])
|
||||
|
||||
|
||||
@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
|
||||
|
||||
_get_user(request) # закрыт от анонима (был публичный compute-эндпоинт)
|
||||
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:
|
||||
logger.exception("check_yaml failed") # детали — в лог оператору, не клиенту
|
||||
return {"error": "Не удалось проверить конфигурацию", "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."""
|
||||
_get_user(request) # был аноним; ниже мёртвый код с сырым traceback — закрыть до ревайва
|
||||
# ⛔ Путь LLM→движок пока НЕ оживлён: код ниже зовёт несуществующие методы
|
||||
# (ProjectConfig.from_yaml_string / NormResources.from_dict / FGISLookup(region=))
|
||||
# и отдавал сырой traceback пользователю. Кнопка «Генерация» депрекирована
|
||||
# (chat.html, 2026-05-07), путь достижим лишь прямым URL. До keystone-ревайва
|
||||
# (роадмап: оживить контракт с fail-loud цен + проверенным маппингом НР/СП по
|
||||
# 812/774/пр) — честный ответ вместо сырой ошибки. Логика ниже сохранена как
|
||||
# стартовая точка ревайва.
|
||||
return {
|
||||
"error": "Автоматический расчёт сметы пока в разработке — функция скоро появится.",
|
||||
"download_url": None,
|
||||
}
|
||||
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}
|
||||
# ── Депрекированные страницы → всё переехало в чат (Fable retire 2026-07-18) ──
|
||||
# Пакетная обработка/SSR/генерация: там ИИ-скрипт исполнялся на хосте (риск RCE
|
||||
# через смету-с-начинкой) + анонимные роуты. Функционал давно заменён чатом.
|
||||
from fastapi.responses import RedirectResponse as _DepRedirect
|
||||
|
||||
|
||||
@app.get("/api/gen/download/{job_id}")
|
||||
async def download_estimate(job_id: str, request: Request):
|
||||
"""Download generated Excel estimate."""
|
||||
_get_user(request) # был публичный доступ к файлам по угадываемому id
|
||||
safe_id = Path(job_id).name # без traversal в имени файла
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
|
||||
xlsx_path = data_dir / f"estimate_{safe_id}.xlsx"
|
||||
if not xlsx_path.exists():
|
||||
raise HTTPException(404, "Файл не найден")
|
||||
return FileResponse(str(xlsx_path), filename=f"smeta_{safe_id}.xlsx")
|
||||
async def _deprecated_moved():
|
||||
return _DepRedirect("/", status_code=302)
|
||||
|
||||
|
||||
for _dep_url in ("/batch", "/batch2", "/batch3", "/ssr", "/wizard",
|
||||
"/generate", "/reference", "/check"):
|
||||
app.add_api_route(_dep_url, _deprecated_moved, methods=["GET"], include_in_schema=False)
|
||||
|
||||
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