Spaces:
Paused

miracle / tasks /analytics.py
dushyantsingh0
Claude Sonnet 4.6
fix: normalize naive DB datetimes to UTC-aware in personnel analytics
94afd06
Raw History Blame Contribute Delete
9.57 kB
"""
Analytics and personnel-related background tasks.
"""
from typing import Optional, Dict
from uuid import UUID
from datetime import datetime, timezone, timedelta
from sqlalchemy import select
from core.database import async_session_factory
from core.logging import get_logger
from core.llm import get_llm
from models.user import User, UserRole
from models.user_workspace import UserWorkspace
from models.ticket import Ticket, TicketStatus
from models.escalation_rule import EscalationRule
from models.message import Message
from tasks.system import check_cron_lock
from langchain_core.prompts import ChatPromptTemplate
logger = get_logger(__name__)
def _compute_tier(compliance: int, resolved: int, active_load: int) -> str:
if compliance >= 90 and resolved >= 8:
return "TOP"
elif compliance >= 75 and resolved >= 3:
return "STRONG"
elif compliance >= 55:
return "STEADY"
elif compliance >= 30:
return "AT_RISK"
else:
return "CRITICAL"
async def harvest_expertise_task(ctx, ticket_id: UUID, **kwargs):
"""Analyze a resolved ticket and harvest skills for the agent."""
from agents.staff_profiler import harvest_agent_skills
async with async_session_factory() as db:
try:
stmt = select(Ticket).where(Ticket.id == ticket_id)
ticket = (await db.execute(stmt)).scalar_one_or_none()
if not ticket or not ticket.assigned_to:
return
msg_stmt = select(Message).where(Message.ticket_id == ticket_id).order_by(Message.created_at.asc())
msgs = (await db.execute(msg_stmt)).scalars().all()
agent_stmt = select(User).where(User.id == ticket.assigned_to)
agent = (await db.execute(agent_stmt)).scalar_one_or_none()
if not agent:
return
await harvest_agent_skills(db, ticket, msgs, agent)
except Exception as e:
logger.error(f"Expertise Harvesting failed: {e}")
async def generate_nightly_personnel_analytics(ctx, workspace_id: Optional[str] = None, user_id: Optional[UUID] = None, **kwargs):
"""
Gathers user activity metrics and generates an AI narrative.
If workspace_id is provided, it targets only that workspace.
If user_id is provided, it targets only that user.
"""
# Only check cron lock if this is a nightly run (no workspace_id/user_id)
if not workspace_id and not user_id:
if not await check_cron_lock(ctx, "generate_nightly_personnel_analytics"):
return
async with async_session_factory() as db:
# 1. Fetch memberships to process
stmt = select(UserWorkspace).where(
UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]),
UserWorkspace.is_active
)
if workspace_id:
stmt = stmt.where(UserWorkspace.workspace_id == UUID(workspace_id))
if user_id:
stmt = stmt.where(UserWorkspace.user_id == user_id)
memberships = (await db.execute(stmt)).scalars().all()
now = datetime.now(timezone.utc)
last_30d = now - timedelta(days=30)
# 2. Fetch escalation rules (workspace-aware)
rules_res = await db.execute(select(EscalationRule))
all_rules = rules_res.scalars().all()
rules_map = {}
for r in all_rules:
rules_map.setdefault(str(r.workspace_id), {})[r.priority_level.upper()] = r.threshold_minutes
for uw in memberships:
try:
# 2. GATHER INTELLIGENCE (Sync with API Forensic Logic)
from sqlalchemy import or_
tracked_stmt = select(Ticket).where(
Ticket.workspace_id == uw.workspace_id,
Ticket.deleted_at.is_(None),
or_(
(Ticket.resolved_by == uw.user_id) & (Ticket.resolved_at >= last_30d),
(Ticket.assigned_to == uw.user_id) & (Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]))
)
)
tracked_tickets = (await db.execute(tracked_stmt)).scalars().all()
ws_rules = rules_map.get(str(uw.workspace_id), {})
res_count = 0
active_count = 0
breached = 0
categories = {}
total_res_time = 0
for t in tracked_tickets:
# Robust priority lookup
p_val = t.priority.value if hasattr(t.priority, 'value') else str(t.priority)
limit = ws_rules.get(str(p_val).upper(), 1440)
# Normalize DB timestamps to UTC-aware (stored naive, Python now() is aware)
def _utc(dt):
if dt is None:
return None
return dt if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc)
end_time = _utc(t.resolved_at) or now
created_at = _utc(t.created_at)
duration_mins = (end_time - created_at).total_seconds() / 60
if t.resolved_at:
res_count += 1
total_res_time += duration_mins
# Category count (only for resolved)
cat = (t.category or "General").title()
categories[cat] = categories.get(cat, 0) + 1
else:
active_count += 1
if duration_mins > limit:
breached += 1
total_tracked = len(tracked_tickets)
compliance = round((total_tracked - breached) / total_tracked * 100) if total_tracked > 0 else 100
avg_res_h = round(total_res_time / res_count / 60, 1) if res_count > 0 else 0
# Generate AI Narrative
llm = get_llm(timeout=45)
# Dynamic context for prompt
metrics_summary = f"""
- Resolved (30d): {res_count}
- Active Load: {active_count}
- SLA Compliance: {compliance}%
- Avg Resolution Time: {avg_res_h} hours
- Primary Expertise: {', '.join([f"{k} ({v})" for k, v in sorted(categories.items(), key=lambda x: x[1], reverse=True)[:3]])}
"""
prompt = ChatPromptTemplate.from_template("""
You are a service operations analyst. Generate ONE concise, insight-driven sentence about this support agent's performance pattern β€” focus on what the data implies, not what it says.
Metrics (do NOT restate these numbers directly):
{metrics}
Rules:
- Do NOT start with "The agent", "Over the past 30 days", "The staff member", or any similar opener
- Start directly with the core finding, risk, or strength
- Highlight the most significant signal: bottleneck, throughput gap, SLA risk, or standout pattern
- If Resolved is 0, flag the throughput gap; if SLA is below 50%, flag the compliance risk
- Be specific and actionable β€” no generic observations
Good examples:
- "Backlog pressure is intensifying β€” 7 unresolved cases with no recent throughput signals capacity saturation."
- "High throughput combined with 9.9h average resolution suggests complex-case specialization rather than general volume handling."
- "Zero resolutions despite active load indicates potential assignment-pipeline misalignment or escalation dependency."
- "SLA compliance at 14% signals systemic delays β€” active cases are consistently breaching agreed response windows."
Output ONLY the single insight sentence.
""")
narrative_res = await (prompt | llm).ainvoke({"metrics": metrics_summary})
uw.ai_narrative = narrative_res.content.strip()
uw.activity_summary = {
"resolved_30d": res_count,
"compliance": compliance,
"avg_res_h": avg_res_h,
"active_load": active_count,
"tier": _compute_tier(compliance, res_count, active_count),
"last_calculated": now.isoformat()
}
db.add(uw)
# Commit frequently to avoid massive transactions if processing many users
await db.commit()
except Exception as e:
logger.error(f"Failed to generate narrative for user {uw.user_id}: {e}")
continue
# 3. Broadcast Sync Signal
from core.websockets import manager
if workspace_id:
try:
await manager.broadcast_to_workspace(UUID(workspace_id), {
"type": "PERSONNEL_ANALYTICS_READY",
"workspace_id": workspace_id
})
logger.info(f"βœ… Personnel analytics ready signal broadcasted for workspace: {workspace_id}")
except Exception as broadcast_err:
logger.error(f"Failed to broadcast personnel analytics signal: {broadcast_err}")