Spaces:
Paused

dushyantsingh0 commited on
Commit
186d110
·
1 Parent(s): b7ea785

backend stabilization

Browse files
agents/tools/nexus_tools.py CHANGED
@@ -730,6 +730,19 @@ async def assign_ticket_tool(ticket_id: UUID, user_id: UUID, workspace_id: UUID)
730
 
731
  if not t: return "Ticket not found or access denied."
732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
733
  t.assigned_to = user_id
734
  await db.commit()
735
 
 
730
 
731
  if not t: return "Ticket not found or access denied."
732
 
733
+ # 2. Verify target user is active in this workspace
734
+ user_stmt = select(User).join(UserWorkspace).where(
735
+ User.id == u_id,
736
+ UserWorkspace.workspace_id == workspace_id,
737
+ User.is_active == True,
738
+ UserWorkspace.is_active == True,
739
+ User.deleted_at.is_(None),
740
+ UserWorkspace.deleted_at.is_(None)
741
+ )
742
+ user_res = await db.execute(user_stmt)
743
+ if not user_res.scalar_one_or_none():
744
+ return f"Error: User `{user_id}` is inactive, deactivated, or not a member of this workspace. Assignment aborted."
745
+
746
  t.assigned_to = user_id
747
  await db.commit()
748
 
agents/utils.py CHANGED
@@ -23,7 +23,9 @@ async def get_available_agents(db: AsyncSession, workspace_id: UUID) -> List[Use
23
  UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), # INTERNAL ONLY
24
  User.global_role.is_distinct_from(UserRole.SUPERADMIN), # Exclude Global HQ from allocation
25
  User.is_active == True,
26
- User.deleted_at.is_(None)
 
 
27
  )
28
  result = await db.execute(stmt)
29
  verified_staff = list(result.scalars().all())
@@ -167,7 +169,9 @@ async def get_workspace_manager(db: AsyncSession, workspace_id: UUID) -> Optiona
167
  UserWorkspace.workspace_id == workspace_id,
168
  UserWorkspace.role == UserRole.SC_LEAD,
169
  User.is_active == True,
170
- User.deleted_at.is_(None)
 
 
171
  )
172
  .limit(1)
173
  )
@@ -184,7 +188,9 @@ async def get_workspace_manager(db: AsyncSession, workspace_id: UUID) -> Optiona
184
  UserWorkspace.workspace_id == workspace_id,
185
  UserWorkspace.role == UserRole.SC_ADMIN,
186
  User.is_active == True,
187
- User.deleted_at.is_(None)
 
 
188
  )
189
  .limit(1)
190
  )
 
23
  UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), # INTERNAL ONLY
24
  User.global_role.is_distinct_from(UserRole.SUPERADMIN), # Exclude Global HQ from allocation
25
  User.is_active == True,
26
+ User.deleted_at.is_(None),
27
+ UserWorkspace.is_active == True,
28
+ UserWorkspace.deleted_at.is_(None)
29
  )
30
  result = await db.execute(stmt)
31
  verified_staff = list(result.scalars().all())
 
169
  UserWorkspace.workspace_id == workspace_id,
170
  UserWorkspace.role == UserRole.SC_LEAD,
171
  User.is_active == True,
172
+ User.deleted_at.is_(None),
173
+ UserWorkspace.is_active == True,
174
+ UserWorkspace.deleted_at.is_(None)
175
  )
176
  .limit(1)
177
  )
 
188
  UserWorkspace.workspace_id == workspace_id,
189
  UserWorkspace.role == UserRole.SC_ADMIN,
190
  User.is_active == True,
191
+ User.deleted_at.is_(None),
192
+ UserWorkspace.is_active == True,
193
+ UserWorkspace.deleted_at.is_(None)
194
  )
195
  .limit(1)
196
  )
api/v1/dashboard.py CHANGED
@@ -100,7 +100,7 @@ async def get_dashboard_hydration(
100
  # During hydration, we only wait 10s for AI to prevent blocking the entire dashboard.
101
  # If it takes longer, we'll serve the background cache or a processing fallback.
102
  return await asyncio.wait_for(
103
- get_ai_insights(request, workspace_id, refresh, current_user, db),
104
  timeout=10.0
105
  )
106
  except asyncio.TimeoutError:
@@ -113,21 +113,32 @@ async def get_dashboard_hydration(
113
  return None
114
 
115
 
116
- # Unified Hydration with strict 35s total timeout to prevent frontend 45s timeout
117
  try:
118
- stats, reports, queue, escalations, insights = await asyncio.wait_for(
 
 
 
 
119
  asyncio.gather(
120
  run_stats(),
121
  run_reports(),
122
  run_queue(),
123
  run_escalations(),
124
- run_insights(),
125
- return_exceptions=True # Prevent one failure from killing the entire hydration
126
  ),
127
- timeout=35.0
128
  )
 
 
 
 
 
 
 
 
129
  except asyncio.TimeoutError:
130
- logger.error(f"Dashboard Hydration CRITICAL TIMEOUT for workspace {workspace_id}")
131
  return {
132
  "stats": {"by_status": {}, "performance": {}, "workspace_id": workspace_id},
133
  "reports": {"daily": [], "volume": {}, "csat": {}, "sla": {}},
@@ -488,7 +499,8 @@ async def get_ai_insights(
488
  workspace_id: str = None,
489
  refresh: bool = False,
490
  current_user: User = Depends(get_current_user),
491
- db: AsyncSession = Depends(get_db)
 
492
  ) -> Any:
493
  from core.cache import get_cached_search, set_cached_search, delete_cached_search
494
 
@@ -542,7 +554,10 @@ async def get_ai_insights(
542
 
543
  # 2. Standard Workspace Mode (Isolated)
544
  # Gather context
545
- stats = await get_dashboard_stats(request, workspace_id, refresh=refresh, current_user=current_user, db=db)
 
 
 
546
 
547
  # Context varies by role: Staff get the full Queue, Customers get their recent activity
548
  if is_staff:
 
100
  # During hydration, we only wait 10s for AI to prevent blocking the entire dashboard.
101
  # If it takes longer, we'll serve the background cache or a processing fallback.
102
  return await asyncio.wait_for(
103
+ get_ai_insights(request, workspace_id, refresh, current_user, db, precomputed_stats=stats_data),
104
  timeout=10.0
105
  )
106
  except asyncio.TimeoutError:
 
113
  return None
114
 
115
 
116
+ # TIERED HYDRATION: Parallelize base telemetry, then run AI insights
117
  try:
118
+ # Strictly enforce workspace context for logging accuracy
119
+ log_ws = workspace_id or str(current_user.workspace_id)
120
+
121
+ # 1. Base Telemetry Layer
122
+ telemetry_results = await asyncio.wait_for(
123
  asyncio.gather(
124
  run_stats(),
125
  run_reports(),
126
  run_queue(),
127
  run_escalations(),
128
+ return_exceptions=True
 
129
  ),
130
+ timeout=25.0
131
  )
132
+
133
+ stats, reports, queue, escalations = telemetry_results
134
+
135
+ # 2. Insights Layer (Dependent on Telemetry)
136
+ # We pass the pre-computed stats to avoid the redundant DB loop inside get_ai_insights
137
+ stats_data = stats if not isinstance(stats, Exception) else None
138
+ insights = await run_insights(stats_data)
139
+
140
  except asyncio.TimeoutError:
141
+ logger.error(f"Dashboard Hydration CRITICAL TIMEOUT for workspace {log_ws}")
142
  return {
143
  "stats": {"by_status": {}, "performance": {}, "workspace_id": workspace_id},
144
  "reports": {"daily": [], "volume": {}, "csat": {}, "sla": {}},
 
499
  workspace_id: str = None,
500
  refresh: bool = False,
501
  current_user: User = Depends(get_current_user),
502
+ db: AsyncSession = Depends(get_db),
503
+ precomputed_stats: Optional[Dict] = None
504
  ) -> Any:
505
  from core.cache import get_cached_search, set_cached_search, delete_cached_search
506
 
 
554
 
555
  # 2. Standard Workspace Mode (Isolated)
556
  # Gather context
557
+ if precomputed_stats:
558
+ stats = precomputed_stats
559
+ else:
560
+ stats = await get_dashboard_stats(request, workspace_id, refresh=refresh, current_user=current_user, db=db)
561
 
562
  # Context varies by role: Staff get the full Queue, Customers get their recent activity
563
  if is_staff:
api/v1/escalations.py CHANGED
@@ -177,7 +177,6 @@ async def list_active_breaches(
177
  EscalationRule.is_active == True
178
  ), isouter=True)
179
  .where(
180
- Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]),
181
  Ticket.deleted_at.is_(None)
182
  )
183
  )
@@ -190,7 +189,14 @@ async def list_active_breaches(
190
  for ticket, threshold in rows:
191
  # Default to 24h if no active rule exists
192
  limit = threshold or 1440
193
- age_mins = (now - ticket.created_at).total_seconds() / 60
 
 
 
 
 
 
 
194
 
195
  raw_risk_score = (age_mins / limit) * 100
196
  risk_score = min(100.0, round(raw_risk_score, 1))
@@ -206,7 +212,11 @@ async def list_active_breaches(
206
  risk_level = "NOMINAL"
207
 
208
  # Report any mission that has used > 50% of its SLA or has a rule
209
- if raw_risk_score > 50:
 
 
 
 
210
  detected_tickets.append({
211
  "id": str(ticket.id),
212
  "title": ticket.title,
@@ -218,7 +228,7 @@ async def list_active_breaches(
218
  "risk_score": risk_score,
219
  "risk_level": risk_level,
220
  "overdue_minutes": max(0, round(age_mins - limit, 1)) if raw_risk_score > 100 else 0,
221
- "minutes_remaining": max(0, round(limit - age_mins, 1)) if raw_risk_score <= 100 else 0,
222
  "is_escalated": ticket.is_escalated is not None,
223
  "is_breached": raw_risk_score > 100
224
  })
 
177
  EscalationRule.is_active == True
178
  ), isouter=True)
179
  .where(
 
180
  Ticket.deleted_at.is_(None)
181
  )
182
  )
 
189
  for ticket, threshold in rows:
190
  # Default to 24h if no active rule exists
191
  limit = threshold or 1440
192
+
193
+ # Frozen time for resolved/closed tickets
194
+ if ticket.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]:
195
+ # Use resolved_at if available, fallback to updated_at
196
+ end_time = ticket.resolved_at or ticket.updated_at or now
197
+ age_mins = (end_time - ticket.created_at).total_seconds() / 60
198
+ else:
199
+ age_mins = (now - ticket.created_at).total_seconds() / 60
200
 
201
  raw_risk_score = (age_mins / limit) * 100
202
  risk_score = min(100.0, round(raw_risk_score, 1))
 
212
  risk_level = "NOMINAL"
213
 
214
  # Report any mission that has used > 50% of its SLA or has a rule
215
+ # For resolved/closed tickets, only report if they ACTUALLY breached
216
+ is_active = ticket.status in [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]
217
+ should_report = raw_risk_score > 50 if is_active else raw_risk_score > 100
218
+
219
+ if should_report:
220
  detected_tickets.append({
221
  "id": str(ticket.id),
222
  "title": ticket.title,
 
228
  "risk_score": risk_score,
229
  "risk_level": risk_level,
230
  "overdue_minutes": max(0, round(age_mins - limit, 1)) if raw_risk_score > 100 else 0,
231
+ "minutes_remaining": max(0, round(limit - age_mins, 1)) if raw_risk_score <= 100 and is_active else 0,
232
  "is_escalated": ticket.is_escalated is not None,
233
  "is_breached": raw_risk_score > 100
234
  })
api/v1/reports.py CHANGED
@@ -330,13 +330,17 @@ async def get_user_performance_metrics(
330
  async def get_ai_service_insights(
331
  workspace_id: str = None,
332
  current_user: User = Depends(get_current_user),
333
- db: AsyncSession = Depends(get_db)
 
334
  ) -> Any:
335
  """Get AI-generated service health narrative."""
336
  from agents.analytics import generate_service_insights
337
 
338
- # 1. Get current SLA metrics
339
- metrics = await get_sla_compliance(workspace_id, current_user, db)
 
 
 
340
 
341
  # Strictly enforce current user's workspace, allowing override for Global Admin
342
  from uuid import UUID
@@ -614,48 +618,13 @@ async def get_reports_summary(
614
  async with async_session_factory() as session:
615
  return await coro_fn(*args, **kwargs, db=session)
616
 
 
617
  tasks = [
618
  run_isolated(get_volume_trends, workspace_id, 30, current_user),
619
  run_isolated(get_csat_report, workspace_id, current_user),
620
  run_isolated(get_sla_compliance, workspace_id, current_user),
621
  run_isolated(get_daily_stats, workspace_id, False, current_user),
622
  ]
623
-
624
- # Wrapped in a shield/timeout to prevent overall hydration failure
625
- async def run_insights_safe():
626
- try:
627
- # Increased timeout to 25s for more complex LLM reasoning cycles
628
- return await asyncio.wait_for(run_isolated(get_ai_service_insights, target_ws, current_user), timeout=25.0)
629
- except Exception as e:
630
- logger.warning(f"Dashboard Hydration: Insights timeout or failure [{type(e).__name__}]. Error: {str(e)}")
631
-
632
- # Retrieve from UserWorkspace cache as fallback (Nightly analysis)
633
- from models.user_workspace import UserWorkspace
634
- try:
635
- async with async_session_factory() as fallback_db:
636
- target_ws_id = workspace_id or str(current_user.workspace_id)
637
- from uuid import UUID
638
- try:
639
- target_ws_uuid = UUID(target_ws_id) if isinstance(target_ws_id, str) else target_ws_id
640
- except (ValueError, TypeError):
641
- # Fallback if invalid UUID
642
- return {"insights": "✨ **System Narrative**: Strategic analysis is currently being background-processed. Core metrics show stable operational flow.", "generated_at": datetime.utcnow().isoformat()}
643
-
644
- stmt = select(UserWorkspace).where(
645
- UserWorkspace.user_id == current_user.id,
646
- UserWorkspace.workspace_id == target_ws_uuid
647
- )
648
- result = await fallback_db.execute(stmt)
649
- uw = result.scalar_one_or_none()
650
- if uw and uw.ai_narrative:
651
- logger.info(f"⚡ DB Cache HIT [UserWorkspace Narrative Fallback]: {target_ws_uuid}")
652
- return {"insights": uw.ai_narrative, "generated_at": datetime.utcnow().isoformat(), "is_stale": True}
653
- except Exception as cache_e:
654
- logger.error(f"Fallback cache lookup failed: {cache_e}")
655
-
656
- return {"insights": "✨ **System Narrative**: High telemetry volume detected. Strategic analysis is currently being background-processed to maintain dashboard velocity.", "generated_at": datetime.utcnow().isoformat()}
657
-
658
- tasks.append(run_insights_safe())
659
 
660
  # Staff only segments
661
  is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
@@ -663,8 +632,30 @@ async def get_reports_summary(
663
  tasks.append(run_isolated(get_staff_performance, target_ws, current_user))
664
  tasks.append(run_isolated(get_escalation_assignee_trends, target_ws, current_user))
665
 
666
- results = await asyncio.gather(*tasks)
667
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668
  summary = {
669
  "volume": results[0],
670
  "csat": results[1],
 
330
  async def get_ai_service_insights(
331
  workspace_id: str = None,
332
  current_user: User = Depends(get_current_user),
333
+ db: AsyncSession = Depends(get_db),
334
+ precomputed_metrics: Optional[Dict] = None
335
  ) -> Any:
336
  """Get AI-generated service health narrative."""
337
  from agents.analytics import generate_service_insights
338
 
339
+ # 1. Get current SLA metrics (Only if not precomputed)
340
+ if precomputed_metrics:
341
+ metrics = precomputed_metrics
342
+ else:
343
+ metrics = await get_sla_compliance(workspace_id, current_user, db)
344
 
345
  # Strictly enforce current user's workspace, allowing override for Global Admin
346
  from uuid import UUID
 
618
  async with async_session_factory() as session:
619
  return await coro_fn(*args, **kwargs, db=session)
620
 
621
+ # 1. Prepare Base Telemetry Tasks
622
  tasks = [
623
  run_isolated(get_volume_trends, workspace_id, 30, current_user),
624
  run_isolated(get_csat_report, workspace_id, current_user),
625
  run_isolated(get_sla_compliance, workspace_id, current_user),
626
  run_isolated(get_daily_stats, workspace_id, False, current_user),
627
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
 
629
  # Staff only segments
630
  is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
 
632
  tasks.append(run_isolated(get_staff_performance, target_ws, current_user))
633
  tasks.append(run_isolated(get_escalation_assignee_trends, target_ws, current_user))
634
 
635
+ # 2. Sequential/Layered execution to avoid redundancy
636
+ # We run base telemetry first, then pass metrics to the AI insights
637
+ try:
638
+ telemetry_results = await asyncio.gather(*tasks)
639
+
640
+ # Index Mapping: 0:volume, 1:csat, 2:sla, 3:daily, 4:staff (if exists), 5:escalations (if exists)
641
+ sla_metrics = telemetry_results[2]
642
+
643
+ # Now run insights with precomputed metrics
644
+ insights = await run_isolated(get_ai_service_insights, workspace_id, current_user, precomputed_metrics=sla_metrics)
645
+
646
+ # Force insights to be at index 4 for consistent summary mapping
647
+ # Structure: [volume, csat, sla, daily, insights, ...staff_results]
648
+ results = list(telemetry_results[:4]) + [insights] + list(telemetry_results[4:])
649
+ except Exception as e:
650
+ logger.error(f"Reports Summary Layered Execution Failed: {e}")
651
+ # Final safety fallback: Return basic structures if everything fails
652
+ return {
653
+ "volume": {}, "csat": {"average_rating": 0, "total_responses": 0},
654
+ "sla": {"sla_compliance_rate": 1.0, "breached_tickets": 0, "on_time_tickets": 0},
655
+ "daily": [], "insights": None, "staff": None, "escalations": None,
656
+ "error": str(e)
657
+ }
658
+
659
  summary = {
660
  "volume": results[0],
661
  "csat": results[1],
frontend/apps/internal/src/App.tsx CHANGED
@@ -181,6 +181,7 @@ function AuthenticatedPortal({ user, authLoading, logout, refreshUser, hasRole }
181
  case 'escalation':
182
  return isAdminOrLead ? (
183
  <EscalationCentre
 
184
  onTicketSelect={(t) => {
185
  setSelectedTicket(t);
186
  setActiveTab('detail');
 
181
  case 'escalation':
182
  return isAdminOrLead ? (
183
  <EscalationCentre
184
+ workspaceId={selectedWorkspaceId}
185
  onTicketSelect={(t) => {
186
  setSelectedTicket(t);
187
  setActiveTab('detail');
frontend/apps/internal/src/components/EscalationCentre.tsx CHANGED
@@ -6,12 +6,13 @@ import styles from './EscalationCentre.module.css';
6
  import { RuleModal } from './RuleModal';
7
 
8
  interface EscalationCentreProps {
 
9
  onTicketSelect?: (ticket: any) => void;
10
  }
11
 
12
- export const EscalationCentre: React.FC<EscalationCentreProps> = ({ onTicketSelect }) => {
13
- const { sla, loading: reportsLoading } = useReports();
14
- const { rules, breaches, audit, loading: escLoading, createRule, updateRule, deleteRule } = useEscalations();
15
  const { hasRole } = useAuth();
16
 
17
  const [isModalOpen, setIsModalOpen] = useState(false);
 
6
  import { RuleModal } from './RuleModal';
7
 
8
  interface EscalationCentreProps {
9
+ workspaceId?: string;
10
  onTicketSelect?: (ticket: any) => void;
11
  }
12
 
13
+ export const EscalationCentre: React.FC<EscalationCentreProps> = ({ workspaceId, onTicketSelect }) => {
14
+ const { sla, loading: reportsLoading } = useReports(workspaceId);
15
+ const { rules, breaches, audit, loading: escLoading, createRule, updateRule, deleteRule } = useEscalations(workspaceId);
16
  const { hasRole } = useAuth();
17
 
18
  const [isModalOpen, setIsModalOpen] = useState(false);
frontend/packages/shared/src/hooks/useDashboard.ts CHANGED
@@ -162,49 +162,45 @@ export interface ServiceNarrative {
162
  generated_at: string;
163
  }
164
 
165
- // Global state for reports
166
- let globalReports: {
167
- volume: VolumeTrend | null;
168
- daily: DailyStat[];
169
- sla: SLAMetrics | null;
170
- csat: CSATMetrics | null;
171
- staff: StaffPerformance | null;
172
- escalations: EscalationTrend | null;
173
- insights: ServiceNarrative | null;
174
- } = { volume: null, daily: [], sla: null, csat: null, staff: null, escalations: null, insights: null };
175
  let globalReportsLoading = false;
176
  let globalReportsError: string | null = null;
177
- let lastReportsFetch = 0;
178
- const reportsListeners = new Set<(r: typeof globalReports, l: boolean, e: string | null) => void>();
179
 
180
- const notifyReports = () => reportsListeners.forEach(l => l(globalReports, globalReportsLoading, globalReportsError));
181
 
182
  export const useReports = (workspaceId?: string) => {
183
- const [localReports, setLocalReports] = useState(globalReports);
 
184
  const [loading, setLoading] = useState(globalReportsLoading);
185
  const [error, setError] = useState(globalReportsError);
186
 
187
  useEffect(() => {
188
- const listener = (r: typeof globalReports, l: boolean, e: string | null) => {
189
- setLocalReports(r);
190
- setLoading(l);
191
- setError(e);
 
 
192
  };
193
  reportsListeners.add(listener);
194
  return () => {
195
  reportsListeners.delete(listener);
196
  };
197
- }, []);
198
 
199
  const fetchReports = useCallback(async (force: boolean = false) => {
200
- const isStale = Date.now() - lastReportsFetch > STALE_WINDOW;
201
- if (!force && globalReports.volume && !isStale) return;
 
202
 
203
- if (!force && globalReports.volume && isStale) {
204
  // Quiet
205
  } else {
206
  globalReportsLoading = true;
207
- notifyReports();
208
  }
209
  try {
210
  let url = workspaceId ? `reports/summary/?workspace_id=${workspaceId}` : 'reports/summary/';
@@ -215,7 +211,7 @@ export const useReports = (workspaceId?: string) => {
215
  const response = await api.get(url);
216
  const data = response.data;
217
 
218
- globalReports = {
219
  volume: data.volume || null,
220
  sla: data.sla || null,
221
  daily: data.daily || [],
@@ -225,23 +221,19 @@ export const useReports = (workspaceId?: string) => {
225
  insights: data.insights || null
226
  };
227
 
228
- // AI insights are now handled within the summary for staff
229
- // If we need to update the narrative state as well:
230
- // Note: useServiceNarrative is separate, but we could sync it here if we wanted.
231
-
232
  globalReportsError = null;
233
- lastReportsFetch = Date.now();
234
  } catch (err: any) {
235
  globalReportsError = err.response?.data?.detail || 'Failed to fetch reports summary';
236
  } finally {
237
  globalReportsLoading = false;
238
- notifyReports();
239
  }
240
- }, [workspaceId]);
241
-
242
-
243
 
244
- // REMOVED: Redundant automatic fetch.
 
 
245
 
246
  return { ...localReports, loading, error, refresh: () => fetchReports(true) };
247
  };
@@ -327,44 +319,43 @@ export interface EscalationRule {
327
  is_active: boolean;
328
  }
329
 
330
- // Global state for escalations
331
- let globalEscalations: {
332
- rules: EscalationRule[];
333
- breaches: Breach[];
334
- audit: AuditEntry[];
335
- } = { rules: [], breaches: [], audit: [] };
336
  let globalEscalationsLoading = false;
337
  let globalEscalationsError: string | null = null;
338
- const escalationsListeners = new Set<(e: typeof globalEscalations, l: boolean, err: string | null) => void>();
339
 
340
- const notifyEscalations = () => {
341
- escalationsListeners.forEach(l => l(globalEscalations, globalEscalationsLoading, globalEscalationsError));
342
  };
343
 
344
  export const useEscalations = (workspaceId?: string) => {
345
- const [localEsc, setLocalEsc] = useState(globalEscalations);
 
346
  const [loading, setLoading] = useState(globalEscalationsLoading);
347
  const [error, setError] = useState(globalEscalationsError);
348
 
349
  useEffect(() => {
350
- const listener = (e: typeof globalEscalations, l: boolean, err: string | null) => {
351
- setLocalEsc(e);
352
- setLoading(l);
353
- setError(err);
 
 
354
  };
355
  escalationsListeners.add(listener);
356
  return () => {
357
  escalationsListeners.delete(listener);
358
  };
359
- }, []);
360
 
361
  const fetchData = useCallback(async (force: boolean = false) => {
362
- if (!force && (globalEscalations.rules.length > 0 || globalEscalations.breaches.length > 0)) {
363
  return;
364
  }
365
 
366
  globalEscalationsLoading = true;
367
- notifyEscalations();
368
  try {
369
  const u = (p: string) => workspaceId ? `${p}?workspace_id=${workspaceId}` : p;
370
  const [rRes, bRes, aRes] = await Promise.all([
@@ -372,7 +363,7 @@ export const useEscalations = (workspaceId?: string) => {
372
  api.get(u('escalations/breaches/')),
373
  api.get(u('escalations/audit/'))
374
  ]);
375
- globalEscalations = {
376
  rules: rRes.data,
377
  breaches: bRes.data,
378
  audit: aRes.data
@@ -382,9 +373,13 @@ export const useEscalations = (workspaceId?: string) => {
382
  globalEscalationsError = err.response?.data?.detail || 'Failed to fetch escalation data';
383
  } finally {
384
  globalEscalationsLoading = false;
385
- notifyEscalations();
386
  }
387
- }, [workspaceId]);
 
 
 
 
388
 
389
  const createRule = async (data: any) => {
390
  try {
@@ -393,7 +388,7 @@ export const useEscalations = (workspaceId?: string) => {
393
  return true;
394
  } catch (err: any) {
395
  globalEscalationsError = err.response?.data?.detail || 'Failed to create rule';
396
- notifyEscalations();
397
  return false;
398
  }
399
  };
@@ -405,7 +400,7 @@ export const useEscalations = (workspaceId?: string) => {
405
  return true;
406
  } catch (err: any) {
407
  globalEscalationsError = err.response?.data?.detail || 'Failed to update rule';
408
- notifyEscalations();
409
  return false;
410
  }
411
  };
@@ -417,15 +412,13 @@ export const useEscalations = (workspaceId?: string) => {
417
  return true;
418
  } catch (err: any) {
419
  globalEscalationsError = err.response?.data?.detail || 'Failed to delete rule';
420
- notifyEscalations();
421
  return false;
422
  }
423
  };
424
 
425
 
426
 
427
- // REMOVED: Redundant automatic fetch.
428
-
429
  return { ...localEsc, loading, error, refresh: () => fetchData(true), createRule, updateRule, deleteRule };
430
  };
431
 
@@ -479,8 +472,8 @@ export const useDashboardHydration = (workspaceId?: string) => {
479
  // Update individual global states to keep other hooks in sync if they are used elsewhere
480
  const wsKey = workspaceId || 'default';
481
  globalStatsMap[wsKey] = response.data.stats;
482
- globalReports = response.data.reports;
483
- globalEscalations = response.data.escalations || globalEscalations;
484
 
485
  // Patch: Sync AI Insights to prevent redundant fetch
486
  if (response.data.insights) {
@@ -495,23 +488,23 @@ export const useDashboardHydration = (workspaceId?: string) => {
495
  }
496
 
497
  // Patch: Sync Narrative so useServiceNarrative doesn't fire a redundant fetch
498
- if (globalReports?.insights) {
499
- globalNarrative = globalReports.insights;
500
  try { sessionStorage.setItem(NARRATIVE_CACHE_KEY, JSON.stringify(globalNarrative)); } catch { }
501
  }
502
 
503
  // Patch: Sync the individual fetch timestamps so child components don't immediately background refresh
504
  lastStatsFetchMap[wsKey] = Date.now();
505
- lastReportsFetch = Date.now();
506
 
507
  globalStatsError = null;
508
  globalReportsError = null;
509
  globalEscalationsError = null;
510
 
511
  notifyStats();
512
- notifyReports();
513
- notifyEscalations();
514
- if (globalReports?.insights) notifyNarrative();
515
 
516
  globalHydrationError = null;
517
  } catch (err: any) {
 
162
  generated_at: string;
163
  }
164
 
165
+ // Global state for reports (Workspace-aware)
166
+ const globalReportsMap: Record<string, any> = {};
 
 
 
 
 
 
 
 
167
  let globalReportsLoading = false;
168
  let globalReportsError: string | null = null;
169
+ let lastReportsFetchMap: Record<string, number> = {};
170
+ const reportsListeners = new Set<(ws: string, r: any, l: boolean, e: string | null) => void>();
171
 
172
+ const notifyReports = (ws: string) => reportsListeners.forEach(l => l(ws, globalReportsMap[ws], globalReportsLoading, globalReportsError));
173
 
174
  export const useReports = (workspaceId?: string) => {
175
+ const wsKey = workspaceId || 'default';
176
+ const [localReports, setLocalReports] = useState(globalReportsMap[wsKey] || { volume: null, daily: [], sla: null, csat: null, staff: null, escalations: null, insights: null });
177
  const [loading, setLoading] = useState(globalReportsLoading);
178
  const [error, setError] = useState(globalReportsError);
179
 
180
  useEffect(() => {
181
+ const listener = (ws: string, r: any, l: boolean, e: string | null) => {
182
+ if (ws === wsKey || ws === 'all') {
183
+ setLocalReports(r);
184
+ setLoading(l);
185
+ setError(e);
186
+ }
187
  };
188
  reportsListeners.add(listener);
189
  return () => {
190
  reportsListeners.delete(listener);
191
  };
192
+ }, [wsKey]);
193
 
194
  const fetchReports = useCallback(async (force: boolean = false) => {
195
+ const lastFetch = lastReportsFetchMap[wsKey] || 0;
196
+ const isStale = Date.now() - lastFetch > STALE_WINDOW;
197
+ if (!force && globalReportsMap[wsKey] && !isStale) return;
198
 
199
+ if (!force && globalReportsMap[wsKey] && isStale) {
200
  // Quiet
201
  } else {
202
  globalReportsLoading = true;
203
+ notifyReports(wsKey);
204
  }
205
  try {
206
  let url = workspaceId ? `reports/summary/?workspace_id=${workspaceId}` : 'reports/summary/';
 
211
  const response = await api.get(url);
212
  const data = response.data;
213
 
214
+ globalReportsMap[wsKey] = {
215
  volume: data.volume || null,
216
  sla: data.sla || null,
217
  daily: data.daily || [],
 
221
  insights: data.insights || null
222
  };
223
 
 
 
 
 
224
  globalReportsError = null;
225
+ lastReportsFetchMap[wsKey] = Date.now();
226
  } catch (err: any) {
227
  globalReportsError = err.response?.data?.detail || 'Failed to fetch reports summary';
228
  } finally {
229
  globalReportsLoading = false;
230
+ notifyReports(wsKey);
231
  }
232
+ }, [workspaceId, wsKey]);
 
 
233
 
234
+ useEffect(() => {
235
+ fetchReports();
236
+ }, [fetchReports]);
237
 
238
  return { ...localReports, loading, error, refresh: () => fetchReports(true) };
239
  };
 
319
  is_active: boolean;
320
  }
321
 
322
+ // Global state for escalations (Workspace-aware)
323
+ const globalEscalationsMap: Record<string, any> = {};
 
 
 
 
324
  let globalEscalationsLoading = false;
325
  let globalEscalationsError: string | null = null;
326
+ const escalationsListeners = new Set<(ws: string, e: any, l: boolean, err: string | null) => void>();
327
 
328
+ const notifyEscalations = (ws: string) => {
329
+ escalationsListeners.forEach(l => l(ws, globalEscalationsMap[ws], globalEscalationsLoading, globalEscalationsError));
330
  };
331
 
332
  export const useEscalations = (workspaceId?: string) => {
333
+ const wsKey = workspaceId || 'default';
334
+ const [localEsc, setLocalEsc] = useState(globalEscalationsMap[wsKey] || { rules: [], breaches: [], audit: [] });
335
  const [loading, setLoading] = useState(globalEscalationsLoading);
336
  const [error, setError] = useState(globalEscalationsError);
337
 
338
  useEffect(() => {
339
+ const listener = (ws: string, e: any, l: boolean, err: string | null) => {
340
+ if (ws === wsKey || ws === 'all') {
341
+ setLocalEsc(e || { rules: [], breaches: [], audit: [] });
342
+ setLoading(l);
343
+ setError(err);
344
+ }
345
  };
346
  escalationsListeners.add(listener);
347
  return () => {
348
  escalationsListeners.delete(listener);
349
  };
350
+ }, [wsKey]);
351
 
352
  const fetchData = useCallback(async (force: boolean = false) => {
353
+ if (!force && globalEscalationsMap[wsKey] && (globalEscalationsMap[wsKey].rules.length > 0 || globalEscalationsMap[wsKey].breaches.length > 0)) {
354
  return;
355
  }
356
 
357
  globalEscalationsLoading = true;
358
+ notifyEscalations(wsKey);
359
  try {
360
  const u = (p: string) => workspaceId ? `${p}?workspace_id=${workspaceId}` : p;
361
  const [rRes, bRes, aRes] = await Promise.all([
 
363
  api.get(u('escalations/breaches/')),
364
  api.get(u('escalations/audit/'))
365
  ]);
366
+ globalEscalationsMap[wsKey] = {
367
  rules: rRes.data,
368
  breaches: bRes.data,
369
  audit: aRes.data
 
373
  globalEscalationsError = err.response?.data?.detail || 'Failed to fetch escalation data';
374
  } finally {
375
  globalEscalationsLoading = false;
376
+ notifyEscalations(wsKey);
377
  }
378
+ }, [workspaceId, wsKey]);
379
+
380
+ useEffect(() => {
381
+ fetchData();
382
+ }, [fetchData]);
383
 
384
  const createRule = async (data: any) => {
385
  try {
 
388
  return true;
389
  } catch (err: any) {
390
  globalEscalationsError = err.response?.data?.detail || 'Failed to create rule';
391
+ notifyEscalations(wsKey);
392
  return false;
393
  }
394
  };
 
400
  return true;
401
  } catch (err: any) {
402
  globalEscalationsError = err.response?.data?.detail || 'Failed to update rule';
403
+ notifyEscalations(wsKey);
404
  return false;
405
  }
406
  };
 
412
  return true;
413
  } catch (err: any) {
414
  globalEscalationsError = err.response?.data?.detail || 'Failed to delete rule';
415
+ notifyEscalations(wsKey);
416
  return false;
417
  }
418
  };
419
 
420
 
421
 
 
 
422
  return { ...localEsc, loading, error, refresh: () => fetchData(true), createRule, updateRule, deleteRule };
423
  };
424
 
 
472
  // Update individual global states to keep other hooks in sync if they are used elsewhere
473
  const wsKey = workspaceId || 'default';
474
  globalStatsMap[wsKey] = response.data.stats;
475
+ globalReportsMap[wsKey] = response.data.reports;
476
+ globalEscalationsMap[wsKey] = response.data.escalations || globalEscalationsMap[wsKey];
477
 
478
  // Patch: Sync AI Insights to prevent redundant fetch
479
  if (response.data.insights) {
 
488
  }
489
 
490
  // Patch: Sync Narrative so useServiceNarrative doesn't fire a redundant fetch
491
+ if (globalReportsMap[wsKey]?.insights) {
492
+ globalNarrative = globalReportsMap[wsKey].insights;
493
  try { sessionStorage.setItem(NARRATIVE_CACHE_KEY, JSON.stringify(globalNarrative)); } catch { }
494
  }
495
 
496
  // Patch: Sync the individual fetch timestamps so child components don't immediately background refresh
497
  lastStatsFetchMap[wsKey] = Date.now();
498
+ lastReportsFetchMap[wsKey] = Date.now();
499
 
500
  globalStatsError = null;
501
  globalReportsError = null;
502
  globalEscalationsError = null;
503
 
504
  notifyStats();
505
+ notifyReports(wsKey);
506
+ notifyEscalations(wsKey);
507
+ if (globalReportsMap[wsKey]?.insights) notifyNarrative();
508
 
509
  globalHydrationError = null;
510
  } catch (err: any) {
tasks/system.py CHANGED
@@ -204,6 +204,9 @@ async def monitor_sla_thresholds(ctx, *args, **kwargs):
204
  from agents.utils import get_available_agents
205
  from models.user import UserRole
206
 
 
 
 
207
  notification_tasks = []
208
  redis = get_redis_client()
209
 
@@ -218,18 +221,21 @@ async def monitor_sla_thresholds(ctx, *args, **kwargs):
218
  if ticket.assigned_to:
219
  recipients.append(ticket.assigned_to)
220
 
221
- # Fetch all staff to identify Leads and Admins
222
- all_staff = await get_available_agents(db, ticket.workspace_id)
 
 
 
223
  leads = [s.id for s in all_staff if s.role in [UserRole.SC_LEAD, UserRole.SC_ADMIN]]
224
- admins = [s.id for s in all_staff if s.role == UserRole.SC_ADMIN]
225
-
226
  # TIER 1: BREACHED (>100%)
227
  if raw_risk_score >= 100:
228
  # Notify Everyone (Assignee + Leads + Admins)
229
  target_ids = list(set(recipients + leads))
230
  for uid in target_ids:
231
- notification_tasks.append(send_triple_notification(
232
- ctx, uid, ticket.workspace_id,
 
233
  "🚨 SLA BREACHED: Immediate Intervention Required",
234
  f"Ticket '{ticket.title}' (P:{ticket.priority}) has exceeded its SLA. Urgent action needed.",
235
  link=f"/dashboard?ticket={ticket.id}"
@@ -251,8 +257,9 @@ async def monitor_sla_thresholds(ctx, *args, **kwargs):
251
  # Notify Assignee + Leads
252
  target_ids = list(set(recipients + leads))
253
  for uid in target_ids:
254
- notification_tasks.append(send_triple_notification(
255
- ctx, uid, ticket.workspace_id,
 
256
  "🚨 CRITICAL RISK: SLA Breach Imminent (85%)",
257
  f"Ticket '{ticket.title}' is at 85% of its SLA. Resolution required immediately.",
258
  link=f"/dashboard?ticket={ticket.id}"
@@ -269,8 +276,9 @@ async def monitor_sla_thresholds(ctx, *args, **kwargs):
269
  if not await redis.get(latch):
270
  # Notify Assignee ONLY
271
  for uid in recipients:
272
- notification_tasks.append(send_triple_notification(
273
- ctx, uid, ticket.workspace_id,
 
274
  "⚠️ SLA WARNING: 60% Capacity Reached",
275
  f"Ticket '{ticket.title}' has utilized 60% of its SLA window. Please prioritize.",
276
  link=f"/dashboard?ticket={ticket.id}"
@@ -284,9 +292,10 @@ async def monitor_sla_thresholds(ctx, *args, **kwargs):
284
  except Exception as e:
285
  logger.error(f"SLA Monitor error for ticket {ticket.id}: {e}")
286
 
287
- # Batch commit and notification dispatch
288
  if len(notification_tasks) >= 20:
289
  await db.commit()
 
290
  await asyncio.gather(*notification_tasks, return_exceptions=True)
291
  notification_tasks = []
292
 
 
204
  from agents.utils import get_available_agents
205
  from models.user import UserRole
206
 
207
+ # Cache for staff per workspace to avoid N+1 queries
208
+ staff_cache = {}
209
+
210
  notification_tasks = []
211
  redis = get_redis_client()
212
 
 
221
  if ticket.assigned_to:
222
  recipients.append(ticket.assigned_to)
223
 
224
+ # Fetch all staff to identify Leads and Admins (Cached per workspace)
225
+ if ticket.workspace_id not in staff_cache:
226
+ staff_cache[ticket.workspace_id] = await get_available_agents(db, ticket.workspace_id)
227
+
228
+ all_staff = staff_cache[ticket.workspace_id]
229
  leads = [s.id for s in all_staff if s.role in [UserRole.SC_LEAD, UserRole.SC_ADMIN]]
230
+
 
231
  # TIER 1: BREACHED (>100%)
232
  if raw_risk_score >= 100:
233
  # Notify Everyone (Assignee + Leads + Admins)
234
  target_ids = list(set(recipients + leads))
235
  for uid in target_ids:
236
+ notification_tasks.append(enqueue_task(
237
+ "send_triple_notification",
238
+ uid, ticket.workspace_id,
239
  "🚨 SLA BREACHED: Immediate Intervention Required",
240
  f"Ticket '{ticket.title}' (P:{ticket.priority}) has exceeded its SLA. Urgent action needed.",
241
  link=f"/dashboard?ticket={ticket.id}"
 
257
  # Notify Assignee + Leads
258
  target_ids = list(set(recipients + leads))
259
  for uid in target_ids:
260
+ notification_tasks.append(enqueue_task(
261
+ "send_triple_notification",
262
+ uid, ticket.workspace_id,
263
  "🚨 CRITICAL RISK: SLA Breach Imminent (85%)",
264
  f"Ticket '{ticket.title}' is at 85% of its SLA. Resolution required immediately.",
265
  link=f"/dashboard?ticket={ticket.id}"
 
276
  if not await redis.get(latch):
277
  # Notify Assignee ONLY
278
  for uid in recipients:
279
+ notification_tasks.append(enqueue_task(
280
+ "send_triple_notification",
281
+ uid, ticket.workspace_id,
282
  "⚠️ SLA WARNING: 60% Capacity Reached",
283
  f"Ticket '{ticket.title}' has utilized 60% of its SLA window. Please prioritize.",
284
  link=f"/dashboard?ticket={ticket.id}"
 
292
  except Exception as e:
293
  logger.error(f"SLA Monitor error for ticket {ticket.id}: {e}")
294
 
295
+ # Commit changes every 20 tickets to keep transaction duration low
296
  if len(notification_tasks) >= 20:
297
  await db.commit()
298
+ # Run enqueue_task calls in parallel (they are fast as they only push to Redis)
299
  await asyncio.gather(*notification_tasks, return_exceptions=True)
300
  notification_tasks = []
301