Spaces:
Paused

nexus / api /v1 /dashboard.py
dushyantsingh0
backend stabilization
db51981
Raw History Blame Contribute Delete
16.1 kB
"""
Dashboard endpoints for summary stats and activity.
# v2.1 SYNC
"""
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, or_, 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.ticket import Ticket, TicketStatus
from schemas.ticket import TicketResponse, TicketInternalResponse
from typing import Any, Dict, List, Optional, Union
from core.logging import get_logger
router = APIRouter()
logger = get_logger(__name__)
@router.get("/stats/")
async def get_dashboard_stats(
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
# Cache lookup
target_ws = workspace_id or str(current_user.workspace_id)
cache_key = f"dashboard:stats:{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
is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
# Identify target workspace
target_ws = current_user.workspace_id
is_super_admin = (current_user.role == UserRole.SC_ADMIN)
is_global = False
if workspace_id:
if is_super_admin and workspace_id == "all":
is_global = True
else:
# Multi-workspace Agent/Lead Check: Ensure they are authorized for the requested workspace
if is_super_admin:
target_ws = workspace_id
else:
from models.user_workspace import UserWorkspace
ws_check = await db.execute(
select(UserWorkspace).where(
UserWorkspace.user_id == current_user.id,
UserWorkspace.workspace_id == workspace_id
)
)
if ws_check.scalar_one_or_none():
target_ws = workspace_id
else:
# Silently fallback to primary if not authorized, or raise 403
pass
now = datetime.utcnow()
# 1. Basic Status Counts (Optimized SQL)
stmt = (
select(Ticket.status, func.count(Ticket.id))
.where(Ticket.deleted_at.is_(None))
)
if not is_global:
stmt = stmt.where(Ticket.workspace_id == target_ws)
if current_user.role == UserRole.CUSTOMER_USER:
# Regular customers see ONLY their own tickets' statuses
stmt = stmt.where(Ticket.created_by == current_user.id)
stmt = stmt.group_by(Ticket.status)
counts_res = await db.execute(stmt)
counts = {row[0]: row[1] for row in counts_res.all()}
for s in TicketStatus:
if s not in counts: counts[s] = 0
total = sum(counts.values())
from models.feedback import Feedback
# 2. Advanced Metrics (High-Performance SQL Aggregations)
# Resolution Time: AVG(resolved - created)
# CSAT: Join with Feedback table for user ratings
metrics_stmt = select(
func.avg(func.extract('epoch', Ticket.resolved_at - Ticket.created_at) / 3600).label("avg_res"),
func.avg(func.cast(Feedback.rating, Float)).label("avg_csat"),
func.count(Feedback.id).label("rated_count"),
func.count(Ticket.id).filter(
(Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED])) &
(Ticket.sla_deadline < now)
).label("breached_count")
).outerjoin(Feedback, Ticket.id == Feedback.ticket_id).where(Ticket.deleted_at.is_(None))
if not is_global:
metrics_stmt = metrics_stmt.where(Ticket.workspace_id == target_ws)
if current_user.role == UserRole.CUSTOMER_USER:
metrics_stmt = metrics_stmt.where(Ticket.created_by == current_user.id)
metrics_res = await db.execute(metrics_stmt)
m_row = metrics_res.fetchone()
avg_res = m_row.avg_res or 0.0
avg_csat = m_row.avg_csat or 0.0
rated_count = m_row.rated_count or 0
breach_count = m_row.breached_count or 0
# 3. Personalized Open Count
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 current_user.role == UserRole.CUSTOMER_USER:
# Regular customers see only their own open tickets
my_open_stmt = my_open_stmt.where(Ticket.created_by == current_user.id)
# Else: CUSTOMER_ADMIN sees all open tickets in their workspace
if not is_global:
my_open_stmt = my_open_stmt.where(Ticket.workspace_id == target_ws)
my_open_res = await db.execute(my_open_stmt)
my_open_count = my_open_res.scalar() or 0
# 4. Personnel Load (Join Optimization)
personnel_stmt = (
select(User.full_name, func.count(Ticket.id))
.join(Ticket, Ticket.assigned_to == User.id)
.where(
Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]),
Ticket.deleted_at.is_(None)
)
)
if not is_global:
personnel_stmt = personnel_stmt.where(Ticket.workspace_id == target_ws)
personnel_stmt = personnel_stmt.group_by(User.full_name)
p_res = await db.execute(personnel_stmt)
personnel_load = [{"name": row[0], "count": row[1]} for row in p_res.all()]
# 5. Final Sanitization (Nexus Privacy Layer)
response = {
"total_tickets": total,
"by_status": counts,
"workspace_id": target_ws,
"my_open_count": my_open_count,
"performance": {
"avg_resolution_hours": round(avg_res, 1),
"csat_score": round(avg_csat, 1),
"rated_count": rated_count,
"sla_breached_count": breach_count
}
}
if is_staff:
# Staff get the full forensic payload
response.update({
"personnel_load": personnel_load
})
# Store in cache (60s TTL for stats)
await set_cached_search(cache_key, response, ttl=60)
return response
@router.get("/my-tickets/", response_model=List[Union[TicketInternalResponse, TicketResponse]])
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 sqlalchemy.orm import joinedload
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()
# Process each ticket through the role-based sanitizer
return [await sanitize_ticket_response(t, current_user, db) for t in tickets]
@router.get("/agent-queue/", response_model=List[Union[TicketInternalResponse, TicketResponse]])
async def get_agent_queue(
workspace_id: str = None,
refresh: bool = False,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> Any:
"""Get the active ticket queue. Restricted to internal staff only."""
from core.cache import get_cached_search, set_cached_search, delete_cached_search
# 0. Cache lookup
target_ws = workspace_id or str(current_user.workspace_id)
cache_key = f"dashboard:queue:{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 fastapi import HTTPException
from sqlalchemy.orm import joinedload
from api.v1.tickets import sanitize_ticket_response
is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
if not is_staff:
raise HTTPException(status_code=403, detail="Operational Access: Staff privilege required")
target_ws = current_user.workspace_id
is_super_admin = (current_user.role == UserRole.SC_ADMIN)
is_global = False
if is_super_admin and workspace_id == "all":
is_global = True
elif workspace_id:
if is_super_admin:
target_ws = workspace_id
else:
from models.user_workspace import UserWorkspace
ws_check = await db.execute(
select(UserWorkspace).where(
UserWorkspace.user_id == current_user.id,
UserWorkspace.workspace_id == workspace_id
)
)
if ws_check.scalar_one_or_none():
target_ws = workspace_id
stmt = (
select(Ticket)
.options(
joinedload(Ticket.creator),
joinedload(Ticket.assignee),
joinedload(Ticket.resolver),
joinedload(Ticket.feedback)
)
.where(
Ticket.deleted_at.is_(None)
)
)
if not is_global:
stmt = stmt.where(Ticket.workspace_id == target_ws)
stmt = stmt.order_by(Ticket.priority.asc(), Ticket.created_at.asc())
result = await db.execute(stmt)
tickets = result.scalars().all()
# Process each through sanitizer (will return full forensic view for staff)
res_data = [await sanitize_ticket_response(t, current_user, db) for t in tickets]
# Store in cache (60s TTL)
await set_cached_search(cache_key, res_data, ttl=60)
return res_data
@router.get("/ai-insights/")
async def get_ai_insights(
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
target_ws = workspace_id or str(current_user.workspace_id)
cache_key = f"dashboard:insights:{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
"""
Generates a live AI summary and suggested actions for the landing screen.
Special Mode: For Super-Admins, returns the cached global platform strategic analysis.
"""
from models.platform_insight import PlatformInsight
from sqlalchemy import desc
is_super_admin = (current_user.role == UserRole.SC_ADMIN)
is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
is_global = (is_super_admin and workspace_id == "all")
# 1. Global Tactical Mode (Super-Admin Only)
if is_global:
stmt = select(PlatformInsight).order_by(desc(PlatformInsight.updated_at)).limit(1)
res = await db.execute(stmt)
insight = res.scalar_one_or_none()
if insight:
return {
"summary": insight.summary,
"trends": insight.trends,
"type": "GLOBAL_FORENSIC_SNAPSHOT",
"last_updated": insight.updated_at.isoformat()
}
else:
return {
"summary": "Platform-wide strategic analysis is being initialized. Check back shortly.",
"trends": {},
"type": "GLOBAL_PENDING"
}
# 2. Standard Workspace Mode (Isolated)
# Gather context
stats = await get_dashboard_stats(workspace_id, refresh=refresh, current_user=current_user, db=db)
# Context varies by role: Staff get the full Queue, Customers get their recent activity
if is_staff:
queue = await get_agent_queue(workspace_id, refresh=refresh, current_user=current_user, db=db)
else:
# Fallback for CUSTOMER_ADMIN/USER: Get their workspace-visible tickets
from api.v1.tickets import list_tickets
queue = await list_tickets(limit=5, current_user=current_user, db=db)
# Prepare Prompt
llm = get_llm()
prompt = ChatPromptTemplate.from_template("""
You are the Nexus Workspace Intelligence Engine.
Analyze the following workspace operational data and provide:
1. A concise, professional "Mission Summary" (2-3 sentences).
2. Exactly 3 "Suggested Actions" for the lead agent.
DATA:
- Total Active Tickets: {total}
- Breached/Urgent: {breached}
- Distribution: {status_dist}
- Personnel: {agents}
TICKET SAMPLE:
{ticket_sample}
Respond in JSON format:
{{
"summary": "...",
"actions": ["...", "...", "..."]
}}
""")
# Format ticket sample for context (using dictionary access for sanitized data)
sample = "\n".join([f"- {t['title']} ({t['priority']}, {t['status']})" for t in queue[:5]])
chain = prompt | llm
try:
response = await chain.ainvoke({
"total": stats["total_tickets"],
"breached": any(t["priority"] == "P0" for t in queue),
"status_dist": stats["by_status"],
"agents": len(queue),
"ticket_sample": sample
})
# Robustly clean LLM response
text = response.content if hasattr(response, 'content') else str(response)
text = text.strip()
if not text:
raise ValueError("Empty LLM response")
json_str = text.replace("```json", "").replace("```", "").strip()
import json
insights = json.loads(json_str)
# Ensure schema compliance
result = {
"summary": insights.get("summary", "Analysis complete."),
"actions": insights.get("actions", ["Review unassigned tickets", "Check SLA trends", "Balance personnel load"])[:3]
}
# Store in cache (300s TTL for insights)
await set_cached_search(cache_key, result, ttl=300)
return result
except Exception as e:
logger.error(f"AI Insights Failure: {e}")
return {
"summary": f"Workspace stabilization in progress. {stats['total_tickets']} active tickets identified.",
"actions": [
"Review unassigned P0 tickets in the Operational Board",
"Perform load balance check across active personnel",
"Analyze SLA trends for potential breach risks"
]
}
@router.post("/refresh-global/")
async def refresh_global_insights(
current_user: User = Depends(get_current_user),
arq_pool = Depends(get_arq_pool)
) -> Any:
"""
Manually triggers a platform-wide forensic diagnostic cycle.
Strictly gate to Super-Admins only.
"""
if current_user.role != UserRole.SC_ADMIN:
from fastapi import HTTPException
raise HTTPException(status_code=403, detail="Strategic Refresh: Super-Admin Privilege Required")
await arq_pool.enqueue_job("generate_global_insight", _job_id="global_insight_refresh")
return {"status": "SUCCESS", "message": "Global strategic analysis enqueued for background processing."}