Spaces:
Paused

dushyantsingh0 commited on
Commit
1e6a00d
·
1 Parent(s): 2829e9b

feat: leadership-driven personnel AI narrative refresh with 24h throttle

Browse files
api/v1/reports.py CHANGED
@@ -698,3 +698,61 @@ async def get_reports_summary(
698
  await set_cached_object(cache_key, summary, ttl=60)
699
 
700
  return summary
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698
  await set_cached_object(cache_key, summary, ttl=60)
699
 
700
  return summary
701
+
702
+ @router.post("/personnel/refresh/", dependencies=[Depends(require_roles([UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SUPERADMIN]))])
703
+ async def trigger_personnel_refresh(
704
+ workspace_id: str = None,
705
+ current_user: User = Depends(get_current_user),
706
+ db: AsyncSession = Depends(get_db),
707
+ arq_pool = Depends(get_arq_pool)
708
+ ) -> Any:
709
+ """
710
+ Manually trigger a refresh of personnel AI narratives for a workspace.
711
+ Throttled to once per 24 hours per workspace to prevent LLM spam.
712
+ """
713
+ # 1. Workspace Context
714
+ target_ws, _ = await get_effective_context(db, current_user, workspace_id)
715
+
716
+ from core.cache import get_redis_client
717
+ import json
718
+ redis = get_redis_client()
719
+
720
+ throttle_key = f"throttle:personnel_refresh:{target_ws}"
721
+
722
+ # 2. Check Throttle
723
+ existing_throttle = await redis.get(throttle_key)
724
+ if existing_throttle:
725
+ # Calculate remaining time
726
+ ttl = await redis.ttl(throttle_key)
727
+ hours = ttl // 3600
728
+ mins = (ttl % 3600) // 60
729
+ from fastapi import HTTPException
730
+ raise HTTPException(
731
+ status_code=429,
732
+ detail=f"Personnel analytics were recently refreshed. Next manual refresh available in {hours}h {mins}m."
733
+ )
734
+
735
+ # 3. Enqueue Task
736
+ from core.tasks import enqueue_task
737
+ try:
738
+ # Set 24-hour throttle
739
+ await redis.setex(throttle_key, 86400, "1")
740
+ await enqueue_task(arq_pool, "generate_nightly_personnel_analytics", workspace_id=str(target_ws))
741
+
742
+ # Log to Audit
743
+ from models.audit_log import AuditLog
744
+ db.add(AuditLog(
745
+ workspace_id=target_ws,
746
+ entity_type="workspace",
747
+ entity_id=target_ws,
748
+ action="MANUAL_PERSONNEL_REFRESH",
749
+ user_id=current_user.id,
750
+ new_value={"requested_by": current_user.full_name}
751
+ ))
752
+ await db.commit()
753
+
754
+ return {"status": "SUCCESS", "message": "Personnel AI narrative synthesis enqueued. Updates will appear shortly."}
755
+ except Exception as e:
756
+ logger.error(f"Failed to trigger personnel refresh: {e}")
757
+ await redis.delete(throttle_key)
758
+ return {"status": "ERROR", "message": str(e)}
frontend/apps/internal/src/components/AnalyticsDashboard.module.css CHANGED
@@ -588,6 +588,15 @@
588
 
589
  .sectionHeader {
590
  margin-bottom: 24px;
 
 
 
 
 
 
 
 
 
591
  }
592
 
593
  .sectionHeader h3 {
 
588
 
589
  .sectionHeader {
590
  margin-bottom: 24px;
591
+ display: flex;
592
+ justify-content: space-between;
593
+ align-items: flex-end;
594
+ gap: 20px;
595
+ }
596
+
597
+ .sectionTitleGroup {
598
+ display: flex;
599
+ flex-direction: column;
600
  }
601
 
602
  .sectionHeader h3 {
frontend/apps/internal/src/components/AnalyticsDashboard.tsx CHANGED
@@ -58,8 +58,22 @@ export const AnalyticsDashboard: React.FC<AnalyticsDashboardProps> = ({ workspac
58
  const { narrative, loading: narrativeLoading, refresh: refreshNarrative } = useServiceNarrative(workspaceId);
59
 
60
  const [timeRange, setTimeRange] = useState(30);
 
 
 
61
  const { trend: slaTrend, loading: slaLoading } = useSLATrend(workspaceId, timeRange);
62
- const { metrics: userMetrics, loading: userMetricsLoading } = useUserMetrics(workspaceId, timeRange);
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  const isLoading = statsLoading || reportsLoading || escLoading || aiLoading || narrativeLoading || slaLoading || userMetricsLoading;
65
  const safeDaily = daily || [];
@@ -295,8 +309,18 @@ export const AnalyticsDashboard: React.FC<AnalyticsDashboardProps> = ({ workspac
295
  {/* 6. User Operational Metrics Table */}
296
  <div className={styles.userMetricsSection}>
297
  <div className={styles.sectionHeader}>
298
- <h3>USER PERFORMANCE & SLA TRACKING</h3>
299
- <p>Real-time efficiency metrics by personnel with neural impact narratives.</p>
 
 
 
 
 
 
 
 
 
 
300
  </div>
301
  <div className={styles.tableWrapper}>
302
  <table className={styles.metricsTable}>
 
58
  const { narrative, loading: narrativeLoading, refresh: refreshNarrative } = useServiceNarrative(workspaceId);
59
 
60
  const [timeRange, setTimeRange] = useState(30);
61
+ const { addNotification } = useNotification();
62
+ const [refreshingNarratives, setRefreshingNarratives] = useState(false);
63
+
64
  const { trend: slaTrend, loading: slaLoading } = useSLATrend(workspaceId, timeRange);
65
+ const { metrics: userMetrics, loading: userMetricsLoading, refreshNarratives } = useUserMetrics(workspaceId, timeRange);
66
+
67
+ const handleRefreshNarratives = async () => {
68
+ setRefreshingNarratives(true);
69
+ const result = await refreshNarratives();
70
+ if (result.success) {
71
+ addNotification('SUCCESS', 'Personnel AI narratives enqueued for synthesis.');
72
+ } else {
73
+ addNotification('WARNING', result.error || 'Failed to trigger narrative refresh.');
74
+ }
75
+ setRefreshingNarratives(false);
76
+ };
77
 
78
  const isLoading = statsLoading || reportsLoading || escLoading || aiLoading || narrativeLoading || slaLoading || userMetricsLoading;
79
  const safeDaily = daily || [];
 
309
  {/* 6. User Operational Metrics Table */}
310
  <div className={styles.userMetricsSection}>
311
  <div className={styles.sectionHeader}>
312
+ <div className={styles.sectionTitleGroup}>
313
+ <h3>USER PERFORMANCE & SLA TRACKING</h3>
314
+ <p>Real-time efficiency metrics by personnel with neural impact narratives.</p>
315
+ </div>
316
+ <button
317
+ className={styles.regenerateButton}
318
+ onClick={handleRefreshNarratives}
319
+ disabled={refreshingNarratives || userMetricsLoading}
320
+ >
321
+ <RotateCcw size={14} className={refreshingNarratives ? styles.spinning : ''} />
322
+ <span>{refreshingNarratives ? 'SYNTHESIZING...' : 'REGENERATE OPINIONS'}</span>
323
+ </button>
324
  </div>
325
  <div className={styles.tableWrapper}>
326
  <table className={styles.metricsTable}>
frontend/packages/shared/src/hooks/useDashboard.ts CHANGED
@@ -317,11 +317,21 @@ export const useUserMetrics = (workspaceId?: string, days: number = 30) => {
317
  }
318
  }, [workspaceId, days, cacheKey]);
319
 
 
 
 
 
 
 
 
 
 
 
320
  useEffect(() => {
321
  fetchMetrics();
322
  }, [fetchMetrics]);
323
 
324
- return { metrics, loading, refresh: () => fetchMetrics(true) };
325
  };
326
 
327
  export interface Breach {
 
317
  }
318
  }, [workspaceId, days, cacheKey]);
319
 
320
+ const refreshNarratives = useCallback(async () => {
321
+ try {
322
+ await api.post('reports/personnel/refresh/', null, { params: { workspace_id: workspaceId } });
323
+ return { success: true };
324
+ } catch (err: any) {
325
+ const msg = err.response?.data?.detail || 'Refresh throttled or failed';
326
+ return { success: false, error: msg };
327
+ }
328
+ }, [workspaceId]);
329
+
330
  useEffect(() => {
331
  fetchMetrics();
332
  }, [fetchMetrics]);
333
 
334
+ return { metrics, loading, refresh: () => fetchMetrics(true), refreshNarratives };
335
  };
336
 
337
  export interface Breach {
tasks/analytics.py CHANGED
@@ -38,28 +38,113 @@ async def harvest_expertise_task(ctx, ticket_id: UUID, **kwargs):
38
  except Exception as e:
39
  logger.error(f"Expertise Harvesting failed: {e}")
40
 
41
- async def generate_nightly_personnel_analytics(ctx, **kwargs):
42
- """Gathers user activity metrics and generates an AI narrative."""
43
- if not await check_cron_lock(ctx, "generate_nightly_personnel_analytics"): return
 
 
 
 
 
 
44
 
45
  async with async_session_factory() as db:
46
- stmt = select(UserWorkspace).where(UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), UserWorkspace.is_active == True)
 
 
 
 
 
 
 
 
 
47
  memberships = (await db.execute(stmt)).scalars().all()
48
 
49
  now = datetime.utcnow()
50
- last_7d = now - timedelta(days=7)
51
 
 
 
 
 
 
 
 
52
  for uw in memberships:
53
  try:
54
- # Basic metrics
55
- res_count = (await db.execute(select(func.count(Ticket.id)).where(Ticket.resolved_by == uw.user_id, Ticket.resolved_at >= last_7d))).scalar() or 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- llm = get_llm(timeout=30)
58
- prompt = ChatPromptTemplate.from_template("Generate performance narrative for staff member with {res} resolutions.")
59
- narrative_res = await (prompt | llm).ainvoke({"res": res_count})
60
 
61
  uw.ai_narrative = narrative_res.content.strip()
62
- uw.activity_summary = {"resolved_7d": res_count, "last_calculated": now.isoformat()}
 
 
 
 
 
 
63
  db.add(uw)
64
- except Exception: continue
65
- await db.commit()
 
 
 
 
38
  except Exception as e:
39
  logger.error(f"Expertise Harvesting failed: {e}")
40
 
41
+ async def generate_nightly_personnel_analytics(ctx, workspace_id: str = None, user_id: UUID = None, **kwargs):
42
+ """
43
+ Gathers user activity metrics and generates an AI narrative.
44
+ If workspace_id is provided, it targets only that workspace.
45
+ If user_id is provided, it targets only that user.
46
+ """
47
+ # Only check cron lock if this is a nightly run (no workspace_id/user_id)
48
+ if not workspace_id and not user_id:
49
+ if not await check_cron_lock(ctx, "generate_nightly_personnel_analytics"): return
50
 
51
  async with async_session_factory() as db:
52
+ # 1. Fetch memberships to process
53
+ stmt = select(UserWorkspace).where(
54
+ UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]),
55
+ UserWorkspace.is_active == True
56
+ )
57
+ if workspace_id:
58
+ stmt = stmt.where(UserWorkspace.workspace_id == UUID(workspace_id))
59
+ if user_id:
60
+ stmt = stmt.where(UserWorkspace.user_id == user_id)
61
+
62
  memberships = (await db.execute(stmt)).scalars().all()
63
 
64
  now = datetime.utcnow()
65
+ last_30d = now - timedelta(days=30)
66
 
67
+ # 2. Fetch escalation rules (workspace-aware)
68
+ rules_res = await db.execute(select(EscalationRule))
69
+ all_rules = rules_res.scalars().all()
70
+ rules_map = {}
71
+ for r in all_rules:
72
+ rules_map.setdefault(str(r.workspace_id), {})[r.priority_level.upper()] = r.threshold_minutes
73
+
74
  for uw in memberships:
75
  try:
76
+ # GATHER INTELLIGENCE
77
+ # Resolved in 30d
78
+ res_stmt = select(Ticket).where(
79
+ Ticket.resolved_by == uw.user_id,
80
+ Ticket.resolved_at >= last_30d,
81
+ Ticket.workspace_id == uw.workspace_id
82
+ )
83
+ resolved_tickets = (await db.execute(res_stmt)).scalars().all()
84
+
85
+ # Active assignments
86
+ active_count = (await db.execute(select(func.count(Ticket.id)).where(
87
+ Ticket.assigned_to == uw.user_id,
88
+ Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]),
89
+ Ticket.workspace_id == uw.workspace_id
90
+ ))).scalar() or 0
91
+
92
+ ws_rules = rules_map.get(str(uw.workspace_id), {})
93
+
94
+ breached = 0
95
+ categories = {}
96
+ total_res_time = 0
97
+
98
+ for t in resolved_tickets:
99
+ # SLA Check
100
+ p_val = t.priority.value if hasattr(t.priority, 'value') else str(t.priority)
101
+ limit = ws_rules.get(str(p_val).upper(), 1440)
102
+ duration = (t.resolved_at - t.created_at).total_seconds() / 60
103
+ if duration > limit:
104
+ breached += 1
105
+ total_res_time += duration
106
+
107
+ # Category count
108
+ cat = (t.category or "General").title()
109
+ categories[cat] = categories.get(cat, 0) + 1
110
+
111
+ res_count = len(resolved_tickets)
112
+ compliance = round((res_count - breached) / res_count * 100) if res_count > 0 else 100
113
+ avg_res_h = round(total_res_time / res_count / 60, 1) if res_count > 0 else 0
114
+
115
+ # Generate AI Narrative
116
+ llm = get_llm(timeout=45)
117
+
118
+ # Dynamic context for prompt
119
+ metrics_summary = f"""
120
+ - Resolved (30d): {res_count}
121
+ - Active Load: {active_count}
122
+ - SLA Compliance: {compliance}%
123
+ - Avg Resolution Time: {avg_res_h} hours
124
+ - Primary Expertise: {', '.join([f"{k} ({v})" for k, v in sorted(categories.items(), key=lambda x: x[1], reverse=True)[:3]])}
125
+ """
126
+
127
+ prompt = ChatPromptTemplate.from_template("""
128
+ You are a senior service operations analyst. Generate a forensic, professional, and objective 2-sentence performance narrative for a support staff member based on these 30-day metrics:
129
+ {metrics}
130
+
131
+ Tone: Analytical, direct, and slightly clinical. Avoid generic praise. Focus on throughput, SLA reliability, and load management.
132
+ Output only the 2-sentence narrative.
133
+ """)
134
 
135
+ narrative_res = await (prompt | llm).ainvoke({"metrics": metrics_summary})
 
 
136
 
137
  uw.ai_narrative = narrative_res.content.strip()
138
+ uw.activity_summary = {
139
+ "resolved_30d": res_count,
140
+ "compliance": compliance,
141
+ "avg_res_h": avg_res_h,
142
+ "active_load": active_count,
143
+ "last_calculated": now.isoformat()
144
+ }
145
  db.add(uw)
146
+ # Commit frequently to avoid massive transactions if processing many users
147
+ await db.commit()
148
+ except Exception as e:
149
+ logger.error(f"Failed to generate narrative for user {uw.user_id}: {e}")
150
+ continue