Spaces:
Paused
Paused
Download api/v1/dashboard.py from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/dashboard.py
- Command line
-
hf download hf://spaces/3SCError404/miracle/api/v1/dashboard.py
-
curl -L -o dashboard.py https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/dashboard.py
16.5 kB
| """ | |
| Dashboard endpoints for summary stats and activity. | |
| # v2.1 SYNC | |
| """ | |
| import asyncio | |
| from datetime import datetime, timedelta | |
| from typing import Any, List, Optional, Union, Dict | |
| from fastapi import APIRouter, Depends, Request | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select, func, Float, desc | |
| from sqlalchemy.orm import joinedload | |
| from core.deps import get_db, get_current_user, get_arq_pool | |
| from core.llm import get_llm | |
| from langchain_core.prompts import ChatPromptTemplate | |
| from models.user import User, UserRole | |
| from models.user_workspace import UserWorkspace | |
| from models.ticket import Ticket, TicketStatus, TicketPriority | |
| from schemas.ticket import TicketResponse, TicketInternalResponse | |
| from core.logging import get_logger | |
| router = APIRouter() | |
| logger = get_logger(__name__) | |
| from core.permissions import get_effective_context | |
| async def get_dashboard_hydration( | |
| request: Request, | |
| workspace_id: str = None, | |
| refresh: bool = False, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db), | |
| arq_pool = Depends(get_arq_pool) | |
| ) -> Any: | |
| """ | |
| ULTRA-HYDRATION: Unified endpoint for instant dashboard population. | |
| Consolidates Stats, Reports Summary, and Agent Queue in one trip. | |
| """ | |
| # 1. PRE-RESOLUTION: Resolve context once to avoid redundant DB hits in parallel tasks | |
| target_ws, effective_role = await get_effective_context(db, current_user, workspace_id) | |
| ws_id_str = str(target_ws) | |
| is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN] or current_user.is_platform_admin | |
| from core.database import async_session_factory | |
| # Helper to run dashboard components in isolated sessions for safe concurrency | |
| async def run_isolated(coro_fn, *args, **kwargs): | |
| async with async_session_factory() as session: | |
| return await coro_fn(*args, **kwargs, db=session) | |
| from services.ticket_service import TicketService | |
| # 2. UNIFIED TELEMETRY FETCH: Single scan for counts, trends, and performance | |
| async def _telemetry_task(db: AsyncSession): | |
| return await TicketService.get_workspace_telemetry(db, current_user, target_ws) | |
| async def _reports_task(db: AsyncSession, telemetry_data): | |
| from api.v1.reports import get_reports_summary | |
| return await get_reports_summary(ws_id_str, current_user, db, precomputed_telemetry=telemetry_data) | |
| async def _queue_task(db: AsyncSession): | |
| if not is_staff: return [] | |
| return await get_agent_queue(request, ws_id_str, limit=50, refresh=refresh, current_user=current_user, db=db) | |
| async def _escalations_task(db: AsyncSession): | |
| from api.v1.escalations import list_escalation_rules, list_active_breaches, view_escalation_audit | |
| from schemas.escalation import EscalationRuleResponse, AuditLogResponse | |
| rules = await list_escalation_rules(ws_id_str, current_user, db) | |
| breaches = await list_active_breaches(ws_id_str, current_user, db) | |
| audit = await view_escalation_audit(ws_id_str, 0, 5, current_user, db) | |
| return { | |
| "rules": [EscalationRuleResponse.model_validate(r).model_dump() for r in rules], | |
| "breaches": breaches, | |
| "audit": [AuditLogResponse.model_validate(a).model_dump() for a in audit] | |
| } | |
| # Parallel Execution of core data | |
| try: | |
| # We run telemetry, queue, and escalations in parallel. | |
| core_results = await asyncio.wait_for(asyncio.gather( | |
| run_isolated(_telemetry_task), | |
| run_isolated(_queue_task), | |
| run_isolated(_escalations_task), | |
| return_exceptions=True | |
| ), timeout=15.0) | |
| telemetry, queue, escalations = core_results | |
| # Handle failures | |
| telemetry = telemetry if not isinstance(telemetry, Exception) else None | |
| queue = queue if not isinstance(queue, Exception) else [] | |
| escalations = escalations if not isinstance(escalations, Exception) else {"rules": [], "breaches": [], "audit": []} | |
| # 3. SECONDARY LAYER: Reports & Insights (Dependent on Telemetry if we want to optimize, or run in parallel) | |
| # We run it now to ensure we have the most complete dashboard state in one trip. | |
| reports_data = await run_isolated(_reports_task, telemetry_data=telemetry) | |
| # Build initial response structure | |
| res_data = { | |
| "stats": telemetry if telemetry else {"by_status": {}, "performance": {}, "workspace_id": ws_id_str}, | |
| "reports": reports_data if reports_data else {"daily": [], "volume": {}}, | |
| "queue": queue, | |
| "escalations": escalations, | |
| "insights": reports_data.get("insights") if reports_data else None | |
| } | |
| return res_data | |
| except Exception as e: | |
| import traceback | |
| logger.error(f"Dashboard Hydration CRITICAL FAILURE: {e}\n{traceback.format_exc()}") | |
| return { | |
| "stats": {"by_status": {}, "performance": {}, "workspace_id": ws_id_str}, | |
| "reports": {"daily": [], "volume": {}, "csat": {}, "sla": {}}, | |
| "queue": [], | |
| "escalations": {"rules": [], "breaches": [], "audit": []}, | |
| "insights": None, | |
| "error": str(e) | |
| } | |
| async def get_dashboard_stats( | |
| request: Request = None, | |
| workspace_id: str = None, | |
| refresh: bool = False, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| from core.cache import get_cached_search, set_cached_search, delete_cached_search, SemanticCacheManager | |
| # 0. Role Class Normalization | |
| role_class = SemanticCacheManager._normalize_role_class(str(current_user.role)) | |
| portal = request.headers.get("X-Nexus-Portal", "unknown") if request else "system" | |
| # Cache lookup | |
| target_ws = workspace_id or str(current_user.workspace_id) | |
| cache_key = f"dashboard:stats:{portal}:{role_class}:{target_ws}:{current_user.id}" | |
| if refresh: | |
| await delete_cached_search(cache_key) | |
| else: | |
| cached_data = await get_cached_search(cache_key) | |
| if cached_data: | |
| return cached_data | |
| from datetime import datetime | |
| # Identify target workspace | |
| is_global = (workspace_id == "all" and current_user.is_platform_admin) | |
| if is_global: | |
| target_ws = "all" | |
| effective_role = UserRole.SC_ADMIN | |
| else: | |
| # Strictly enforce workspace isolation | |
| target_ws, effective_role = await get_effective_context(db, current_user, workspace_id) | |
| is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN] or current_user.is_platform_admin | |
| now = datetime.utcnow() | |
| since_30d = now - timedelta(days=30) | |
| # 1. Fetch Unified Telemetry from Service | |
| from services.ticket_service import TicketService | |
| stats_data = await TicketService.get_workspace_telemetry(db, current_user, target_ws) | |
| # 2. Personalized Open Count (User-specific) | |
| my_open_stmt = select(func.count(Ticket.id)).where( | |
| Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), | |
| Ticket.deleted_at.is_(None) | |
| ) | |
| if is_staff: | |
| my_open_stmt = my_open_stmt.where(Ticket.assigned_to == current_user.id) | |
| elif effective_role == UserRole.CUSTOMER_USER: | |
| my_open_stmt = my_open_stmt.where(Ticket.created_by == current_user.id) | |
| if not is_global: | |
| my_open_stmt = my_open_stmt.where(Ticket.workspace_id == target_ws) | |
| my_open_count = (await db.execute(my_open_stmt)).scalar() or 0 | |
| # 3. Personnel Load (Workspace Staff Capacity) | |
| from models.user_workspace import UserWorkspace | |
| staff_query = ( | |
| select(User) | |
| .join(UserWorkspace, User.id == UserWorkspace.user_id) | |
| .where( | |
| UserWorkspace.workspace_id == target_ws, | |
| UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), | |
| User.is_active == True, | |
| UserWorkspace.is_active == True, | |
| User.deleted_at.is_(None) | |
| ) | |
| ) | |
| if is_global: | |
| staff_query = select(User).where( | |
| User.global_role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), | |
| User.is_active == True, | |
| User.deleted_at.is_(None) | |
| ) | |
| staff_res = await db.execute(staff_query) | |
| workspace_staff = staff_res.scalars().all() | |
| staff_ids = [u.id for u in workspace_staff] | |
| personnel_load = [] | |
| if staff_ids: | |
| load_stmt = ( | |
| select(Ticket.assigned_to, func.count(Ticket.id)) | |
| .where( | |
| Ticket.assigned_to.in_(staff_ids), | |
| Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), | |
| Ticket.deleted_at.is_(None) | |
| ) | |
| ) | |
| if not is_global: | |
| load_stmt = load_stmt.where(Ticket.workspace_id == target_ws) | |
| load_stmt = load_stmt.group_by(Ticket.assigned_to) | |
| counts_res = await db.execute(load_stmt) | |
| load_map = {row[0]: row[1] for row in counts_res.all()} | |
| personnel_load = [ | |
| {"name": u.full_name, "count": load_map.get(u.id, 0)} | |
| for u in workspace_staff | |
| ] | |
| personnel_load.sort(key=lambda x: x["count"], reverse=True) | |
| response = { | |
| "total_tickets": stats_data.get("total_tickets", 0), | |
| "by_status": stats_data.get("by_status", {}), | |
| "by_priority": stats_data.get("by_priority", {}), | |
| "by_category": stats_data.get("by_category", {}), | |
| "workspace_id": str(target_ws), | |
| "my_open_count": my_open_count, | |
| "performance": stats_data.get("performance", {}) | |
| } | |
| if is_staff: | |
| response.update({ | |
| "personnel_load": personnel_load | |
| }) | |
| await set_cached_search(cache_key, response, ttl=60) | |
| return response | |
| async def get_my_tickets( | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Get tickets identified with the current user (Created or Assigned). Sanitized for Customers.""" | |
| from api.v1.tickets import sanitize_ticket_response | |
| stmt = ( | |
| select(Ticket) | |
| .options( | |
| joinedload(Ticket.creator), | |
| joinedload(Ticket.assignee), | |
| joinedload(Ticket.resolver), | |
| joinedload(Ticket.feedback) | |
| ) | |
| .where( | |
| ((Ticket.created_by == current_user.id) | (Ticket.assigned_to == current_user.id)), | |
| Ticket.workspace_id == current_user.workspace_id, | |
| Ticket.deleted_at.is_(None) | |
| ) | |
| .order_by(Ticket.updated_at.desc()) | |
| ) | |
| result = await db.execute(stmt) | |
| tickets = result.scalars().all() | |
| return await asyncio.gather(*[sanitize_ticket_response(t, current_user, db) for t in tickets]) | |
| async def get_agent_queue( | |
| request: Request, | |
| workspace_id: str = None, | |
| status_filter: Optional[TicketStatus] = None, | |
| priority_filter: Optional[TicketPriority] = None, | |
| search_query: Optional[str] = None, | |
| creator_query: Optional[str] = None, | |
| ticket_id_filter: Optional[str] = None, | |
| sort_by: str = "created_at", | |
| limit: int = 500, | |
| refresh: bool = False, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Get the active ticket queue with tactical search and filtering.""" | |
| from core.cache import get_cached_search, set_cached_search, delete_cached_search, SemanticCacheManager | |
| from services.ticket_service import TicketService | |
| is_staff = ( | |
| current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN] or | |
| current_user.is_platform_admin | |
| ) | |
| if not is_staff: | |
| from fastapi import HTTPException | |
| raise HTTPException(status_code=403, detail="Operational Access: Staff privilege required") | |
| role_class = SemanticCacheManager._normalize_role_class(str(current_user.role)) | |
| portal = request.headers.get("X-Nexus-Portal", "unknown") if request else "system" | |
| target_ws, effective_role = await get_effective_context(db, current_user, workspace_id) | |
| cache_params = f"{status_filter}:{priority_filter}:{search_query}:{creator_query}:{ticket_id_filter}:{sort_by}" | |
| cache_key = f"dashboard:queue:{portal}:{role_class}:{target_ws}:{current_user.id}:{cache_params}" | |
| if refresh: | |
| await delete_cached_search(cache_key) | |
| else: | |
| cached_data = await get_cached_search(cache_key) | |
| if cached_data: | |
| return cached_data | |
| res = await TicketService.list_tickets_paginated( | |
| db=db, | |
| current_user=current_user, | |
| workspace_id=target_ws, | |
| skip=0, | |
| limit=limit, | |
| status_filter=status_filter, | |
| priority_filter=priority_filter, | |
| search_query=search_query, | |
| creator_query=creator_query, | |
| ticket_id_filter=ticket_id_filter, | |
| sort_by=sort_by | |
| ) | |
| res_data = res["items"] | |
| await set_cached_search(cache_key, res_data, ttl=60) | |
| return res_data | |
| async def get_ai_insights( | |
| request: Request, | |
| workspace_id: str = None, | |
| refresh: bool = False, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db), | |
| precomputed_stats: Optional[Dict] = None, | |
| arq_pool = Depends(get_arq_pool) | |
| ) -> Any: | |
| from core.cache import get_cached_search, set_cached_search, delete_cached_search | |
| target_ws, effective_role = await get_effective_context(db, current_user, workspace_id) | |
| # Determine view mode | |
| INTERNAL_ROLES = {UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN} | |
| is_internal = effective_role in INTERNAL_ROLES | |
| view_mode = "internal" if is_internal else "customer" | |
| cache_key = f"dashboard:insights:{target_ws}:{view_mode}:{current_user.id}" | |
| # --- DEDUPLICATION & STALE-WHILE-REVALIDATE --- | |
| # Check if a background job is already in progress for this workspace and role | |
| throttle_key = f"job_throttle:generate_workspace_insights:{target_ws}:{view_mode}" | |
| job_in_progress = await get_cached_search(throttle_key) is not None | |
| if not refresh: | |
| cached_data = await get_cached_search(cache_key) | |
| if cached_data: | |
| return cached_data | |
| # Even if refreshing, try to serve stale system data as a buffer | |
| system_cache_key = f"dashboard:insights:{target_ws}:{view_mode}" | |
| system_data = await get_cached_search(system_cache_key) | |
| if system_data: | |
| # If refreshing and no job is running, trigger it but still return the stale data as buffer | |
| if not job_in_progress: | |
| from core.tasks import enqueue_task | |
| try: | |
| await enqueue_task(arq_pool, "generate_workspace_insights", str(target_ws), role=view_mode) | |
| except: pass | |
| return system_data | |
| # --- FALLBACK: NO DATA AT ALL --- | |
| if not job_in_progress: | |
| from core.tasks import enqueue_task | |
| try: | |
| await enqueue_task(arq_pool, "generate_workspace_insights", str(target_ws), role=view_mode) | |
| except Exception as e: | |
| logger.warning(f"Failed to enqueue background insights: {e}") | |
| return { | |
| "summary": "Nexus Intelligence is synthesizing your workspace telemetry. Trends will appear momentarily.", | |
| "actions": ["Review active ticket distribution", "Verify personnel load balancing", "Monitor SLA breach risks"], | |
| "metric_insights": {"intensity": "STABLE", "velocity": "NORMAL", "thermal": "OPTIMIZING"}, | |
| "type": "ASYNC_PENDING" | |
| } | |
| async def refresh_global_insights( | |
| current_user: User = Depends(get_current_user), | |
| arq_pool = Depends(get_arq_pool) | |
| ) -> Any: | |
| if current_user.role != UserRole.SC_ADMIN: | |
| from fastapi import HTTPException | |
| raise HTTPException(status_code=403, detail="Super-Admin Privilege Required") | |
| from core.tasks import enqueue_task | |
| await enqueue_task(arq_pool, "generate_global_insight", _job_id="global_insight_refresh") | |
| return {"status": "SUCCESS"} | |