Files
smeta-web/main.py
T
anorandClaude Opus 4.8 ad8fefdb60 feat(chat): Ф2 — UI-селектор даты сметы в шапке чата
- Бейдж «🗓 Смета на: сегодня/ДД.ММ.ГГГГ» в шапке (акцентный при фиксации, приглушённый по
  умолчанию — 95% смет «на сегодня» ничего лишнего не видят). Тёмная тема через var(--accent/border).
- Клик → ввод даты (ГГГГ-ММ-ДД, пусто = сегодня); при непустом диалоге — предупреждение, что
  ранее посчитанное не пересчитается автоматически. POST /api/sessions/{tab}/date.
- Подтягивается при загрузке, switchChat (своя дата у каждого диалога), newChat (сброс на сегодня).
- Bump APP_VERSION 2026-07-18d.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 17:56:42 +10:00

1932 lines
78 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5."""
import asyncio
import json
import os
import re
import shutil
import time
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from auth import authenticate, verify_token, make_download_ticket, verify_download_ticket
from db import clear_history, delete_session, get_audit_log, get_feedback, get_history, get_history_any_user, init_db, list_sessions, log_action, ping as db_ping, save_feedback, save_message, set_session_title
from tus_upload import register_tus
from error_mask import looks_like_provider_error, PROVIDER_ERROR_MESSAGE
from archive_host import extract_archive_async
# Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task)
AI_BACKEND = os.environ.get("AI_BACKEND", "claude")
if AI_BACKEND == "glm":
from claude_bridge_glm import (
clear_session, get_work_dir, is_allowed_file,
list_user_files, stream_claude,
)
elif AI_BACKEND == "hybrid":
# DeepSeek для нормативных вопросов (95% запросов из логов),
# Claude CLI через подписку Pro/Max + Domain MCP — для агентских
# задач (открыть/проанализировать/заполнить xlsm). Без расходов на
# Anthropic API.
from claude_bridge_glm import (
clear_session, get_work_dir, is_allowed_file, list_user_files,
stream_claude as _stream_glm,
)
from claude_bridge import stream_claude as _stream_claude
from routing import decide_engine
async def stream_claude(message: str, username: str, tab_id: str = "default"):
# Файл из work_dir упомянут по имени → агентский путь (mentions_file).
from claude_bridge_glm import get_work_dir as _gw
msg_lower = message.lower()
work_dir = _gw(username, tab_id)
mentions_file = False
if work_dir.exists():
for f in work_dir.iterdir():
if f.is_file() and not f.name.startswith("."):
stem = f.stem.lower()
parts = [p for p in stem.replace("-", " ").replace("_", " ").split() if len(p) > 2]
if any(p in msg_lower for p in parts):
mentions_file = True
break
# Решение вынесено в routing.decide_engine (детерминированный юнит-тест).
stream_fn = _stream_claude if decide_engine(message, mentions_file) == "claude" else _stream_glm
async for chunk in stream_fn(message, username, tab_id):
yield chunk
elif AI_BACKEND == "auto":
from claude_bridge_glm import (
clear_session, get_work_dir, is_allowed_file, list_user_files,
)
from claude_bridge_sonnet import stream_claude as _stream_sonnet
from claude_bridge import stream_claude as _stream_claude
async def stream_claude(message: str, username: str, tab_id: str = "default"):
"""Auto-route: file-related → Claude Code, normative questions → GLM-5.
Logic:
1. Message mentions files/creating/editing → Claude
2. Message references uploaded file names → Claude
3. Everything else (НР, СП, коэффициенты, правила) → GLM
"""
msg_lower = message.lower()
# Step 1: Strong file indicators (high confidence → Claude)
file_actions = [
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
"перенеси данн", "измени файл", "отредактируй", "скопируй",
"проверь файл", "открой файл", "покажи файл",
"загруж", "прикреп", ".xlsx", ".docx", ".pdf", ".csv",
"ячейк",
]
# 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
work_dir = _get_wd(username, tab_id)
mentions_file = False
if work_dir.exists():
for f in work_dir.iterdir():
if f.is_file() and not f.name.startswith("."):
stem = f.stem.lower()
parts = [p for p in stem.replace("-", " ").replace("_", " ").split() if len(p) > 2]
if any(p in msg_lower for p in parts):
mentions_file = True
break
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
stream_fn = _stream_claude if use_claude else _stream_sonnet
async for chunk in stream_fn(message, username, tab_id):
yield chunk
else:
from claude_bridge import (
clear_session, get_work_dir, is_allowed_file,
list_user_files, stream_claude,
)
app = FastAPI(title="smeta-web")
app.mount("/static", StaticFiles(directory="static"), name="static")
MAX_UPLOAD_SIZE = 100 * 1024 * 1024 # 100 MB
MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-07-18d"
# Audit: path → action name mapping
_AUDIT_MAP = [
("POST", "/api/login", "login"),
("POST", "/api/register", "register"),
("POST", "/api/verify-email", "verify_email"),
("POST", "/api/refresh", "refresh"),
("POST", "/api/chat", "chat"),
("POST", "/api/upload", "upload"),
("GET", "/api/files/", "download"),
("GET", "/api/files", "list_files"),
("POST", "/api/clear-files", "clear_files"),
("POST", "/api/reset", "reset_session"),
("POST", "/api/batch-v2/", "batch_v2"),
("GET", "/api/batch-v2/", "batch_v2"),
("POST", "/api/batch-v3/", "batch_v3"),
("GET", "/api/batch-v3/", "batch_v3"),
("POST", "/api/ssr/", "ssr"),
("GET", "/api/ssr/", "ssr"),
("POST", "/api/check/", "check"),
("POST", "/api/gen/", "generate"),
("GET", "/api/gen/", "generate"),
("POST", "/api/wizard/", "wizard"),
("GET", "/api/wizard/", "wizard"),
("GET", "/api/ref/", "reference"),
("GET", "/api/history", "history"),
("GET", "/api/sessions", "sessions"),
("GET", "/api/admin/", "admin"),
("POST", "/api/admin/", "admin"),
]
_SKIP_PREFIXES = ("/static/", "/favicon", "/api/tus") # tus chunks are logged on completion, not per-PATCH
def _resolve_action(method: str, path: str) -> str | None:
if any(path.startswith(p) for p in _SKIP_PREFIXES):
return None
for m, prefix, action in _AUDIT_MAP:
if method == m and path.startswith(prefix):
# For admin sub-actions: admin.invite, admin.block, etc.
if action == "admin":
sub = path.removeprefix("/api/admin/").split("/")[0].split("?")[0]
return f"admin.{sub}" if sub else "admin"
return action
# Pages (GET /, /batch2, /admin, etc.) — skip
if not path.startswith("/api/"):
return None
return method.lower() + ":" + path
@app.on_event("startup")
async def startup():
init_db()
# Прогрев справочника ФГИС в фоне: системный промпт агента берёт квартал/регионы из диск-кэша
# БЕЗ сетевого вызова в async-пути (иначе первый чат заморозил бы весь сервер до таймаута сети).
try:
import threading
import ext_status
threading.Thread(target=ext_status.warm_reference, daemon=True).start()
except Exception: # noqa: BLE001
pass
# Actions logged manually in handlers (with richer detail)
_MANUAL_ACTIONS = {"login", "login_fail", "chat", "upload", "register", "register_fail"}
@app.middleware("http")
async def audit_middleware(request: Request, call_next):
method = request.method
path = request.url.path
action = _resolve_action(method, path)
response = await call_next(request)
if action is None or action in _MANUAL_ACTIONS:
return response
# Extract username from JWT (best-effort, don't fail)
username = None
try:
auth_header = request.headers.get("authorization", "")
tok = auth_header.removeprefix("Bearer ").strip()
if tok:
username = verify_token(tok)
except Exception:
pass
# Extract detail based on action
detail = None
if action == "download":
parts = path.split("/api/files/")
detail = parts[1] if len(parts) > 1 else None
elif action in ("batch_v2", "batch_v3", "ssr", "generate"):
sub = path.split("/")[-1] if "/" in path else None
detail = sub
ip = request.client.host if request.client else None
try:
log_action(username, action, method, path, detail, ip, response.status_code)
except Exception:
pass
return response
# 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:
auth = request.headers.get("authorization", "")
token = auth.removeprefix("Bearer ").strip()
if not token:
raise HTTPException(401, "No token")
user = verify_token(token)
if not user:
raise HTTPException(401, "Invalid token")
return user
def _get_tab(request: Request, body: dict | None = None) -> str:
if body and "tab_id" in body:
return body["tab_id"]
return request.headers.get("x-tab-id", "default")
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
# Кэш-бастинг главной (как /admin): без актуального ?v= → 302 на URL с v=APP_VERSION
# (новый URL ≠ закэшированный без query → промах кэша → свежий запрос → no-store).
# Прочие параметры (?tab=) сохраняем. Иначе браузер держит старый chat.html навсегда.
from fastapi.responses import RedirectResponse
from urllib.parse import urlencode
if request.query_params.get("v") != APP_VERSION:
params = dict(request.query_params)
params["v"] = APP_VERSION
return RedirectResponse(url=f"/?{urlencode(params)}", status_code=302)
return HTMLResponse(
Path("static/chat.html").read_text(encoding="utf-8"),
headers={
"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
"Pragma": "no-cache",
"Expires": "0",
},
)
@app.get("/api/version")
async def version():
"""Public — single source of UI version (stamped into .app-version on the front)."""
return {"version": APP_VERSION}
# Свежесть корпусной базы цен — чтобы сметчик видел, на какой период данные.
# Берём реальный ценовой период ИЗ данных (а не mtime файла: после git clone
# mtime = дата клонирования и врёт). Кэшируем — файлы корпуса по 5–12 МБ.
_DATA_PERIODS_CACHE = None
def _compute_data_periods():
base = Path(__file__).resolve().parent / "data" / "real_corpus"
rx = re.compile(r"(20[12]\d) ?Q([1-4])") # 2010–2029, отсекаем мусор вроде «2052 Q1»
srcs = [
("Корпус смет (расценки/цены)", "estimates_index.json"),
("База материалов (КА)", "ka_index.json"),
("База работ (ВОР)", "vor_index.json"),
]
result = []
for label, fn in srcs:
period = None
try:
txt = (base / fn).read_text(encoding="utf-8")
ms = rx.findall(txt)
if ms:
y, q = max(ms, key=lambda yq: (int(yq[0]), int(yq[1])))
period = f"{y} Q{q}"
except OSError:
pass
result.append({"label": label, "period": period})
return result
@app.get("/health")
async def health():
"""Public health-check для мониторинга: 503 если БД недоступна (критично),
иначе 200 с состоянием знаниевой базы. Чтобы владелец узнавал о падении не
от пользователя."""
checks = {}
healthy = True
try:
await asyncio.to_thread(db_ping)
checks["db"] = "ok"
except Exception as e: # noqa: BLE001
checks["db"] = f"error: {e}"
healthy = False
proj = os.environ.get("SMETA_PROJECT_DIR", "")
checks["knowledge_base"] = "ok" if (proj and Path(proj).exists()) else "missing"
# Свежесть мониторинга внешних источников (heartbeat чекера ext_check). Просрочка — это
# деградация ЗНАНИЙ (данные могли устареть), а не отказ сервиса → НЕ валим health в 503.
try:
import ext_state
age = ext_state.heartbeat_age_days()
checks["ext_watch"] = ("never" if age is None else
f"stale ({age:.0f}d)" if age > 8 else "ok")
except Exception: # noqa: BLE001
checks["ext_watch"] = "unknown"
payload = {"status": "ok" if healthy else "down", "checks": checks, "version": APP_VERSION}
return JSONResponse(payload, status_code=200 if healthy else 503)
@app.get("/api/data-version")
async def data_version():
"""Public — на какой ценовой период актуальна корпусная база (свежесть данных)."""
global _DATA_PERIODS_CACHE
if _DATA_PERIODS_CACHE is None:
_DATA_PERIODS_CACHE = await asyncio.to_thread(_compute_data_periods)
periods = [s["period"] for s in _DATA_PERIODS_CACHE if s["period"]]
newest = max(periods, key=lambda s: (int(s[:4]), int(s[-1]))) if periods else None
return {"newest_period": newest, "sources": _DATA_PERIODS_CACHE, "app_version": APP_VERSION}
# Resumable uploads (tus 1.0.0). Same-process, reuses auth + per-user work dir;
# the finished file lands in the work dir exactly like legacy /api/upload.
TUS_MAX_SIZE = 3 * 1024 * 1024 * 1024 # 3 GB
register_tus(
app,
get_user=_get_user,
get_work_dir=get_work_dir,
is_allowed_file=is_allowed_file,
log_action=log_action,
save_message=save_message,
max_size=TUS_MAX_SIZE,
staging_root=Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_tus",
allowed_hint="xlsx, xls, docx, pdf, csv, txt, xml, json, yaml, gge, esw, zip, rar, 7z и многотомные (.z01…/.001…)",
)
@app.post("/api/login")
async def login(request: Request):
body = await request.json()
username = body.get("username", "")
password = body.get("password", "")
client_ip = request.client.host if request.client else ""
token = authenticate(username, password, client_ip)
if not token:
log_action(username, "login_fail", "POST", "/api/login", None, client_ip, 401)
raise HTTPException(401, "Wrong credentials")
from auth import _make_refresh_token, get_token_role
role = get_token_role(token)
refresh = _make_refresh_token(username, role)
log_action(username, "login", "POST", "/api/login", f"role={role}", client_ip, 200)
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")
async def register(request: Request):
body = await request.json()
email = body.get("email", "")
password = body.get("password", "")
invite = body.get("invite", "")
from auth import register_user
result = register_user(email, password, invite)
client_ip = request.client.host if request.client else ""
if not result["ok"]:
log_action(email, "register_fail", "POST", "/api/register", result["error"], client_ip, 400)
raise HTTPException(400, result["error"])
log_action(email, "register", "POST", "/api/register", None, client_ip, 200)
# Send verification code via email
code = result.get("code", "")
if code:
from email_service import send_verification_code
sent = send_verification_code(email, code)
if not sent:
return {"message": "Аккаунт создан, но email не отправлен. Обратитесь к администратору."}
return {"message": result["message"]}
@app.post("/api/verify-email")
async def verify_email_endpoint(request: Request):
body = await request.json()
email = body.get("email", "")
code = body.get("code", "")
from auth import verify_email
result = verify_email(email, code)
if not result["ok"]:
raise HTTPException(400, result["error"])
return {"message": result["message"]}
@app.get("/register", response_class=HTMLResponse)
async def register_page():
return Path("static/register.html").read_text(encoding="utf-8")
def _work_dir_snapshot(work_dir: Path) -> dict:
"""Map filename -> (mtime_ns, size) for visible files in work_dir."""
snap = {}
for f in work_dir.iterdir():
if f.is_file() and not f.name.startswith("."):
st = f.stat()
snap[f.name] = (st.st_mtime_ns, st.st_size)
return snap
def _sse_payload_text(chunk: str) -> str:
"""Собрать text/result из data-строк SSE-чанка (для детекции ошибок)."""
parts = []
for line in chunk.split("\n"):
if line.startswith("data: "):
try:
d = json.loads(line[6:])
parts.append(d.get("text") or d.get("result") or "")
except Exception:
pass
return "".join(parts)
async def _stream_and_save(message: str, user: str, tab_id: str):
"""Wrap stream_claude to save messages to DB."""
save_message(user, tab_id, "user", message)
# Снимок work_dir ДО ответа: после ответа diff покажет файлы, которые
# агент создал/изменил, и пользователь получит кнопки скачивания в чате.
work_dir = get_work_dir(user, tab_id)
before = _work_dir_snapshot(work_dir)
full_response = ""
errored = False
async for chunk in stream_claude(message, user, tab_id):
# Guard: сырая ошибка провайдера (401/rate/overloaded) не должна утечь
# юзеру ни в стрим, ни в историю (инцидент 2026-07-15). Маскируем и
# обрываем — после ошибки провайдера полезного ответа уже не будет.
if "event: text" in chunk or "event: done" in chunk:
payload = _sse_payload_text(chunk)
if payload and looks_like_provider_error(payload):
errored = True
log_action(user, "agent_error", "STREAM", "/api/chat",
payload[:200], None, 502)
yield f"event: text\ndata: {json.dumps({'text': PROVIDER_ERROR_MESSAGE}, ensure_ascii=False)}\n\n"
yield f"event: done\ndata: {json.dumps({'result': ''}, ensure_ascii=False)}\n\n"
break
yield chunk
# Collect text for saving
if "event: text" in chunk:
for line in chunk.split("\n"):
if line.startswith("data: "):
try:
d = json.loads(line[6:])
full_response += d.get("text", "")
except Exception:
pass
elif "event: done" in chunk:
for line in chunk.split("\n"):
if line.startswith("data: "):
try:
d = json.loads(line[6:])
if not full_response and d.get("result"):
full_response = d["result"]
except Exception:
pass
if errored:
save_message(user, tab_id, "assistant", PROVIDER_ERROR_MESSAGE)
return
if full_response:
save_message(user, tab_id, "assistant", full_response)
# Структурированная смета от агента (tool show_estimate пишет _estimate_panel.json) →
# событие estimate + панель. Файл читаем, эмитим, удаляем (не в кнопки, не повторно).
est_file = work_dir / "_estimate_panel.json"
if est_file.exists():
try:
est_data = json.loads(est_file.read_text(encoding="utf-8"))
if isinstance(est_data, dict) and est_data.get("positions"):
save_message(user, tab_id, "estimate", json.dumps(est_data, ensure_ascii=False))
yield f"event: estimate\ndata: {json.dumps(est_data, ensure_ascii=False)}\n\n"
except Exception:
pass
finally:
try:
est_file.unlink()
except OSError:
pass
# Форма КА (tool build_ka_form пишет _ka_panel.json) → панель офферов.
ka_file = work_dir / "_ka_panel.json"
if ka_file.exists():
try:
ka_data = json.loads(ka_file.read_text(encoding="utf-8"))
if isinstance(ka_data, dict) and ka_data.get("rows"):
save_message(user, tab_id, "ka_form", json.dumps(ka_data, ensure_ascii=False))
yield f"event: ka_form\ndata: {json.dumps(ka_data, ensure_ascii=False)}\n\n"
except Exception:
pass
finally:
try:
ka_file.unlink()
except OSError:
pass
# Новые/изменённые файлы за время ответа → кнопки скачивания в чате.
# .md включён: агент отдаёт отчёты и в markdown. Служебные *_csv/ —
# директории, отсекаются is_file().
new_files = []
for name, (mtime_ns, size) in sorted(_work_dir_snapshot(work_dir).items()):
if not (is_allowed_file(name) or name.lower().endswith(".md")):
continue
if before.get(name) != (mtime_ns, size):
new_files.append({"name": name, "size": size})
if new_files:
# role='files' — не попадает в history_recap (там только user/assistant),
# но восстанавливает кнопки при перезагрузке истории.
save_message(user, tab_id, "files", json.dumps(new_files, ensure_ascii=False))
yield f"event: files\ndata: {json.dumps({'files': new_files}, ensure_ascii=False)}\n\n"
@app.post("/api/chat")
async def chat(request: Request):
user = _get_user(request)
_check_rate_limit(user)
body = await request.json()
message = body.get("message", "").strip()
tab_id = _get_tab(request, body)
if not message:
raise HTTPException(400, "Empty message")
if len(message) > MAX_MESSAGE_LEN:
raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)")
ip = request.client.host if request.client else None
log_action(user, "chat", "POST", "/api/chat", f"tab={tab_id} | {message[:120]}", ip, 200)
return StreamingResponse(
_stream_and_save(message, user, tab_id),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
)
@app.post("/api/feedback")
async def feedback(request: Request):
"""Жалоба на ответ ассистента (кнопка «сообщить об ошибке»). Замыкает
петлю обратной связи — дефекты копятся в БД, а не теряются."""
user = _get_user(request)
body = await request.json()
comment = (body.get("comment") or "").strip()[:2000]
answer = (body.get("answer") or "")[:8000]
tab_id = _get_tab(request, body)
if not comment and not answer:
raise HTTPException(400, "Empty feedback")
await asyncio.to_thread(save_feedback, user, tab_id, comment, answer)
ip = request.client.host if request.client else None
log_action(user, "feedback", "POST", "/api/feedback", comment[:120], ip, 200)
return {"ok": True}
@app.get("/api/history")
async def history(request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
# Try own history first; if empty and admin — try any user's history for this tab
result = get_history(user, tab_id)
if not result:
from auth import get_token_role
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
if get_token_role(token) == "admin":
result = get_history_any_user(tab_id)
return result
@app.get("/api/sessions")
async def sessions(request: Request):
user = _get_user(request)
return list_sessions(user)
@app.post("/api/recalc")
async def recalc(request: Request):
"""Пересчитать смету движком по правкам объёмов (срез 6.2). Числа — из движка, не из JS.
body: {positions:[{code, qty, unit?}], meta?}. Тяжёлую загрузку движка гоним в
threadpool, чтобы не блокировать сервер."""
_get_user(request)
body = await request.json()
positions = body.get("positions") or []
if not isinstance(positions, list) or not positions:
raise HTTPException(400, "Нет позиций для расчёта")
meta = body.get("meta") if isinstance(body.get("meta"), dict) else {}
import estimate_contract as ec
if not ec.engine_enabled():
raise HTTPException(400, "Расчётный движок выключен")
import asyncio
try:
r = await asyncio.get_event_loop().run_in_executor(None, lambda: ec.calc_estimate(positions, meta))
except Exception: # noqa: BLE001 — движок недоступен/данные битые: честный 500, детали в логах uvicorn
import traceback; traceback.print_exc()
raise HTTPException(500, "Не удалось пересчитать")
return {
"title": meta.get("title") or "Смета (пересчёт)",
"positions": [{"code": p.get("code"), "name": p.get("name"), "unit": p.get("unit"),
"qty": p.get("qty"), "total": p.get("total")} for p in r.get("positions", [])],
"totals": {"grand_total": r.get("grand_total")},
"ok": r.get("ok"), "missing": r.get("missing"),
}
@app.delete("/api/sessions/{tab_id}")
async def delete_session_ep(tab_id: str, request: Request):
"""Удалить свой диалог ЦЕЛИКОМ (история в БД + загруженные файлы на диске).
Скоуп строго по владельцу из JWT — чужой не тронуть. confirm в UI обещает
«необратимо целиком» — поэтому чистим и work_dir, а не только строки (Fable Ф3)."""
user = _get_user(request)
removed = delete_session(user, tab_id)
try:
work_dir = get_work_dir(user, tab_id)
for f in work_dir.iterdir():
if f.name.startswith("."):
continue
if f.is_file():
f.unlink()
elif f.is_dir():
shutil.rmtree(f)
clear_session(user, tab_id)
except Exception: # noqa: BLE001 — файлов могло не быть; строки БД уже удалены
pass
return {"ok": True, "removed": removed}
@app.post("/api/sessions/{tab_id}/title")
async def rename_session_ep(tab_id: str, request: Request):
"""Переименовать свой диалог. Пустой/слишком длинный заголовок отклоняем."""
user = _get_user(request)
try:
body = await request.json()
assert isinstance(body, dict)
except Exception: # noqa: BLE001 — кривой JSON → честный 400, не 500
raise HTTPException(400, "Некорректный запрос")
title = (body.get("title") or "").strip()
if not title:
raise HTTPException(400, "Пустое название")
if len(title) > 120:
title = title[:120]
set_session_title(user, tab_id, title)
return {"ok": True, "title": title}
@app.get("/api/sessions/{tab_id}/date")
async def get_session_date_ep(tab_id: str, request: Request):
"""Дата сметы диалога: {date, pinned}. pinned=false → сегодня (по умолчанию, не хранится)."""
user = _get_user(request)
from claude_bridge_glm import effective_as_of
d, pinned = effective_as_of(user, tab_id)
return {"date": d, "pinned": pinned}
@app.post("/api/sessions/{tab_id}/date")
async def set_session_date_ep(tab_id: str, request: Request):
"""Зафиксировать дату сметы диалога (body {date:'ГГГГ-ММ-ДД'}) или вернуть «сегодня» (date null).
Нормативы этого диалога считаются на эту дату. Будущее/кривой формат → 400."""
import datetime
from claude_bridge_glm import _today_msk
from db import clear_session_date, save_message, set_session_date
user = _get_user(request)
ip = request.client.host if request.client else None
try:
body = await request.json()
assert isinstance(body, dict)
except Exception: # noqa: BLE001
raise HTTPException(400, "Некорректный запрос")
date = body.get("date")
if not date: # null/пусто → вернуть к «сегодня»
clear_session_date(user, tab_id)
log_action(user, "set_date", "POST", f"/api/sessions/{tab_id}/date", "clear", ip, 200)
return {"ok": True, "date": _today_msk(), "pinned": False}
if not isinstance(date, str) or len(date) != 10:
raise HTTPException(400, "Дата должна быть в формате ГГГГ-ММ-ДД")
try:
d = datetime.date.fromisoformat(date)
except ValueError:
raise HTTPException(400, "Дата должна быть в формате ГГГГ-ММ-ДД")
if d > datetime.date.fromisoformat(_today_msk()):
raise HTTPException(400, "Дата сметы не может быть в будущем — нормативов будущего не существует")
if date < "2000-01-01":
raise HTTPException(400, "Слишком ранняя дата")
set_session_date(user, tab_id, date)
log_action(user, "set_date", "POST", f"/api/sessions/{tab_id}/date", date, ip, 200)
try: # след в истории диалога (оба движка увидят в prior)
save_message(user, tab_id, "system", f"Дата сметы диалога установлена: {date}. "
f"Нормативы считаются по состоянию на эту дату.")
except Exception: # noqa: BLE001
pass
return {"ok": True, "date": date, "pinned": True}
@app.post("/api/upload")
async def upload(request: Request, file: UploadFile):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
work_dir = get_work_dir(user, tab_id)
safe_name = Path(file.filename).name
if not safe_name or safe_name.startswith("."):
raise HTTPException(400, "Invalid filename")
if not is_allowed_file(safe_name):
try:
from claude_bridge_glm import ALLOWED_EXTENSIONS as _ALLOWED
except Exception:
from claude_bridge import ALLOWED_EXTENSIONS as _ALLOWED
allowed = ", ".join(sorted(e.lstrip(".") for e in _ALLOWED))
raise HTTPException(400, f"Формат не поддерживается. Разрешены: {allowed}")
chunks = []
total = 0
while True:
chunk = await file.read(1024 * 1024)
if not chunk:
break
total += len(chunk)
if total > MAX_UPLOAD_SIZE:
raise HTTPException(413, f"File too large (max {MAX_UPLOAD_SIZE // 1024 // 1024}MB)")
chunks.append(chunk)
dest = work_dir / safe_name
dest.write_bytes(b"".join(chunks))
save_message(user, tab_id, "system", f"Загружен файл: {safe_name} ({total} байт)")
# Архивы/тома многотомников распаковываем на хосте (unar), чтобы агент увидел
# обычные файлы, а не непонятный архив (инциденты 2026-07-15, 2026-07-16).
extract_archive_async(dest, work_dir, user, tab_id)
ip = request.client.host if request.client else None
log_action(user, "upload", "POST", "/api/upload", f"{safe_name} ({total}B) tab={tab_id}", ip, 200)
return {"filename": safe_name, "size": total}
def _admin_tab_owner(request: Request, user: str, tab_id: str) -> str | None:
"""Владелец вкладки, если её смотрит админ (зеркало фолбэка /api/history).
Не-админам и для собственных вкладок возвращает None."""
from auth import get_token_role
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
if get_token_role(token) != "admin":
return None
from db import get_tab_owner
owner = get_tab_owner(tab_id)
if not owner or owner == user:
return None
return owner
@app.get("/api/files")
async def files(request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
result = list_user_files(user, tab_id)
if not result:
owner = _admin_tab_owner(request, user, tab_id)
if owner:
result = list_user_files(owner, tab_id)
return result
@app.get("/api/files/{filename}")
async def download_file(filename: str, request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
safe_name = Path(filename).name
fpath = get_work_dir(user, tab_id) / safe_name
if not fpath.exists() or not fpath.is_file():
owner = _admin_tab_owner(request, user, tab_id)
if owner:
fpath = get_work_dir(owner, tab_id) / safe_name
if not fpath.exists() or not fpath.is_file():
raise HTTPException(404, "File not found")
return FileResponse(fpath, filename=filename)
@app.post("/api/extract_complaints")
async def extract_complaints_endpoint(request: Request):
"""Detrministic regex extraction of (пункт → смета) pairs from xlsm.
Body: {"tab_id": "...", "filename": "..."} — file must already be uploaded.
Returns: stats + pairs + no_code_rows.
"""
from complaints import extract_pairs
user = _get_user(request)
body = await request.json()
tab_id = body.get("tab_id") or request.headers.get("x-tab-id", "default")
filename = body.get("filename")
if not filename:
raise HTTPException(400, "filename required")
safe_name = Path(filename).name
fpath = get_work_dir(user, tab_id) / safe_name
if not fpath.exists():
raise HTTPException(404, "File not found in work directory")
try:
result = extract_pairs(fpath)
except ValueError as e:
raise HTTPException(400, str(e))
ip = request.client.host if request.client else None
log_action(user, "extract_complaints", "POST", "/api/extract_complaints",
f"{safe_name} pairs={result['stats']['total_pairs']}", ip, 200)
return result
@app.post("/api/apply_matches")
async def apply_matches_endpoint(request: Request):
"""Fill column D in sheet «РеестрСМ» with matching пункт-замечания.
Body: {"tab_id": "...", "filename": "..."} — original xlsm with both sheets.
Saves <stem>_filled.xlsm into the same work directory and returns
download URL + stats.
"""
from complaints import apply_to_registry
user = _get_user(request)
body = await request.json()
tab_id = body.get("tab_id") or request.headers.get("x-tab-id", "default")
filename = body.get("filename")
if not filename:
raise HTTPException(400, "filename required")
safe_name = Path(filename).name
work_dir = get_work_dir(user, tab_id)
fpath = work_dir / safe_name
if not fpath.exists():
raise HTTPException(404, "File not found in work directory")
# openpyxl drops VBA macros when saving — write as .xlsx so Excel
# opens it cleanly even when the source was .xlsm
out_name = f"{Path(safe_name).stem}_filled.xlsx"
out_path = work_dir / out_name
try:
result = apply_to_registry(fpath, out_path)
except ValueError as e:
raise HTTPException(400, str(e))
ip = request.client.host if request.client else None
log_action(user, "apply_matches", "POST", "/api/apply_matches",
f"{safe_name} filled={result['cells_filled']}", ip, 200)
return {
**result,
"output_filename": out_name,
"download_url": f"/api/files/{out_name}",
}
@app.post("/api/reset")
async def reset_session(request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
clear_session(user, tab_id)
clear_history(user, tab_id)
return {"status": "ok"}
@app.post("/api/clear-files")
async def clear_files(request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
work_dir = get_work_dir(user, tab_id)
for f in work_dir.iterdir():
if f.name.startswith("."):
continue
if f.is_file():
f.unlink()
elif f.is_dir():
shutil.rmtree(f)
clear_session(user, tab_id)
clear_history(user, tab_id)
return {"status": "ok"}
# === 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
# === 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["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."""
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
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."""
_get_user(request)
job = batch_v3.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")
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):
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
# 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):
_get_user(request)
job = batch_v3.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)
# === Admin: view user sessions ===
@app.get("/api/admin/sessions")
async def admin_sessions(request: Request):
"""List all sessions with last activity — for admin use."""
_require_admin(request)
from db import _conn
with _conn() as conn:
rows = conn.execute(
"SELECT username, tab_id, MAX(timestamp) as last_ts, COUNT(*) as msg_count, "
"(SELECT content FROM messages m2 WHERE m2.tab_id = messages.tab_id "
" AND m2.username = messages.username "
" AND m2.role = 'user' ORDER BY m2.id DESC LIMIT 1) as last_question "
"FROM messages GROUP BY username, tab_id ORDER BY last_ts DESC LIMIT 50",
).fetchall()
return [dict(r) for r in rows]
@app.get("/api/admin/audit")
async def admin_audit(request: Request):
"""Full audit log — admin only."""
_require_admin(request)
limit = int(request.query_params.get("limit", "200"))
offset = int(request.query_params.get("offset", "0"))
username = request.query_params.get("username") or None
action = request.query_params.get("action") or None
return get_audit_log(limit, offset, username, action)
@app.get("/api/admin/feedback")
async def admin_feedback(request: Request):
"""Жалобы пользователей на ответы («сообщить об ошибке») — admin only."""
_require_admin(request)
limit = int(request.query_params.get("limit", "200"))
return get_feedback(limit)
@app.get("/api/admin/stats")
async def admin_stats(request: Request):
"""Dashboard stats: messages per day, total sessions, etc."""
_require_admin(request)
from db import _conn
with _conn() as conn:
# Messages per day (last 14 days)
import time as _time
cutoff = _time.time() - 14 * 86400
daily = conn.execute(
"SELECT date(timestamp, 'unixepoch', '+10 hours') as day, "
"COUNT(*) as total, "
"SUM(CASE WHEN role='user' THEN 1 ELSE 0 END) as questions, "
"SUM(CASE WHEN role='assistant' THEN 1 ELSE 0 END) as answers "
"FROM messages WHERE timestamp > ? "
"GROUP BY day ORDER BY day DESC",
(cutoff,),
).fetchall()
# Totals
totals = conn.execute(
"SELECT COUNT(*) as messages, COUNT(DISTINCT tab_id) as sessions, "
"COUNT(DISTINCT username) as users "
"FROM messages",
).fetchone()
return {"daily": [dict(r) for r in daily], "totals": dict(totals)}
@app.get("/api/admin/normative-status")
async def admin_normative_status(request: Request):
"""Состояние нормативной базы из внешних источников: что загружено, когда, период базы,
полнота N/86, свежесть, что применено к движку, здоровье конвейера. Admin only."""
_require_admin(request)
import ext_status
return await asyncio.to_thread(ext_status.normative_status)
@app.post("/api/admin/normative-recheck")
async def admin_normative_recheck(request: Request):
"""Запустить проверку внешних источников сейчас (read-only, в фоне). Панель обновит статус
по heartbeat. _solo_run в чекере не даёт наложиться на cron-прогон. Admin only."""
_require_admin(request)
import subprocess
import sys
# EXT_REGIONS по умолчанию 'all' — чтобы ручная проверка была ПОЛНОЙ даже там, где переменная
# не задана в .env; пишет в тот же ext_dir, что и cron (shared .check.lock не даст наложиться).
env = {**os.environ, "EXT_REGIONS": os.environ.get("EXT_REGIONS") or "all"}
try:
subprocess.Popen(
[sys.executable, "ext_check.py", "--no-notify"],
cwd=str(Path(__file__).resolve().parent), start_new_session=True, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception as e: # noqa: BLE001
raise HTTPException(500, f"не удалось запустить проверку: {e}")
return {"started": True}
@app.get("/api/admin/models-status")
async def admin_models_status(request: Request):
"""Реестр ИИ-моделей по ролям: провайдер, модель, дата пина, кандидат, последний eval.
Точка «не застрять на старой версии» — Юрий видит, что где стои́т. Admin only."""
_require_admin(request)
import model_registry
return model_registry.status_summary()
@app.post("/api/admin/invite")
async def create_invite_endpoint(request: Request):
"""Create invite link. Admin only."""
_require_admin(request)
user = _get_user(request)
import secrets
from db import create_invite
invite_token = secrets.token_urlsafe(24)
create_invite(invite_token, user)
return {"invite_token": invite_token, "url": f"https://infosmeta.ru/register?invite={invite_token}"}
@app.get("/api/admin/invites")
async def list_invites_endpoint(request: Request):
_require_admin(request)
from db import list_invites
return list_invites()
@app.get("/api/admin/users")
async def list_users_endpoint(request: Request):
_require_admin(request)
from db import list_users
return list_users()
def _require_admin(request: Request):
"""Check that current user is admin."""
_get_user(request)
from auth import get_token_role
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
if get_token_role(token) != "admin":
raise HTTPException(403, "Admin only")
@app.post("/api/admin/users/block")
async def block_user_endpoint(request: Request):
_require_admin(request)
body = await request.json()
email = body.get("email", "")
blocked = body.get("blocked", True)
from db import block_user
block_user(email, blocked)
return {"ok": True}
@app.post("/api/admin/users/delete")
async def delete_user_endpoint(request: Request):
_require_admin(request)
body = await request.json()
email = body.get("email", "")
current_user = _get_user(request)
if email.lower() == current_user.lower():
raise HTTPException(400, "Нельзя удалить себя")
from db import delete_user
delete_user(email)
return {"ok": True}
@app.post("/api/admin/users/role")
async def set_role_endpoint(request: Request):
_require_admin(request)
body = await request.json()
email = body.get("email", "")
role = body.get("role", "user")
from db import set_user_role
set_user_role(email, role)
return {"ok": True}
@app.post("/api/admin/users/verify")
async def admin_verify_endpoint(request: Request):
_require_admin(request)
body = await request.json()
email = body.get("email", "")
from db import admin_verify_user
admin_verify_user(email)
return {"ok": True}
@app.get("/api/admin/file_users")
async def admin_file_users_endpoint(request: Request):
"""Юзеры, у которых есть файлы в DATA_DIR.
Источник — FS, не таблица users: бывают env-only аккаунты (`smeta`)
и удалённые из БД пользователи, чьи файлы остались. Админу нужно
видеть всех с реальными файлами.
"""
_require_admin(request)
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
if not data_dir.exists():
return {"users": []}
out = []
for d in sorted(data_dir.iterdir()):
if not d.is_dir() or d.name.startswith(".") or d.name.startswith("_"):
continue
n = 0
for tab in d.iterdir():
if tab.is_dir() and not tab.name.startswith("."):
for f in tab.iterdir():
if f.is_file() and not f.name.startswith("."):
n += 1
out.append({"username": d.name, "file_count": n})
out.sort(key=lambda x: -x["file_count"])
return {"users": out}
@app.get("/api/admin/files")
async def admin_list_files_endpoint(request: Request):
"""All files uploaded by a specific user (across every tab).
Спец-значение `username=__all__` — файлы всех юзеров. Каждая
запись содержит поле `username` (для одиночного режима тоже —
UI единообразно).
"""
_require_admin(request)
target_user = request.query_params.get("username", "").strip()
if not target_user:
raise HTTPException(400, "username query param required")
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
files = []
def _collect(user_dir: Path, username: str):
if not user_dir.exists() or not user_dir.is_dir():
return
for tab_dir in sorted(user_dir.iterdir()):
if not tab_dir.is_dir() or tab_dir.name.startswith("."):
continue
for f in sorted(tab_dir.iterdir()):
if f.is_file() and not f.name.startswith("."):
st = f.stat()
files.append({
"username": username,
"tab_id": tab_dir.name,
"filename": f.name,
"size": st.st_size,
"mtime": st.st_mtime,
})
if target_user == "__all__":
if data_dir.exists():
for d in sorted(data_dir.iterdir()):
if not d.is_dir() or d.name.startswith(".") or d.name.startswith("_"):
continue
_collect(d, d.name)
return {"username": "__all__", "count": len(files), "files": files}
safe_user = Path(target_user).name
if safe_user != target_user or not safe_user:
raise HTTPException(400, "Invalid username")
_collect(data_dir / safe_user, safe_user)
return {"username": safe_user, "count": len(files), "files": files}
@app.post("/api/admin/download_ticket")
async def admin_download_ticket_endpoint(request: Request):
"""Issue a short-lived signed ticket so the admin UI can trigger a native
browser download (streams to disk, any size) without putting the JWT in a URL."""
_require_admin(request)
body = await request.json()
username = (body.get("username") or "").strip()
tab_id = (body.get("tab_id") or "").strip()
filename = (body.get("filename") or "").strip()
if not (username and tab_id and filename):
raise HTTPException(400, "username, tab_id, filename required")
exp, sig = make_download_ticket(username, tab_id, filename)
return {"exp": exp, "sig": sig}
@app.get("/api/admin/file_download")
async def admin_download_file_endpoint(request: Request):
"""Download any user's uploaded file (admin only).
Path components passed as query params to avoid URL-escaping pain
with names like `!Реестр СМ..xlsm` and tab_ids containing slashes.
"""
target_user = request.query_params.get("username", "").strip()
tab_id = request.query_params.get("tab_id", "").strip()
filename = request.query_params.get("filename", "").strip()
if not (target_user and tab_id and filename):
raise HTTPException(400, "username, tab_id, filename required")
# Auth via short-lived signed ticket (issued by /api/admin/download_ticket to
# an authenticated admin) so the admin JWT never lands in a URL or access log.
if not verify_download_ticket(target_user, tab_id, filename,
request.query_params.get("exp", ""),
request.query_params.get("sig", "")):
raise HTTPException(403, "Invalid or expired download ticket")
safe_user = Path(target_user).name
safe_tab = Path(tab_id).name
safe_name = Path(filename).name
if not (safe_user and safe_tab and safe_name):
raise HTTPException(400, "Invalid path component")
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")).resolve()
fpath = (data_dir / safe_user / safe_tab / safe_name).resolve()
try:
fpath.relative_to(data_dir)
except ValueError:
raise HTTPException(400, "Path traversal denied")
if not fpath.exists() or not fpath.is_file():
raise HTTPException(404, "File not found")
return FileResponse(fpath, filename=safe_name, headers={"Referrer-Policy": "no-referrer"})
ADMIN_HTML_VERSION = "20260602b"
@app.get("/admin", response_class=HTMLResponse)
async def admin_page(request: Request):
# Если у юзера в браузере осталась старая закэшированная копия
# /admin без no-store, то любые серверные заголовки уже не
# помогут — браузер сам решает, делать ли revalidation. Поэтому:
# - на запрос без актуальной ?v= делаем 302 на URL с query
# - URL с query !== закэшированный URL без query → промах кэша →
# браузер делает свежий запрос, получает no-store, дальше всегда
# свежий
from fastapi.responses import RedirectResponse
if request.query_params.get("v") != ADMIN_HTML_VERSION:
return RedirectResponse(url=f"/admin?v={ADMIN_HTML_VERSION}", status_code=302)
html = Path("static/admin.html").read_text(encoding="utf-8")
return HTMLResponse(
html,
headers={
"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
"Pragma": "no-cache",
"Expires": "0",
},
)
# === 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["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."""
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
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):
_get_user(request)
job = batch_v3.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")
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):
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
# 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):
_get_user(request)
job = batch_v3.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)
# ── 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")
def _import_ssr_scripts():
"""Import smeta-railway scripts (installed via pip install -e)."""
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)
@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):
_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")
# ── 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."""
# ⛔ Путь 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}
@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")))