Spaces:
Paused

dushyantsingh0 commited on
Commit
1fdd745
·
1 Parent(s): 0afbc73

backend stabilization

Browse files
api/v1/escalations.py CHANGED
@@ -193,7 +193,18 @@ async def list_active_breaches(
193
  raw_risk_score = (age_mins / limit) * 100
194
  risk_score = min(100.0, round(raw_risk_score, 1))
195
 
196
- if raw_risk_score > 75:
 
 
 
 
 
 
 
 
 
 
 
197
  detected_tickets.append({
198
  "id": str(ticket.id),
199
  "title": ticket.title,
@@ -203,6 +214,7 @@ async def list_active_breaches(
203
  "age_minutes": round(age_mins, 1),
204
  "threshold": limit,
205
  "risk_score": risk_score,
 
206
  "overdue_minutes": max(0, round(age_mins - limit, 1)) if raw_risk_score > 100 else 0,
207
  "minutes_remaining": max(0, round(limit - age_mins, 1)) if raw_risk_score <= 100 else 0,
208
  "is_escalated": ticket.is_escalated is not None,
 
193
  raw_risk_score = (age_mins / limit) * 100
194
  risk_score = min(100.0, round(raw_risk_score, 1))
195
 
196
+ # NEW: Descriptive Risk Levels for "Mission Management"
197
+ if raw_risk_score > 100:
198
+ risk_level = "BREACHED"
199
+ elif raw_risk_score > 85:
200
+ risk_level = "CRITICAL"
201
+ elif raw_risk_score > 60:
202
+ risk_level = "WARNING"
203
+ else:
204
+ risk_level = "NOMINAL"
205
+
206
+ # Report any mission that has used > 50% of its SLA or has a rule
207
+ if raw_risk_score > 50:
208
  detected_tickets.append({
209
  "id": str(ticket.id),
210
  "title": ticket.title,
 
214
  "age_minutes": round(age_mins, 1),
215
  "threshold": limit,
216
  "risk_score": risk_score,
217
+ "risk_level": risk_level,
218
  "overdue_minutes": max(0, round(age_mins - limit, 1)) if raw_risk_score > 100 else 0,
219
  "minutes_remaining": max(0, round(limit - age_mins, 1)) if raw_risk_score <= 100 else 0,
220
  "is_escalated": ticket.is_escalated is not None,
frontend/apps/internal/src/components/DashboardOverview.module.css CHANGED
@@ -442,14 +442,33 @@
442
  /* 5 Recent Tickets Table */
443
  .tableBox {
444
  flex: 1;
445
- overflow: hidden;
 
446
  background: white;
447
  border-radius: var(--radius-md);
448
  border: 1px solid var(--border-subtle);
449
  }
450
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
  .miniTable {
452
  width: 100%;
 
453
  border-collapse: collapse;
454
  text-align: left;
455
  }
 
442
  /* 5 Recent Tickets Table */
443
  .tableBox {
444
  flex: 1;
445
+ overflow-x: auto;
446
+ overflow-y: hidden;
447
  background: white;
448
  border-radius: var(--radius-md);
449
  border: 1px solid var(--border-subtle);
450
  }
451
 
452
+ .tableBox::-webkit-scrollbar {
453
+ height: 4px;
454
+ }
455
+
456
+ .tableBox::-webkit-scrollbar-track {
457
+ background: transparent;
458
+ }
459
+
460
+ .tableBox::-webkit-scrollbar-thumb {
461
+ background: rgba(124, 58, 237, 0.15);
462
+ border-radius: 10px;
463
+ }
464
+
465
+ .tableBox::-webkit-scrollbar-thumb:hover {
466
+ background: rgba(124, 58, 237, 0.3);
467
+ }
468
+
469
  .miniTable {
470
  width: 100%;
471
+ min-width: 450px;
472
  border-collapse: collapse;
473
  text-align: left;
474
  }
frontend/apps/internal/src/components/EscalationCentre.module.css CHANGED
@@ -279,10 +279,29 @@
279
 
280
  .tableWrapper {
281
  overflow-x: auto;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  }
283
 
284
  .missionTable {
285
  width: 100%;
 
286
  border-collapse: collapse;
287
  }
288
 
 
279
 
280
  .tableWrapper {
281
  overflow-x: auto;
282
+ border-radius: 12px;
283
+ }
284
+
285
+ .tableWrapper::-webkit-scrollbar {
286
+ height: 6px;
287
+ }
288
+
289
+ .tableWrapper::-webkit-scrollbar-track {
290
+ background: transparent;
291
+ }
292
+
293
+ .tableWrapper::-webkit-scrollbar-thumb {
294
+ background: rgba(124, 58, 237, 0.15);
295
+ border-radius: 10px;
296
+ }
297
+
298
+ .tableWrapper::-webkit-scrollbar-thumb:hover {
299
+ background: rgba(124, 58, 237, 0.3);
300
  }
301
 
302
  .missionTable {
303
  width: 100%;
304
+ min-width: 900px;
305
  border-collapse: collapse;
306
  }
307
 
frontend/apps/internal/src/components/EscalationCentre.tsx CHANGED
@@ -109,8 +109,10 @@ export const EscalationCentre: React.FC<EscalationCentreProps> = ({ onTicketSele
109
  const matchesUser = userFilter === 'ALL' || userFilter === '' || bUser.includes(userFilter.toUpperCase());
110
  if (!matchesUser) return false;
111
 
112
- if (riskFilter === 'BREACHED') return b.is_breached;
113
- if (riskFilter === 'SOON') return !b.is_breached && b.minutes_remaining <= 1440;
 
 
114
 
115
  return true;
116
  });
@@ -187,10 +189,12 @@ export const EscalationCentre: React.FC<EscalationCentreProps> = ({ onTicketSele
187
  <option value="P2">P2 MEDIUM</option>
188
  <option value="P3">P3 LOW</option>
189
  </select>
190
- <select value={riskFilter} onChange={(e) => setRiskFilter(e.target.value)} style={{ marginLeft: '12px', borderLeft: '1px solid #E2E8F0', paddingLeft: '12px' }}>
191
  <option value="ALL">ALL RISKS</option>
192
- <option value="SOON">SOON TO BREACH (&lt;24h)</option>
193
- <option value="BREACHED">BREACHED ONLY</option>
 
 
194
  </select>
195
  <div style={{ position: 'relative', marginLeft: '12px', borderLeft: '1px solid #E2E8F0', paddingLeft: '12px', display: 'flex', alignItems: 'center' }}>
196
  <input
@@ -225,8 +229,8 @@ export const EscalationCentre: React.FC<EscalationCentreProps> = ({ onTicketSele
225
  <th>PRIORITY</th>
226
  <th>TIME TO BREACH</th>
227
  <th>RISK SCORE</th>
228
- <th>OVERDUE HOURS</th>
229
- <th>STATUS</th>
230
  </tr>
231
  </thead>
232
  <tbody>
@@ -280,7 +284,13 @@ export const EscalationCentre: React.FC<EscalationCentreProps> = ({ onTicketSele
280
  </div>
281
  </td>
282
  <td>
283
- <div className={styles.statusBadge}>{breach.status}</div>
 
 
 
 
 
 
284
  </td>
285
  </tr>
286
  )) : (
 
109
  const matchesUser = userFilter === 'ALL' || userFilter === '' || bUser.includes(userFilter.toUpperCase());
110
  if (!matchesUser) return false;
111
 
112
+ if (riskFilter === 'BREACHED') return b.risk_level === 'BREACHED';
113
+ if (riskFilter === 'CRITICAL') return b.risk_level === 'CRITICAL';
114
+ if (riskFilter === 'WARNING') return b.risk_level === 'WARNING';
115
+ if (riskFilter === 'NOMINAL') return b.risk_level === 'NOMINAL';
116
 
117
  return true;
118
  });
 
189
  <option value="P2">P2 MEDIUM</option>
190
  <option value="P3">P3 LOW</option>
191
  </select>
192
+ <select value={riskFilter} onChange={(e) => { setRiskFilter(e.target.value); setCurrentPage(1); }} style={{ marginLeft: '12px', borderLeft: '1px solid #E2E8F0', paddingLeft: '12px' }}>
193
  <option value="ALL">ALL RISKS</option>
194
+ <option value="BREACHED">⚠️ BREACHED</option>
195
+ <option value="CRITICAL">🚨 CRITICAL (&gt;85%)</option>
196
+ <option value="WARNING">⚡ WARNING (&gt;60%)</option>
197
+ <option value="NOMINAL">🟢 NOMINAL</option>
198
  </select>
199
  <div style={{ position: 'relative', marginLeft: '12px', borderLeft: '1px solid #E2E8F0', paddingLeft: '12px', display: 'flex', alignItems: 'center' }}>
200
  <input
 
229
  <th>PRIORITY</th>
230
  <th>TIME TO BREACH</th>
231
  <th>RISK SCORE</th>
232
+ <th>DELAY</th>
233
+ <th>SLA STATUS</th>
234
  </tr>
235
  </thead>
236
  <tbody>
 
284
  </div>
285
  </td>
286
  <td>
287
+ <div className={styles.statusBadge} style={{
288
+ color: breach.risk_level === 'BREACHED' ? 'var(--error)' : breach.risk_level === 'CRITICAL' ? 'var(--warning)' : 'inherit',
289
+ fontWeight: breach.risk_level === 'BREACHED' || breach.risk_level === 'CRITICAL' ? 900 : 500,
290
+ fontSize: '10px'
291
+ }}>
292
+ {breach.risk_level || breach.status}
293
+ </div>
294
  </td>
295
  </tr>
296
  )) : (
frontend/apps/internal/src/components/RuleModal.module.css CHANGED
@@ -141,24 +141,40 @@
141
  background: #f8fafc;
142
  border: 1px solid var(--border-subtle);
143
  border-radius: 12px;
144
- padding: 2px;
 
 
 
 
 
 
 
145
  }
146
 
147
  .thresholdWrapper input {
148
  flex: 1;
149
  border: none !important;
150
  background: transparent !important;
151
- padding: 12px 14px;
 
152
  font-size: 14px;
153
  font-weight: 700;
154
- text-align: center;
 
 
 
 
 
 
 
155
  }
156
 
157
  .thresholdSuffix {
158
- padding-right: 14px;
159
  font-size: 9px;
160
  font-weight: 900;
161
  color: var(--text-muted);
 
162
  }
163
 
164
  .logicPreview {
 
141
  background: #f8fafc;
142
  border: 1px solid var(--border-subtle);
143
  border-radius: 12px;
144
+ height: 48px;
145
+ transition: all 0.2s;
146
+ }
147
+
148
+ .thresholdWrapper:focus-within {
149
+ border-color: var(--accent);
150
+ background: white;
151
+ box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
152
  }
153
 
154
  .thresholdWrapper input {
155
  flex: 1;
156
  border: none !important;
157
  background: transparent !important;
158
+ padding: 0 18px;
159
+ height: 100%;
160
  font-size: 14px;
161
  font-weight: 700;
162
+ color: var(--text-main);
163
+ outline: none;
164
+ }
165
+
166
+ .thresholdWrapper input::-webkit-outer-spin-button,
167
+ .thresholdWrapper input::-webkit-inner-spin-button {
168
+ -webkit-appearance: none;
169
+ margin: 0;
170
  }
171
 
172
  .thresholdSuffix {
173
+ padding-right: 18px;
174
  font-size: 9px;
175
  font-weight: 900;
176
  color: var(--text-muted);
177
+ letter-spacing: 0.05em;
178
  }
179
 
180
  .logicPreview {
frontend/apps/internal/src/components/RuleModal.tsx CHANGED
@@ -105,7 +105,7 @@ export const RuleModal: React.FC<RuleModalProps> = ({ rule, onClose, onSave, loa
105
 
106
  <div className={styles.section}>
107
  <div className={styles.sectionHeader}>
108
- <Clock size={14} /> <span>3. THRESHOLD</span>
109
  </div>
110
  <div className={styles.thresholdWrapper}>
111
  <input
@@ -144,7 +144,7 @@ export const RuleModal: React.FC<RuleModalProps> = ({ rule, onClose, onSave, loa
144
  <Terminal size={12} /> LOGIC PREVIEW
145
  </div>
146
  <div className={styles.previewContent}>
147
- IF RESOLUTION &gt; <span>{formData.threshold_minutes} MINS</span> ➔ <strong>{formData.action.replace(/_/g, ' ')}</strong>
148
  </div>
149
  </motion.div>
150
 
 
105
 
106
  <div className={styles.section}>
107
  <div className={styles.sectionHeader}>
108
+ <Clock size={14} /> <span>3. SLA WINDOW</span>
109
  </div>
110
  <div className={styles.thresholdWrapper}>
111
  <input
 
144
  <Terminal size={12} /> LOGIC PREVIEW
145
  </div>
146
  <div className={styles.previewContent}>
147
+ IF AGE &gt; <span>{formData.threshold_minutes} MINS</span> (DEADLINE) ➔ <strong>{formData.action.replace(/_/g, ' ')}</strong>
148
  </div>
149
  </motion.div>
150
 
frontend/packages/shared/src/hooks/useDashboard.ts CHANGED
@@ -297,12 +297,15 @@ export interface Breach {
297
  title: string;
298
  priority: string;
299
  status: string;
 
300
  age_minutes: number;
301
  threshold: number;
302
  is_escalated: boolean;
303
  minutes_remaining: number;
304
  risk_score: number;
 
305
  is_breached: boolean;
 
306
  }
307
 
308
  export interface AuditEntry {
 
297
  title: string;
298
  priority: string;
299
  status: string;
300
+ assigned_name?: string;
301
  age_minutes: number;
302
  threshold: number;
303
  is_escalated: boolean;
304
  minutes_remaining: number;
305
  risk_score: number;
306
+ risk_level: 'NOMINAL' | 'WARNING' | 'CRITICAL' | 'BREACHED';
307
  is_breached: boolean;
308
+ overdue_minutes: number;
309
  }
310
 
311
  export interface AuditEntry {
tasks/system.py CHANGED
@@ -194,7 +194,6 @@ async def monitor_sla_thresholds(ctx, *args, **kwargs):
194
  .where(
195
  Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]),
196
  Ticket.deleted_at.is_(None),
197
- Ticket.is_escalated.is_(None),
198
  EscalationRule.is_active
199
  )
200
  .limit(500)
@@ -202,66 +201,94 @@ async def monitor_sla_thresholds(ctx, *args, **kwargs):
202
  result = await db.execute(stmt)
203
  breached_candidates = result.all()
204
 
205
- manager_cache = {}
206
- ws_ids = list({t.workspace_id for t, r in breached_candidates})
207
 
208
- from agents.utils import get_workspace_manager
209
- manager_lookups = [get_workspace_manager(db, ws_id) for ws_id in ws_ids]
210
- managers = await asyncio.gather(*manager_lookups)
211
- for ws_id, mgr in zip(ws_ids, managers):
212
- manager_cache[ws_id] = mgr
213
-
214
  notification_tasks = []
215
  redis = get_redis_client()
216
 
217
- count = 0
218
  for ticket, rule in breached_candidates:
219
  try:
220
- count += 1
221
  threshold_time = ticket.created_at.replace(tzinfo=None)
222
  age_minutes = (now - threshold_time).total_seconds() / 60
223
- minutes_remaining = rule.threshold_minutes - age_minutes
224
 
225
- manager_user = manager_cache.get(ticket.workspace_id)
 
 
 
226
 
227
- if age_minutes >= rule.threshold_minutes:
228
- if manager_user:
 
 
 
 
 
 
 
 
229
  notification_tasks.append(send_triple_notification(
230
- ctx, manager_user.id, ticket.workspace_id,
231
  "🚨 SLA BREACHED: Immediate Intervention Required",
232
- f"Ticket '{ticket.title}' (Priority: {ticket.priority}) has exceeded its SLA threshold.",
233
  link=f"/dashboard?ticket={ticket.id}"
234
  ))
 
 
235
  ticket.is_escalated = now
236
  db.add(ticket)
237
  await invalidate_cache(f"ticket:detail:{ticket.id}")
238
  db.add(AuditLog(
239
  workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id,
240
- action="SLA_ESCALATION", user_id=None, new_value={"rule": rule.name}
241
  ))
242
 
243
- elif 0 <= minutes_remaining <= 120:
244
- warning_latch = f"notified_sla_pre_breach_2h:{str(ticket.id)}"
245
- if not await redis.get(warning_latch) and manager_user:
246
- notification_tasks.append(send_triple_notification(
247
- ctx, manager_user.id, ticket.workspace_id,
248
- "⚠️ CRITICAL WARNING: SLA Breach in 2 Hours",
249
- f"Ticket '{ticket.title}' is approaching its SLA threshold.",
250
- link=f"/dashboard?ticket={ticket.id}"
 
 
 
 
 
 
 
 
 
251
  ))
252
- await redis.set(warning_latch, "1", ex=86400)
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  db.add(AuditLog(
254
  workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id,
255
- action="SLA_PRE_BREACH_WARNING", user_id=None, new_value={"rule": rule.name}
256
  ))
 
257
  except Exception as e:
258
- logger.error(f"SLA Monitor error: {e}")
259
 
260
- if count % 50 == 0:
 
261
  await db.commit()
262
- if notification_tasks:
263
- await asyncio.gather(*notification_tasks, return_exceptions=True)
264
- notification_tasks = []
265
 
266
  await db.commit()
267
  if notification_tasks:
 
194
  .where(
195
  Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]),
196
  Ticket.deleted_at.is_(None),
 
197
  EscalationRule.is_active
198
  )
199
  .limit(500)
 
201
  result = await db.execute(stmt)
202
  breached_candidates = result.all()
203
 
204
+ from agents.utils import get_available_agents
205
+ from models.user import UserRole
206
 
 
 
 
 
 
 
207
  notification_tasks = []
208
  redis = get_redis_client()
209
 
 
210
  for ticket, rule in breached_candidates:
211
  try:
 
212
  threshold_time = ticket.created_at.replace(tzinfo=None)
213
  age_minutes = (now - threshold_time).total_seconds() / 60
214
+ raw_risk_score = (age_minutes / rule.threshold_minutes) * 100
215
 
216
+ # RECIPIENTS: Always include assignee, plus role-based escalation
217
+ recipients = []
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}"
236
  ))
237
+
238
+ if not ticket.is_escalated:
239
  ticket.is_escalated = now
240
  db.add(ticket)
241
  await invalidate_cache(f"ticket:detail:{ticket.id}")
242
  db.add(AuditLog(
243
  workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id,
244
+ action="SLA_ESCALATION", user_id=None, new_value={"rule": rule.name, "risk": "BREACHED"}
245
  ))
246
 
247
+ # TIER 2: CRITICAL (>85%)
248
+ elif raw_risk_score >= 85:
249
+ latch = f"notified_sla_critical:{str(ticket.id)}"
250
+ if not await redis.get(latch):
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}"
259
+ ))
260
+ await redis.set(latch, "1", ex=86400)
261
+ db.add(AuditLog(
262
+ workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id,
263
+ action="SLA_CRITICAL_WARNING", user_id=None, new_value={"rule": rule.name, "risk": "85%"}
264
  ))
265
+
266
+ # TIER 3: WARNING (>60%)
267
+ elif raw_risk_score >= 60:
268
+ latch = f"notified_sla_warning:{str(ticket.id)}"
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}"
277
+ ))
278
+ await redis.set(latch, "1", ex=86400)
279
  db.add(AuditLog(
280
  workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id,
281
+ action="SLA_WARNING", user_id=None, new_value={"rule": rule.name, "risk": "60%"}
282
  ))
283
+
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
 
293
  await db.commit()
294
  if notification_tasks: