feat: генератор ССР в веб-интерфейсе (/ssr)
Новая страница: загрузка ZIP с GGE → парсинг → 9 листов xlsx + HTML-превью в iframe для валидации перед скачиванием. Кнопка "ССР" в навигации чата. Эндпоинты: /api/ssr/upload, /api/ssr/preview, /api/ssr/download. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from fastapi import FastAPI, HTTPException, Request, UploadFile
|
from fastapi import FastAPI, HTTPException, Request, UploadFile
|
||||||
@@ -37,35 +38,54 @@ elif AI_BACKEND == "auto":
|
|||||||
"""
|
"""
|
||||||
msg_lower = message.lower()
|
msg_lower = message.lower()
|
||||||
|
|
||||||
# Keywords that need Claude Code (file operations)
|
# Step 1: Strong file indicators (high confidence → Claude)
|
||||||
claude_keywords = [
|
file_actions = [
|
||||||
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
|
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
|
||||||
"перенеси данн", "измени файл", "отредактируй", "скопируй",
|
"перенеси данн", "измени файл", "отредактируй", "скопируй",
|
||||||
"проверь смет", "проверь файл", "открой файл", "покажи файл",
|
"проверь файл", "открой файл", "покажи файл",
|
||||||
"загруж", "прикреп", "файл", ".xlsx", ".docx", ".pdf", ".csv",
|
"загруж", "прикреп", ".xlsx", ".docx", ".pdf", ".csv",
|
||||||
"внеси", "обнови", "заполни", "строк", "ячейк", "лист",
|
"ячейк",
|
||||||
"ссрсс", "ссрс", "ведомост", "смет",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
# Check if message references files in work directory (partial match)
|
# Step 2: Strong reference indicators (high confidence → GLM)
|
||||||
|
reference_words = [
|
||||||
|
"какой нр", "какой сп", "какая нр", "какая сп",
|
||||||
|
"коэффициент", "зимнее удорожан", "временные здани",
|
||||||
|
"расценк", "найди расценку", "найди норму",
|
||||||
|
"сметная цена", "цена материал",
|
||||||
|
"приказ ", "фснб", "методик",
|
||||||
|
"посчитай нр", "посчитай сп", "рассчитай",
|
||||||
|
"что ты умеешь", "помощь", "help",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Step 3: Check file mentions in work directory
|
||||||
from claude_bridge_glm import get_work_dir as _get_wd
|
from claude_bridge_glm import get_work_dir as _get_wd
|
||||||
work_dir = _get_wd(username, tab_id)
|
work_dir = _get_wd(username, tab_id)
|
||||||
has_files = False
|
|
||||||
mentions_file = False
|
mentions_file = False
|
||||||
if work_dir.exists():
|
if work_dir.exists():
|
||||||
for f in work_dir.iterdir():
|
for f in work_dir.iterdir():
|
||||||
if f.is_file() and not f.name.startswith("."):
|
if f.is_file() and not f.name.startswith("."):
|
||||||
has_files = True
|
|
||||||
# Check partial name match (without extension)
|
|
||||||
stem = f.stem.lower()
|
stem = f.stem.lower()
|
||||||
parts = [p for p in stem.replace("-", " ").replace("_", " ").split() if len(p) > 2]
|
parts = [p for p in stem.replace("-", " ").replace("_", " ").split() if len(p) > 2]
|
||||||
if any(p in msg_lower for p in parts):
|
if any(p in msg_lower for p in parts):
|
||||||
mentions_file = True
|
mentions_file = True
|
||||||
break
|
break
|
||||||
|
|
||||||
has_keyword = any(kw in msg_lower for kw in claude_keywords)
|
is_file_action = mentions_file or any(kw in msg_lower for kw in file_actions)
|
||||||
|
is_reference = any(kw in msg_lower for kw in reference_words)
|
||||||
|
|
||||||
|
# Decision: file action wins if explicit, otherwise reference
|
||||||
|
if is_file_action and not is_reference:
|
||||||
|
use_claude = True
|
||||||
|
elif is_reference and not is_file_action:
|
||||||
|
use_claude = False
|
||||||
|
elif is_file_action and is_reference:
|
||||||
|
# Ambiguous — file actions take priority (safer)
|
||||||
|
use_claude = True
|
||||||
|
else:
|
||||||
|
# Neither — default to GLM (normative reference)
|
||||||
|
use_claude = False
|
||||||
|
|
||||||
use_claude = mentions_file or has_keyword
|
|
||||||
stream_fn = _stream_claude if use_claude else _stream_sonnet
|
stream_fn = _stream_claude if use_claude else _stream_sonnet
|
||||||
async for chunk in stream_fn(message, username, tab_id):
|
async for chunk in stream_fn(message, username, tab_id):
|
||||||
yield chunk
|
yield chunk
|
||||||
@@ -87,6 +107,22 @@ async def startup():
|
|||||||
init_db()
|
init_db()
|
||||||
|
|
||||||
|
|
||||||
|
# Rate limiting for chat API (10 requests/minute per user)
|
||||||
|
_chat_rate: dict[str, list[float]] = {}
|
||||||
|
CHAT_RATE_LIMIT = 10
|
||||||
|
CHAT_RATE_WINDOW = 60
|
||||||
|
|
||||||
|
|
||||||
|
def _check_rate_limit(user: str):
|
||||||
|
now = time.time()
|
||||||
|
times = _chat_rate.get(user, [])
|
||||||
|
times = [t for t in times if now - t < CHAT_RATE_WINDOW]
|
||||||
|
_chat_rate[user] = times
|
||||||
|
if len(times) >= CHAT_RATE_LIMIT:
|
||||||
|
raise HTTPException(429, "Too many requests. Wait a minute.")
|
||||||
|
times.append(now)
|
||||||
|
|
||||||
|
|
||||||
def _get_user(request: Request) -> str:
|
def _get_user(request: Request) -> str:
|
||||||
auth = request.headers.get("authorization", "")
|
auth = request.headers.get("authorization", "")
|
||||||
token = auth.removeprefix("Bearer ").strip()
|
token = auth.removeprefix("Bearer ").strip()
|
||||||
@@ -118,7 +154,24 @@ async def login(request: Request):
|
|||||||
token = authenticate(username, password, client_ip)
|
token = authenticate(username, password, client_ip)
|
||||||
if not token:
|
if not token:
|
||||||
raise HTTPException(401, "Wrong credentials")
|
raise HTTPException(401, "Wrong credentials")
|
||||||
return {"token": token, "username": username}
|
from auth import _make_refresh_token, get_token_role
|
||||||
|
role = get_token_role(token)
|
||||||
|
refresh = _make_refresh_token(username, role)
|
||||||
|
return {"token": token, "refresh_token": refresh, "username": username}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/refresh")
|
||||||
|
async def refresh_token(request: Request):
|
||||||
|
"""Exchange refresh token for new access token."""
|
||||||
|
body = await request.json()
|
||||||
|
refresh = body.get("refresh_token", "")
|
||||||
|
if not refresh:
|
||||||
|
raise HTTPException(400, "No refresh token")
|
||||||
|
from auth import refresh_access_token
|
||||||
|
new_token = refresh_access_token(refresh)
|
||||||
|
if not new_token:
|
||||||
|
raise HTTPException(401, "Invalid or expired refresh token")
|
||||||
|
return {"token": new_token}
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/register")
|
@app.post("/api/register")
|
||||||
@@ -195,6 +248,7 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
|
|||||||
@app.post("/api/chat")
|
@app.post("/api/chat")
|
||||||
async def chat(request: Request):
|
async def chat(request: Request):
|
||||||
user = _get_user(request)
|
user = _get_user(request)
|
||||||
|
_check_rate_limit(user)
|
||||||
body = await request.json()
|
body = await request.json()
|
||||||
message = body.get("message", "").strip()
|
message = body.get("message", "").strip()
|
||||||
tab_id = _get_tab(request, body)
|
tab_id = _get_tab(request, body)
|
||||||
@@ -309,8 +363,8 @@ async def clear_files(request: Request):
|
|||||||
|
|
||||||
|
|
||||||
# === Batch processing ===
|
# === Batch processing ===
|
||||||
from batch import analyze_structure, create_job, extract_zip, get_job, run_batch
|
from xlsx_utils import extract_zip
|
||||||
import batch_v2
|
import batch_v3
|
||||||
import threading
|
import threading
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
@@ -322,96 +376,7 @@ async def batch_page():
|
|||||||
return Path("static/batch.html").read_text(encoding="utf-8")
|
return Path("static/batch.html").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/batch/upload")
|
# V1 batch endpoints removed — use /api/batch-v3/* instead
|
||||||
async def batch_upload(request: Request):
|
|
||||||
"""Upload zip + target file, extract, analyze structure."""
|
|
||||||
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 = BATCH_DIR / user / job_id
|
|
||||||
job_dir.mkdir(parents=True, exist_ok=True)
|
|
||||||
|
|
||||||
# Save target
|
|
||||||
target_path = job_dir / Path(target_file.filename).name
|
|
||||||
target_content = await target_file.read()
|
|
||||||
target_path.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))
|
|
||||||
|
|
||||||
# Analyze with LLM
|
|
||||||
analysis = await analyze_structure(source_files, str(target_path), task_desc)
|
|
||||||
|
|
||||||
job = create_job(job_id)
|
|
||||||
job["source_dir"] = str(source_dir)
|
|
||||||
job["target_file"] = str(target_path)
|
|
||||||
job["total_files"] = len(source_files)
|
|
||||||
job["analysis"] = analysis
|
|
||||||
job["status"] = "analyzed"
|
|
||||||
|
|
||||||
return {
|
|
||||||
"job_id": job_id,
|
|
||||||
"total_files": len(source_files),
|
|
||||||
"analysis": analysis,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/batch/run/{job_id}")
|
|
||||||
async def batch_run(job_id: str, request: Request):
|
|
||||||
"""Confirm and run the batch script."""
|
|
||||||
_get_user(request)
|
|
||||||
job = get_job(job_id)
|
|
||||||
if not job:
|
|
||||||
raise HTTPException(404, "Job not found")
|
|
||||||
|
|
||||||
script = job.get("analysis", {}).get("python_script", "")
|
|
||||||
if not script:
|
|
||||||
raise HTTPException(400, "No script generated")
|
|
||||||
|
|
||||||
# Run in background thread
|
|
||||||
threading.Thread(
|
|
||||||
target=run_batch,
|
|
||||||
args=(job_id, script, job["source_dir"], job["target_file"]),
|
|
||||||
daemon=True,
|
|
||||||
).start()
|
|
||||||
|
|
||||||
return {"status": "started", "job_id": job_id}
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/batch/status/{job_id}")
|
|
||||||
async def batch_status(job_id: str, request: Request):
|
|
||||||
_get_user(request)
|
|
||||||
job = get_job(job_id)
|
|
||||||
if not job:
|
|
||||||
raise HTTPException(404, "Job not found")
|
|
||||||
return {
|
|
||||||
"status": job["status"],
|
|
||||||
"total": job.get("total_files", 0),
|
|
||||||
"processed": job.get("processed", 0),
|
|
||||||
"errors": job.get("errors", [])[:10],
|
|
||||||
"description": job.get("analysis", {}).get("description", ""),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/batch/download/{job_id}")
|
|
||||||
async def batch_download(job_id: str, request: Request):
|
|
||||||
_get_user(request)
|
|
||||||
job = get_job(job_id)
|
|
||||||
if not job or not job.get("output_file"):
|
|
||||||
raise HTTPException(404, "Result not ready")
|
|
||||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
|
||||||
|
|
||||||
|
|
||||||
# === Batch V2: Claude Code analysis ===
|
# === Batch V2: Claude Code analysis ===
|
||||||
@@ -459,14 +424,14 @@ async def batch_v2_upload(request: Request):
|
|||||||
target_only_dir.mkdir(exist_ok=True)
|
target_only_dir.mkdir(exist_ok=True)
|
||||||
shutil.copy2(str(target_path), str(target_only_dir / target_name))
|
shutil.copy2(str(target_path), str(target_only_dir / target_name))
|
||||||
target_csv_dir = str(job_dir / "target_csv")
|
target_csv_dir = str(job_dir / "target_csv")
|
||||||
batch_v2.convert_all_to_csv(str(target_only_dir), target_csv_dir)
|
batch_v3.convert_all_to_csv(str(target_only_dir), target_csv_dir)
|
||||||
shutil.rmtree(str(target_only_dir))
|
shutil.rmtree(str(target_only_dir))
|
||||||
|
|
||||||
# Select and convert SAMPLE files (not all — could be 2000+)
|
# Select and convert SAMPLE files (not all — could be 2000+)
|
||||||
sample_info = batch_v2.prepare_samples(str(source_dir), job_dir, {})
|
sample_info = batch_v3.prepare_samples(str(source_dir), job_dir, {})
|
||||||
|
|
||||||
# Create job
|
# Create job
|
||||||
job = batch_v2.create_job(job_id)
|
job = batch_v3.create_job(job_id)
|
||||||
job["source_dir"] = str(source_dir)
|
job["source_dir"] = str(source_dir)
|
||||||
job["target_file"] = str(target_path)
|
job["target_file"] = str(target_path)
|
||||||
job["target_name"] = target_name
|
job["target_name"] = target_name
|
||||||
@@ -492,7 +457,7 @@ async def batch_v2_upload(request: Request):
|
|||||||
async def batch_v2_analyze(job_id: str, request: Request):
|
async def batch_v2_analyze(job_id: str, request: Request):
|
||||||
"""Start Claude Code analysis — returns SSE stream."""
|
"""Start Claude Code analysis — returns SSE stream."""
|
||||||
_get_user(request)
|
_get_user(request)
|
||||||
job = batch_v2.get_job(job_id)
|
job = batch_v3.get_job(job_id)
|
||||||
if not job:
|
if not job:
|
||||||
raise HTTPException(404, "Job not found")
|
raise HTTPException(404, "Job not found")
|
||||||
|
|
||||||
@@ -503,7 +468,7 @@ async def batch_v2_analyze(job_id: str, request: Request):
|
|||||||
sample_info = job["sample_info"]
|
sample_info = job["sample_info"]
|
||||||
|
|
||||||
async def event_stream():
|
async def event_stream():
|
||||||
async for event in batch_v2.run_claude_analysis(
|
async for event in batch_v3.run_claude_analysis(
|
||||||
job_dir, task_desc, target_name, total_files, sample_info
|
job_dir, task_desc, target_name, total_files, sample_info
|
||||||
):
|
):
|
||||||
etype = event.get("type", "")
|
etype = event.get("type", "")
|
||||||
@@ -533,7 +498,7 @@ async def batch_v2_analyze(job_id: str, request: Request):
|
|||||||
async def batch_v2_run(job_id: str, request: Request):
|
async def batch_v2_run(job_id: str, request: Request):
|
||||||
"""Confirm and run the Claude-generated script."""
|
"""Confirm and run the Claude-generated script."""
|
||||||
_get_user(request)
|
_get_user(request)
|
||||||
job = batch_v2.get_job(job_id)
|
job = batch_v3.get_job(job_id)
|
||||||
if not job:
|
if not job:
|
||||||
raise HTTPException(404, "Job not found")
|
raise HTTPException(404, "Job not found")
|
||||||
|
|
||||||
@@ -542,7 +507,7 @@ async def batch_v2_run(job_id: str, request: Request):
|
|||||||
raise HTTPException(400, "No script generated")
|
raise HTTPException(400, "No script generated")
|
||||||
|
|
||||||
threading.Thread(
|
threading.Thread(
|
||||||
target=batch_v2.run_batch_v2,
|
target=batch_v3.run_batch_v2,
|
||||||
args=(job_id, script, job["source_dir"], job["target_file"]),
|
args=(job_id, script, job["source_dir"], job["target_file"]),
|
||||||
daemon=True,
|
daemon=True,
|
||||||
).start()
|
).start()
|
||||||
@@ -553,7 +518,7 @@ async def batch_v2_run(job_id: str, request: Request):
|
|||||||
@app.get("/api/batch-v2/status/{job_id}")
|
@app.get("/api/batch-v2/status/{job_id}")
|
||||||
async def batch_v2_status(job_id: str, request: Request):
|
async def batch_v2_status(job_id: str, request: Request):
|
||||||
_get_user(request)
|
_get_user(request)
|
||||||
job = batch_v2.get_job(job_id)
|
job = batch_v3.get_job(job_id)
|
||||||
if not job:
|
if not job:
|
||||||
raise HTTPException(404, "Job not found")
|
raise HTTPException(404, "Job not found")
|
||||||
|
|
||||||
@@ -561,7 +526,7 @@ async def batch_v2_status(job_id: str, request: Request):
|
|||||||
# but SSE didn't deliver the done event
|
# but SSE didn't deliver the done event
|
||||||
if job["status"] == "uploaded" and job.get("job_dir"):
|
if job["status"] == "uploaded" and job.get("job_dir"):
|
||||||
job_dir = Path(job["job_dir"])
|
job_dir = Path(job["job_dir"])
|
||||||
result_data = batch_v2._read_result_files(job_dir)
|
result_data = batch_v3._read_result_files(job_dir)
|
||||||
if result_data.get("script"):
|
if result_data.get("script"):
|
||||||
job["analysis"] = {
|
job["analysis"] = {
|
||||||
"python_script": result_data["script"],
|
"python_script": result_data["script"],
|
||||||
@@ -583,7 +548,7 @@ async def batch_v2_status(job_id: str, request: Request):
|
|||||||
@app.get("/api/batch-v2/download/{job_id}")
|
@app.get("/api/batch-v2/download/{job_id}")
|
||||||
async def batch_v2_download(job_id: str, request: Request):
|
async def batch_v2_download(job_id: str, request: Request):
|
||||||
_get_user(request)
|
_get_user(request)
|
||||||
job = batch_v2.get_job(job_id)
|
job = batch_v3.get_job(job_id)
|
||||||
if not job or not job.get("output_file"):
|
if not job or not job.get("output_file"):
|
||||||
raise HTTPException(404, "Result not ready")
|
raise HTTPException(404, "Result not ready")
|
||||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||||
@@ -890,6 +855,106 @@ async def batch_v3_download(job_id: str, request: Request):
|
|||||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||||
|
|
||||||
|
|
||||||
|
# ── SSR Generator ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# In-memory SSR job store (same pattern as batch)
|
||||||
|
_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")
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ssr/upload")
|
||||||
|
async def ssr_upload(request: Request):
|
||||||
|
"""Upload ZIP with GGE files → parse → 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")
|
||||||
|
|
||||||
|
# Optional params
|
||||||
|
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))
|
||||||
|
title = form.get("title", "")
|
||||||
|
|
||||||
|
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 from smeta-railway/scripts (pip install -e ../smeta-railway)
|
||||||
|
import sys
|
||||||
|
for scripts_dir in [
|
||||||
|
str(Path(__file__).resolve().parent / ".." / "smeta-railway" / "scripts"),
|
||||||
|
str(Path.home() / "smeta-railway" / "scripts"),
|
||||||
|
]:
|
||||||
|
if Path(scripts_dir).exists() and scripts_dir not in sys.path:
|
||||||
|
sys.path.insert(0, scripts_dir)
|
||||||
|
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")
|
||||||
|
|
||||||
|
# Parse GGE
|
||||||
|
data = parse_gge_from_zip(str(zip_path))
|
||||||
|
if title:
|
||||||
|
data["title"] = title
|
||||||
|
|
||||||
|
# Generate SSR
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Store job
|
||||||
|
_ssr_jobs[job_id] = {
|
||||||
|
"user": user,
|
||||||
|
"job_dir": str(job_dir),
|
||||||
|
"xlsx_path": xlsx_path,
|
||||||
|
"html_path": html_path,
|
||||||
|
"result": result,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Return preview HTML content + stats
|
||||||
|
preview_html = Path(html_path).read_text(encoding="utf-8")
|
||||||
|
return {
|
||||||
|
"job_id": job_id,
|
||||||
|
"preview_html": preview_html,
|
||||||
|
"stats": result,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/ssr/preview/{job_id}")
|
||||||
|
async def ssr_preview(job_id: str, request: Request):
|
||||||
|
_get_user(request)
|
||||||
|
job = _ssr_jobs.get(job_id)
|
||||||
|
if not job:
|
||||||
|
raise HTTPException(404, "Job not found")
|
||||||
|
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):
|
||||||
|
_get_user(request)
|
||||||
|
job = _ssr_jobs.get(job_id)
|
||||||
|
if not job:
|
||||||
|
raise HTTPException(404, "Job not found")
|
||||||
|
return FileResponse(job["xlsx_path"], filename="ssr_generated.xlsx")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|
||||||
|
|||||||
+30
-5
@@ -121,6 +121,7 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
|
|||||||
<div class="header-actions">
|
<div class="header-actions">
|
||||||
<button id="btn-admin" style="display:none" onclick="window.open('/admin','_blank')">Админ</button>
|
<button id="btn-admin" style="display:none" onclick="window.open('/admin','_blank')">Админ</button>
|
||||||
<button onclick="window.open('/batch3','_blank')">Пакетная</button>
|
<button onclick="window.open('/batch3','_blank')">Пакетная</button>
|
||||||
|
<button onclick="window.open('/ssr','_blank')">ССР</button>
|
||||||
<button onclick="showSessions()">История</button>
|
<button onclick="showSessions()">История</button>
|
||||||
<button onclick="resetSession()">Новый диалог</button>
|
<button onclick="resetSession()">Новый диалог</button>
|
||||||
<button onclick="listFiles()">Файлы</button>
|
<button onclick="listFiles()">Файлы</button>
|
||||||
@@ -140,6 +141,7 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
|
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
|
||||||
|
<div style="text-align:center;margin-top:4px"><a href="/static/security.html" target="_blank" style="font-size:.65rem;color:var(--text-muted);opacity:.4;text-decoration:none">О безопасности сервиса</a></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -161,11 +163,11 @@ const API = '';
|
|||||||
let token = localStorage.getItem('token');
|
let token = localStorage.getItem('token');
|
||||||
let pendingFiles = [];
|
let pendingFiles = [];
|
||||||
let streaming = false;
|
let streaming = false;
|
||||||
// Each tab gets its own session — allows multiple windows
|
// Session continuity: reuse last tabId from localStorage
|
||||||
// Support ?tab=UUID to open specific session
|
// New session only via "Новый чат" button or ?tab=UUID
|
||||||
const urlTab = new URLSearchParams(window.location.search).get('tab');
|
const urlTab = new URLSearchParams(window.location.search).get('tab');
|
||||||
let tabId = urlTab || sessionStorage.getItem('tabId') || crypto.randomUUID();
|
let tabId = urlTab || localStorage.getItem('tabId') || crypto.randomUUID();
|
||||||
sessionStorage.setItem('tabId', tabId);
|
localStorage.setItem('tabId', tabId);
|
||||||
|
|
||||||
function checkAdmin() {
|
function checkAdmin() {
|
||||||
try {
|
try {
|
||||||
@@ -206,6 +208,7 @@ async function doLogin(e) {
|
|||||||
const data = await r.json();
|
const data = await r.json();
|
||||||
token = data.token;
|
token = data.token;
|
||||||
localStorage.setItem('token', token);
|
localStorage.setItem('token', token);
|
||||||
|
if (data.refresh_token) localStorage.setItem('refresh_token', data.refresh_token);
|
||||||
checkAdmin();
|
checkAdmin();
|
||||||
showChat();
|
showChat();
|
||||||
addMsg('system', 'Добро пожаловать! Напишите вопрос или прикрепите файл.');
|
addMsg('system', 'Добро пожаловать! Напишите вопрос или прикрепите файл.');
|
||||||
@@ -214,14 +217,36 @@ async function doLogin(e) {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
async function tryRefreshToken() {
|
||||||
|
const rt = localStorage.getItem('refresh_token');
|
||||||
|
if (!rt) return false;
|
||||||
|
try {
|
||||||
|
const r = await fetch(API + '/api/refresh', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({refresh_token: rt})});
|
||||||
|
if (!r.ok) return false;
|
||||||
|
const data = await r.json();
|
||||||
|
token = data.token;
|
||||||
|
localStorage.setItem('token', token);
|
||||||
|
return true;
|
||||||
|
} catch { return false; }
|
||||||
|
}
|
||||||
function logout() {
|
function logout() {
|
||||||
token = null;
|
token = null;
|
||||||
|
localStorage.removeItem('refresh_token');
|
||||||
localStorage.removeItem('token');
|
localStorage.removeItem('token');
|
||||||
showLogin();
|
showLogin();
|
||||||
}
|
}
|
||||||
function authHeaders() {
|
function authHeaders() {
|
||||||
return {'Authorization': 'Bearer ' + token, 'X-Tab-Id': tabId};
|
return {'Authorization': 'Bearer ' + token, 'X-Tab-Id': tabId};
|
||||||
}
|
}
|
||||||
|
async function authFetch(url, opts={}) {
|
||||||
|
let r = await fetch(url, {...opts, headers: {...(opts.headers||{}), ...authHeaders()}});
|
||||||
|
if (r.status === 401) {
|
||||||
|
const refreshed = await tryRefreshToken();
|
||||||
|
if (refreshed) r = await fetch(url, {...opts, headers: {...(opts.headers||{}), ...authHeaders()}});
|
||||||
|
else { logout(); showLogin(); }
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Messages ---
|
// --- Messages ---
|
||||||
const msgs = document.getElementById('messages');
|
const msgs = document.getElementById('messages');
|
||||||
@@ -432,7 +457,7 @@ async function sendMessage() {
|
|||||||
async function resetSession() {
|
async function resetSession() {
|
||||||
// Create new tab = new session, old one stays in DB
|
// Create new tab = new session, old one stays in DB
|
||||||
tabId = crypto.randomUUID();
|
tabId = crypto.randomUUID();
|
||||||
sessionStorage.setItem('tabId', tabId);
|
localStorage.setItem('tabId', tabId);
|
||||||
msgs.innerHTML = '';
|
msgs.innerHTML = '';
|
||||||
addMsg('system', 'Новый диалог начат.');
|
addMsg('system', 'Новый диалог начат.');
|
||||||
}
|
}
|
||||||
|
|||||||
+174
@@ -0,0 +1,174 @@
|
|||||||
|
<!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; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||||
|
.container { max-width: 900px; margin: 0 auto; }
|
||||||
|
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||||
|
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||||
|
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
|
||||||
|
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||||
|
.card.hidden { display: none; }
|
||||||
|
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||||
|
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||||
|
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||||
|
input[type=number] { width: 80px; padding: .4rem; border: 1.5px solid var(--border); border-radius: 6px; font-size: .9rem; }
|
||||||
|
.params-row { display: flex; flex-wrap: wrap; gap: 1rem; margin: .8rem 0; }
|
||||||
|
.param { display: flex; flex-direction: column; }
|
||||||
|
.param label { font-size: .8rem; font-weight: 500; }
|
||||||
|
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||||
|
button:hover { background: #a83830; }
|
||||||
|
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||||
|
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||||
|
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
|
||||||
|
@keyframes spin { to { transform: rotate(360deg); } }
|
||||||
|
.error { color: var(--accent); margin-top: .5rem; font-size: .85rem; }
|
||||||
|
.stats { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); flex-wrap: wrap; }
|
||||||
|
.stats span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
|
||||||
|
.btn-download { background: var(--green); margin-top: 1rem; font-size: 1rem; padding: .8rem 2rem; }
|
||||||
|
.btn-download:hover { background: #246e45; }
|
||||||
|
#preview-frame { width: 100%; border: 1px solid var(--border); border-radius: var(--radius); min-height: 400px; background: #fff; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<a class="back" href="/">← Вернуться в чат</a>
|
||||||
|
<h1>Генератор ССР <span class="badge">из GGE</span></h1>
|
||||||
|
<p class="subtitle">Загрузите ZIP с GGE-файлами — получите сводный сметный расчёт (9 листов) с превью</p>
|
||||||
|
|
||||||
|
<!-- Step 1: Upload -->
|
||||||
|
<div class="card" id="step-upload">
|
||||||
|
<label>Архив с GGE-файлами (.zip)</label>
|
||||||
|
<p class="hint">ZIP со всеми локальными сметами в формате GGE (до 2000 файлов, до 100 MB)</p>
|
||||||
|
<input type="file" id="zip-file" accept=".zip">
|
||||||
|
|
||||||
|
<label>Параметры расчёта</label>
|
||||||
|
<div class="params-row">
|
||||||
|
<div class="param">
|
||||||
|
<label>Зимнее, %</label>
|
||||||
|
<input type="number" id="p-winter" value="3.2" step="0.1" min="0" max="20">
|
||||||
|
</div>
|
||||||
|
<div class="param">
|
||||||
|
<label>Стройконтроль, %</label>
|
||||||
|
<input type="number" id="p-control" value="0.55" step="0.01" min="0" max="5">
|
||||||
|
</div>
|
||||||
|
<div class="param">
|
||||||
|
<label>Резерв, %</label>
|
||||||
|
<input type="number" id="p-reserve" value="1.0" step="0.5" min="0" max="10">
|
||||||
|
</div>
|
||||||
|
<div class="param">
|
||||||
|
<label>НДС, %</label>
|
||||||
|
<input type="number" id="p-vat" value="22" step="1" min="0" max="30">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button id="btn-upload" onclick="doUpload()">Генерировать ССР</button>
|
||||||
|
<div id="upload-error" class="error"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Step 2: Processing -->
|
||||||
|
<div class="card hidden" id="step-processing">
|
||||||
|
<span class="spinner"></span> Парсинг GGE-файлов и генерация ССР...
|
||||||
|
<p class="hint" style="margin-top:.5rem">Это может занять 10-30 секунд для крупных архивов</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Step 3: Preview + Download -->
|
||||||
|
<div class="card hidden" id="step-result">
|
||||||
|
<h2 style="margin-bottom:.5rem">Результат</h2>
|
||||||
|
<div id="stats" class="stats"></div>
|
||||||
|
<button class="btn-download" id="btn-download" onclick="doDownload()">Скачать XLSX (9 листов)</button>
|
||||||
|
<hr style="margin:1rem 0;border:none;border-top:1px solid var(--border)">
|
||||||
|
<h2 style="margin-bottom:.5rem">Превью</h2>
|
||||||
|
<iframe id="preview-frame" sandbox="allow-same-origin"></iframe>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (!token) location.href = '/';
|
||||||
|
|
||||||
|
let currentJobId = null;
|
||||||
|
|
||||||
|
async function doUpload() {
|
||||||
|
const zipInput = document.getElementById('zip-file');
|
||||||
|
const errorEl = document.getElementById('upload-error');
|
||||||
|
errorEl.textContent = '';
|
||||||
|
|
||||||
|
if (!zipInput.files.length) {
|
||||||
|
errorEl.textContent = 'Выберите ZIP-файл';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append('zip_file', zipInput.files[0]);
|
||||||
|
fd.append('winter_pct', document.getElementById('p-winter').value);
|
||||||
|
fd.append('control_pct', document.getElementById('p-control').value);
|
||||||
|
fd.append('reserve_pct', document.getElementById('p-reserve').value);
|
||||||
|
fd.append('vat_pct', document.getElementById('p-vat').value);
|
||||||
|
|
||||||
|
document.getElementById('btn-upload').disabled = true;
|
||||||
|
document.getElementById('step-processing').classList.remove('hidden');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/api/ssr/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Authorization': 'Bearer ' + token },
|
||||||
|
body: fd,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!resp.ok) {
|
||||||
|
const err = await resp.json();
|
||||||
|
throw new Error(err.detail || 'Upload failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await resp.json();
|
||||||
|
currentJobId = data.job_id;
|
||||||
|
|
||||||
|
// Show stats
|
||||||
|
const s = data.stats;
|
||||||
|
document.getElementById('stats').innerHTML =
|
||||||
|
`<span>Смет: ${s.estimates}</span>` +
|
||||||
|
`<span>Глав: ${s.chapters}</span>` +
|
||||||
|
`<span>Листов: ${s.sheets}</span>` +
|
||||||
|
`<span>СР-10: ${s.sr10_eff_pct.toFixed(3)}%</span>` +
|
||||||
|
`<span>Итого с НДС: ${Number(s.total_vat).toLocaleString('ru-RU', {minimumFractionDigits:2})} тыс.руб.</span>`;
|
||||||
|
|
||||||
|
// Show preview in iframe
|
||||||
|
const frame = document.getElementById('preview-frame');
|
||||||
|
frame.srcdoc = data.preview_html;
|
||||||
|
frame.style.height = '600px';
|
||||||
|
|
||||||
|
document.getElementById('step-processing').classList.add('hidden');
|
||||||
|
document.getElementById('step-result').classList.remove('hidden');
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
errorEl.textContent = e.message;
|
||||||
|
document.getElementById('step-processing').classList.add('hidden');
|
||||||
|
document.getElementById('btn-upload').disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function doDownload() {
|
||||||
|
if (!currentJobId) return;
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = `/api/ssr/download/${currentJobId}`;
|
||||||
|
// Add auth header via fetch+blob
|
||||||
|
fetch(a.href, { headers: { 'Authorization': 'Bearer ' + token } })
|
||||||
|
.then(r => r.blob())
|
||||||
|
.then(blob => {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = 'ssr_generated.xlsx';
|
||||||
|
link.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user