"""API v2: пока каркас и dashboard. Настоящие разделы — P2.4+.""" from __future__ import annotations import asyncio import time from fastapi import APIRouter, HTTPException, Request import admin_actions import attention import customers import db import metrics import money from admin_auth import require_admin router = APIRouter(prefix="/api/admin/v2", tags=["admin-v2"]) # Один снимок на 15 секунд: «Мой день» не должен пересчитывать метрики на каждый F5. _CACHE: dict = {"ts": 0.0, "data": None} _CACHE_TTL = 15 def _build(user: str) -> dict: work = metrics.collect(1)["work"] cash = money.summary() return {"generated_at": time.time(), "work_24h": {"people": work["people"], "requests": work["requests"], "failures": work["failures"], "failure_share": work["failure_share"], "limit_hits": work["limit_hits"], "latency_qa_ms": work["latency"]["qa"]["median_ms"], "latency_qa_p95_ms": work["latency"]["qa"]["p95_ms"], "latency_agent_ms": work["latency"]["agent"]["median_ms"], "latency_agent_p95_ms": work["latency"]["agent"]["p95_ms"]}, "money": cash, "customers": {"total": db.count_living_users(), "active_24h": work["people"]}, "attention": {"failures": work["failures"], "limit_hits": work["limit_hits"], "unpriced": cash.get("unpriced")}} @router.get("/ping") async def ping(request: Request): user = require_admin(request) return {"ok": True, "v2": True, "user": user} @router.post("/visit") async def visit(request: Request): user = require_admin(request) result = await asyncio.to_thread(db.record_admin_visit, user) # Кэш общий и personal-поля в него не входят: визит не должен его сбрасывать. return {"ok": True, **result} def _attention_snapshot() -> dict: work = metrics.collect(1)["work"] cash = money.summary() return attention.collect(work, cash) @router.get("/attention") async def attention_queue(request: Request): require_admin(request) return await asyncio.to_thread(_attention_snapshot) @router.post("/attention/{key}/done") async def attention_done(key: str, request: Request): require_admin(request) snap = await asyncio.to_thread(_attention_snapshot) keys = {i["key"] for i in snap["items"]} if key not in keys and not attention.state_of(key): raise HTTPException(404, "Такого сигнала нет") ok = await asyncio.to_thread(attention.mark_done, key) return {"ok": ok, "key": key} @router.post("/attention/{key}/snooze") async def attention_snooze(key: str, request: Request): require_admin(request) try: body = await request.json() if not isinstance(body, dict): raise ValueError minutes = int(body.get("minutes") or 0) except (ValueError, TypeError): raise HTTPException(400, "minutes 1..10080") from None snap = await asyncio.to_thread(_attention_snapshot) keys = {i["key"] for i in snap["items"]} if key not in keys and not attention.state_of(key): raise HTTPException(404, "Такого сигнала нет") ok = await asyncio.to_thread(attention.snooze, key, minutes) if not ok: raise HTTPException(400, "minutes 1..10080") return {"ok": True, "key": key, "minutes": minutes} @router.get("/customers") async def customers_list(request: Request, query: str = "", q: str = "", status: str = "", page: int = 1, per_page: int = 50, sort: str = "last_seen"): require_admin(request) try: return await asyncio.to_thread(customers.list_customers, query or q, status, page, per_page, sort) except ValueError as e: raise HTTPException(400, str(e)) from e except LookupError as e: raise HTTPException(503, str(e)) from e @router.get("/customers/{email}") async def customer_card(email: str, request: Request): require_admin(request) data = await asyncio.to_thread(customers.card, email) if data is None: raise HTTPException(404, "Клиент не найден") return data @router.get("/customers/{email}/dialogs") async def customer_dialogs(email: str, request: Request): require_admin(request) data = await asyncio.to_thread(customers.dialogs, email) if data is None: raise HTTPException(404, "Клиент не найден") return {"items": data} @router.get("/customers/{email}/ledger") async def customer_ledger(email: str, request: Request): require_admin(request) data = await asyncio.to_thread(customers.ledger, email) if data is None: raise HTTPException(404, "Клиент не найден") return data @router.get("/customers/{email}/files") async def customer_files(email: str, request: Request): require_admin(request) data = await asyncio.to_thread(customers.files, email) if data is None: raise HTTPException(404, "Клиент не найден") return {"items": data} @router.get("/customers/{email}/history") async def customer_history(email: str, request: Request): require_admin(request) data = await asyncio.to_thread(customers.history, email) if data is None: raise HTTPException(404, "Клиент не найден") return {"items": data} @router.post("/customers/{email}/action") async def customer_action(email: str, request: Request): user = require_admin(request) try: body = await request.json() except Exception: raise HTTPException(400, "тело — JSON-объект") from None action = body.get("action") if isinstance(body, dict) else None value = body.get("value") if isinstance(body, dict) else None if not isinstance(value, dict): raise HTTPException(400, "value должен быть объектом") try: return await asyncio.to_thread(admin_actions.perform, user, email, action, value) except ValueError as e: raise HTTPException(400, str(e)) from e except LookupError as e: raise HTTPException(404, str(e)) from e @router.post("/actions/{action_id}/undo") async def undo_action(action_id: int, request: Request): user = require_admin(request) try: return await asyncio.to_thread(admin_actions.undo, user, action_id) except LookupError as e: raise HTTPException(404, str(e)) from e except ValueError as e: raise HTTPException(400, str(e)) from e @router.get("/dashboard") async def dashboard(request: Request): user = require_admin(request) now = time.time() if _CACHE["data"] is not None and now - _CACHE["ts"] < _CACHE_TTL: common = _CACHE["data"] else: common = await asyncio.to_thread(_build, user) _CACHE["ts"] = now _CACHE["data"] = common # user/last_visit — персональные, кэш общий: дописываем их на каждый запрос. return {**common, "user": user, "last_visit": db.get_admin_visit(user)}