Spaces:
Paused

dushyantsingh0 commited on
Commit
1aa7d27
·
1 Parent(s): e190dbe

backend stabilisation

Browse files
api/v1/dashboard.py CHANGED
@@ -352,11 +352,16 @@ async def get_ai_insights(
352
  from core.cache import get_cached_search, set_cached_search, delete_cached_search
353
 
354
  target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
355
- cache_key = f"dashboard:insights:{target_ws}:{current_user.id}"
 
 
 
 
 
356
 
357
  # --- DEDUPLICATION & STALE-WHILE-REVALIDATE ---
358
- # Check if a background job is already in progress for this workspace
359
- throttle_key = f"job_throttle:generate_workspace_insights:{target_ws}"
360
  job_in_progress = await get_cached_search(throttle_key) is not None
361
 
362
  if not refresh:
@@ -365,7 +370,7 @@ async def get_ai_insights(
365
  return cached_data
366
 
367
  # Even if refreshing, try to serve stale system data as a buffer
368
- system_cache_key = f"dashboard:insights:{target_ws}:system"
369
  system_data = await get_cached_search(system_cache_key)
370
 
371
  if system_data:
@@ -373,7 +378,7 @@ async def get_ai_insights(
373
  if not job_in_progress:
374
  from core.tasks import enqueue_task
375
  try:
376
- await enqueue_task(arq_pool, "generate_workspace_insights", str(target_ws))
377
  except: pass
378
  return system_data
379
 
@@ -381,7 +386,7 @@ async def get_ai_insights(
381
  if not job_in_progress:
382
  from core.tasks import enqueue_task
383
  try:
384
- await enqueue_task(arq_pool, "generate_workspace_insights", str(target_ws))
385
  except Exception as e:
386
  logger.warning(f"Failed to enqueue background insights: {e}")
387
 
 
352
  from core.cache import get_cached_search, set_cached_search, delete_cached_search
353
 
354
  target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
355
+ # Determine view mode
356
+ INTERNAL_ROLES = {UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN}
357
+ is_internal = effective_role in INTERNAL_ROLES
358
+ view_mode = "internal" if is_internal else "customer"
359
+
360
+ cache_key = f"dashboard:insights:{target_ws}:{view_mode}:{current_user.id}"
361
 
362
  # --- DEDUPLICATION & STALE-WHILE-REVALIDATE ---
363
+ # Check if a background job is already in progress for this workspace and role
364
+ throttle_key = f"job_throttle:generate_workspace_insights:{target_ws}:{view_mode}"
365
  job_in_progress = await get_cached_search(throttle_key) is not None
366
 
367
  if not refresh:
 
370
  return cached_data
371
 
372
  # Even if refreshing, try to serve stale system data as a buffer
373
+ system_cache_key = f"dashboard:insights:{target_ws}:{view_mode}"
374
  system_data = await get_cached_search(system_cache_key)
375
 
376
  if system_data:
 
378
  if not job_in_progress:
379
  from core.tasks import enqueue_task
380
  try:
381
+ await enqueue_task(arq_pool, "generate_workspace_insights", str(target_ws), role=view_mode)
382
  except: pass
383
  return system_data
384
 
 
386
  if not job_in_progress:
387
  from core.tasks import enqueue_task
388
  try:
389
+ await enqueue_task(arq_pool, "generate_workspace_insights", str(target_ws), role=view_mode)
390
  except Exception as e:
391
  logger.warning(f"Failed to enqueue background insights: {e}")
392
 
api/v1/reports.py CHANGED
@@ -373,8 +373,14 @@ async def get_ai_service_insights(
373
  import json
374
  redis = get_redis_client()
375
 
376
- cache_key = f"insights:narrative:v4:{target_ws}"
377
- throttle_key = f"job_throttle:generate_workspace_insights:{target_ws}"
 
 
 
 
 
 
378
 
379
  # 1. FAST-PATH: Return cached narrative immediately (if not forcing refresh)
380
  if not refresh:
@@ -393,8 +399,8 @@ async def get_ai_service_insights(
393
  try:
394
  # Set a 60s throttle to prevent spamming regenerations
395
  await redis.setex(throttle_key, 60, "true")
396
- # Note: 'generate_workspace_insights' already handles the full pipeline
397
- await enqueue_task(arq_pool, "generate_workspace_insights", str(target_ws))
398
  except Exception as e:
399
  logger.warning(f"Failed to enqueue report insights: {e}")
400
  await redis.delete(throttle_key)
 
373
  import json
374
  redis = get_redis_client()
375
 
376
+ # Determine if this is an internal or customer view
377
+ # Group roles into two categories: INTERNAL and CUSTOMER
378
+ INTERNAL_ROLES = {"sc_admin", "sc_lead", "sc_agent", "superadmin", "3sc_admin"}
379
+ is_internal = effective_role.lower() in INTERNAL_ROLES
380
+ view_mode = "internal" if is_internal else "customer"
381
+
382
+ cache_key = f"insights:narrative:v4:{target_ws}:{view_mode}"
383
+ throttle_key = f"job_throttle:generate_workspace_insights:{target_ws}:{view_mode}"
384
 
385
  # 1. FAST-PATH: Return cached narrative immediately (if not forcing refresh)
386
  if not refresh:
 
399
  try:
400
  # Set a 60s throttle to prevent spamming regenerations
401
  await redis.setex(throttle_key, 60, "true")
402
+ # Note: 'generate_workspace_insights' now handles role-based narratives
403
+ await enqueue_task(arq_pool, "generate_workspace_insights", str(target_ws), role=view_mode)
404
  except Exception as e:
405
  logger.warning(f"Failed to enqueue report insights: {e}")
406
  await redis.delete(throttle_key)
frontend/apps/internal/src/components/AnalyticsDashboard.module.css CHANGED
@@ -200,39 +200,27 @@
200
 
201
  .narrativeBox {
202
  margin-top: 32px;
203
- background: var(--bg-hover);
204
- padding: 32px;
205
- border-radius: 20px;
206
  border: 1px solid var(--border-subtle);
207
  position: relative;
208
- box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.02);
209
  }
210
 
211
  .narrativeBox::before {
212
- content: '✨';
213
  position: absolute;
214
- top: -12px;
215
  right: 24px;
216
- font-size: 20px;
217
- filter: drop-shadow(0 0 8px var(--primary));
218
- }
219
-
220
- .narrativeBox p {
221
- font-size: 16px;
222
- line-height: 1.8;
223
- color: var(--text-main);
224
- font-weight: 500;
225
- margin-bottom: 20px;
226
- }
227
-
228
- .narrativeBox strong {
229
  color: var(--primary);
230
- background: var(--primary-glow);
231
- padding: 2px 8px;
232
- border-radius: 6px;
233
- font-weight: 700;
234
  }
235
 
 
 
236
  .actionList {
237
  display: flex;
238
  flex-direction: column;
@@ -274,7 +262,7 @@
274
  .actionItem p {
275
  font-size: 13px;
276
  font-weight: 600;
277
- color: #475569;
278
  line-height: 1.5;
279
  margin: 0;
280
  }
@@ -315,14 +303,14 @@
315
  .headerText h3 {
316
  font-size: 14px;
317
  font-weight: 900;
318
- color: #0F172A;
319
  letter-spacing: 0.05em;
320
  margin: 0;
321
  }
322
 
323
  .headerText span {
324
  font-size: 11px;
325
- color: #64748B;
326
  font-weight: 600;
327
  }
328
 
@@ -747,7 +735,7 @@
747
  .tooltipDate {
748
  font-size: 9px;
749
  text-transform: uppercase;
750
- color: #94A3B8;
751
  letter-spacing: 0.08em;
752
  font-weight: 700;
753
  }
 
200
 
201
  .narrativeBox {
202
  margin-top: 32px;
203
+ background: var(--bg-card);
204
+ padding: clamp(24px, 4vw, 40px);
205
+ border-radius: 24px;
206
  border: 1px solid var(--border-subtle);
207
  position: relative;
208
+ box-shadow: inset 0 2px 20px rgba(0, 0, 0, 0.02), 0 10px 30px rgba(0, 0, 0, 0.04);
209
  }
210
 
211
  .narrativeBox::before {
212
+ content: '✦';
213
  position: absolute;
214
+ top: 12px;
215
  right: 24px;
216
+ font-size: 24px;
 
 
 
 
 
 
 
 
 
 
 
 
217
  color: var(--primary);
218
+ opacity: 0.4;
219
+ filter: drop-shadow(0 0 12px var(--primary-glow));
 
 
220
  }
221
 
222
+ /* Narrative inner styles are now handled primarily by NexusMarkdown */
223
+
224
  .actionList {
225
  display: flex;
226
  flex-direction: column;
 
262
  .actionItem p {
263
  font-size: 13px;
264
  font-weight: 600;
265
+ color: var(--text-muted);
266
  line-height: 1.5;
267
  margin: 0;
268
  }
 
303
  .headerText h3 {
304
  font-size: 14px;
305
  font-weight: 900;
306
+ color: var(--text-main);
307
  letter-spacing: 0.05em;
308
  margin: 0;
309
  }
310
 
311
  .headerText span {
312
  font-size: 11px;
313
+ color: var(--text-muted);
314
  font-weight: 600;
315
  }
316
 
 
735
  .tooltipDate {
736
  font-size: 9px;
737
  text-transform: uppercase;
738
+ color: var(--text-muted);
739
  letter-spacing: 0.08em;
740
  font-weight: 700;
741
  }
frontend/packages/shared/src/components/NexusMarkdown.tsx CHANGED
@@ -32,8 +32,10 @@ export const NexusMarkdown: React.FC<NexusMarkdownProps> = ({ content, isMe }) =
32
  return (
33
  <div className="nexus-markdown-content" style={{
34
  fontSize: '16px',
35
- lineHeight: 1.7,
36
- color: isMe ? '#ffffff' : 'var(--text-main)'
 
 
37
  }}>
38
  <ReactMarkdown
39
  remarkPlugins={[remarkGfm]}
@@ -168,14 +170,14 @@ export const NexusMarkdown: React.FC<NexusMarkdownProps> = ({ content, isMe }) =
168
  );
169
  },
170
  // Paragraph & List Density
171
- p: ({ children }) => <p style={{ margin: '0 0 12px 0', color: 'inherit', wordBreak: 'break-word', fontSize: '16px', lineHeight: 1.7 }}>{children}</p>,
172
  ul: ({ children }) => <ul style={{ margin: '24px 0', paddingLeft: '32px', listStyleType: 'disc' }}>{children}</ul>,
173
  ol: ({ children }) => <ol style={{ margin: '24px 0', paddingLeft: '32px', listStyleType: 'decimal' }}>{children}</ol>,
174
  li: ({ children }) => <li style={{ marginBottom: '14px', color: 'inherit', paddingLeft: '8px' }}>{children}</li>,
175
  // Headings
176
- h1: ({ children }) => <h1 style={{ fontSize: '32px', fontWeight: 900, margin: '48px 0 24px 0', color: isMe ? '#ffffff' : 'var(--text-main)', letterSpacing: '-0.03em', lineHeight: 1.2 }}>{children}</h1>,
177
- h2: ({ children }) => <h2 style={{ fontSize: '26px', fontWeight: 800, margin: '40px 0 20px 0', color: isMe ? '#ffffff' : 'var(--text-main)', letterSpacing: '-0.02em', lineHeight: 1.3 }}>{children}</h2>,
178
- h3: ({ children }) => <h3 style={{ fontSize: '20px', fontWeight: 800, margin: '32px 0 16px 0', color: isMe ? '#ffffff' : 'var(--text-main)', letterSpacing: '-0.01em' }}>{children}</h3>,
179
  // Custom Mention / Link Decorator
180
  a: ({ href, children, ...props }) => {
181
  const isMention = href?.startsWith('mention:');
 
32
  return (
33
  <div className="nexus-markdown-content" style={{
34
  fontSize: '16px',
35
+ lineHeight: 1.8,
36
+ fontFamily: 'var(--font-sans)',
37
+ color: isMe ? '#ffffff' : 'var(--text-main)',
38
+ letterSpacing: '-0.01em'
39
  }}>
40
  <ReactMarkdown
41
  remarkPlugins={[remarkGfm]}
 
170
  );
171
  },
172
  // Paragraph & List Density
173
+ p: ({ children }) => <p style={{ margin: '0 0 16px 0', color: 'inherit', wordBreak: 'break-word', fontSize: '16px', lineHeight: 1.8 }}>{children}</p>,
174
  ul: ({ children }) => <ul style={{ margin: '24px 0', paddingLeft: '32px', listStyleType: 'disc' }}>{children}</ul>,
175
  ol: ({ children }) => <ol style={{ margin: '24px 0', paddingLeft: '32px', listStyleType: 'decimal' }}>{children}</ol>,
176
  li: ({ children }) => <li style={{ marginBottom: '14px', color: 'inherit', paddingLeft: '8px' }}>{children}</li>,
177
  // Headings
178
+ h1: ({ children }) => <h1 style={{ fontSize: '32px', fontWeight: 900, margin: '48px 0 24px 0', color: isMe ? '#ffffff' : 'var(--text-main)', letterSpacing: '-0.03em', lineHeight: 1.2, fontFamily: 'var(--font-heading)' }}>{children}</h1>,
179
+ h2: ({ children }) => <h2 style={{ fontSize: '26px', fontWeight: 800, margin: '40px 0 20px 0', color: isMe ? '#ffffff' : 'var(--text-main)', letterSpacing: '-0.02em', lineHeight: 1.3, fontFamily: 'var(--font-heading)' }}>{children}</h2>,
180
+ h3: ({ children }) => <h3 style={{ fontSize: '20px', fontWeight: 800, margin: '32px 0 16px 0', color: isMe ? '#ffffff' : 'var(--text-main)', letterSpacing: '-0.01em', fontFamily: 'var(--font-heading)' }}>{children}</h3>,
181
  // Custom Mention / Link Decorator
182
  a: ({ href, children, ...props }) => {
183
  const isMention = href?.startsWith('mention:');
frontend/packages/shared/src/components/RichEditor.tsx CHANGED
@@ -122,13 +122,14 @@ export const RichEditor: React.FC<RichEditorProps> = ({ value, onChange, placeho
122
 
123
  // Find the @ and the query
124
  const textBefore = text.slice(0, range.startOffset);
125
- const match = textBefore.match(/@(\w*)$/);
 
126
  if (!match) return;
127
 
128
  const startPos = match.index!;
129
 
130
- // Create the styled mention badge
131
- const badgeHtml = `<span class="mention-badge" data-id="${user.id}" data-name="${user.full_name}">@${user.full_name}</span>&nbsp;`;
132
 
133
  // Select the @query text to replace it
134
  range.setStart(node, startPos);
@@ -139,35 +140,49 @@ export const RichEditor: React.FC<RichEditorProps> = ({ value, onChange, placeho
139
  const div = document.createElement('div');
140
  div.innerHTML = badgeHtml;
141
  const frag = document.createDocumentFragment();
142
- let lastNode;
143
- while (lastNode = div.firstChild) {
144
- frag.appendChild(lastNode);
 
 
145
  }
146
  range.insertNode(frag);
147
 
148
- // Move cursor after the mention
149
- range.setStartAfter(lastNode!);
150
- range.collapse(true);
151
- selection.removeAllRanges();
152
- selection.addRange(range);
 
 
153
 
154
  closeMentions();
155
- handleInput();
 
 
 
 
156
  };
157
 
158
  const handlePaste = async (e: React.ClipboardEvent) => {
159
  const items = e.clipboardData.items;
160
- let imageItem = null;
 
 
 
161
  for (let i = 0; i < items.length; i++) {
162
  if (items[i].type.indexOf("image") !== -1) {
163
- imageItem = items[i];
 
164
  break;
165
  }
166
  }
167
 
168
- if (imageItem) {
169
- e.preventDefault();
170
- const file = imageItem.getAsFile();
 
 
171
  if (file) {
172
  const formData = new FormData();
173
  formData.append("file", file);
@@ -211,7 +226,7 @@ export const RichEditor: React.FC<RichEditorProps> = ({ value, onChange, placeho
211
  return (
212
  <div className="glass-card" style={{
213
  borderRadius: 24,
214
- overflow: 'hidden',
215
  border: '1.5px solid var(--border-subtle)',
216
  background: 'var(--bg-dark)',
217
  display: 'flex',
@@ -388,10 +403,11 @@ export const RichEditor: React.FC<RichEditorProps> = ({ value, onChange, placeho
388
  font-weight: 800;
389
  display: inline-block;
390
  border: 1px solid var(--primary);
391
- box-shadow: var(--shadow-sm);
392
  user-select: none;
393
  cursor: default;
394
  margin: 0 2px;
 
395
  }
396
  `}</style>
397
  </div>
 
122
 
123
  // Find the @ and the query
124
  const textBefore = text.slice(0, range.startOffset);
125
+ // Support non-word characters in match but stop at @
126
+ const match = textBefore.match(/@([^\s@]*)$/);
127
  if (!match) return;
128
 
129
  const startPos = match.index!;
130
 
131
+ // Create the styled mention badge - contentEditable="false" is KEY to prevent "dirty" text editing inside the badge
132
+ const badgeHtml = `<span class="mention-badge" contenteditable="false" data-id="${user.id}" data-name="${user.full_name}">@${user.full_name}</span>&nbsp;`;
133
 
134
  // Select the @query text to replace it
135
  range.setStart(node, startPos);
 
140
  const div = document.createElement('div');
141
  div.innerHTML = badgeHtml;
142
  const frag = document.createDocumentFragment();
143
+ let firstNode = div.firstChild;
144
+ let lastNode = div.lastChild;
145
+
146
+ while (div.firstChild) {
147
+ frag.appendChild(div.firstChild);
148
  }
149
  range.insertNode(frag);
150
 
151
+ // Move cursor after the &nbsp;
152
+ if (lastNode) {
153
+ range.setStartAfter(lastNode);
154
+ range.collapse(true);
155
+ selection.removeAllRanges();
156
+ selection.addRange(range);
157
+ }
158
 
159
  closeMentions();
160
+ // Trigger update
161
+ setTimeout(() => {
162
+ handleInput();
163
+ editorRef.current?.focus();
164
+ }, 0);
165
  };
166
 
167
  const handlePaste = async (e: React.ClipboardEvent) => {
168
  const items = e.clipboardData.items;
169
+ let hasImage = false;
170
+
171
+ // Check for images first and prevent default IMMEDIATELY if found
172
+ // This prevents the browser from doing a default paste of the image while we upload it.
173
  for (let i = 0; i < items.length; i++) {
174
  if (items[i].type.indexOf("image") !== -1) {
175
+ hasImage = true;
176
+ e.preventDefault();
177
  break;
178
  }
179
  }
180
 
181
+ if (hasImage) {
182
+ // Find the first image item to upload
183
+ const imageItem = Array.from(items).find(item => item.type.indexOf("image") !== -1);
184
+ const file = imageItem?.getAsFile();
185
+
186
  if (file) {
187
  const formData = new FormData();
188
  formData.append("file", file);
 
226
  return (
227
  <div className="glass-card" style={{
228
  borderRadius: 24,
229
+ // Removed overflow: hidden to prevent clipping the MentionOverlay
230
  border: '1.5px solid var(--border-subtle)',
231
  background: 'var(--bg-dark)',
232
  display: 'flex',
 
403
  font-weight: 800;
404
  display: inline-block;
405
  border: 1px solid var(--primary);
406
+ box-shadow: 0 2px 8px var(--primary-glow);
407
  user-select: none;
408
  cursor: default;
409
  margin: 0 2px;
410
+ vertical-align: baseline;
411
  }
412
  `}</style>
413
  </div>
frontend/packages/shared/src/hooks/useMentions.ts CHANGED
@@ -44,7 +44,7 @@ export const useMentions = ({ mentionableUsers: initialUsers }: UseMentionsProps
44
 
45
  const handleInputChange = (text: string, position: number, targetId: string | null = null) => {
46
  const textBeforeCursor = text.slice(0, position);
47
- const mentionMatch = textBeforeCursor.match(/@(\w*)$/);
48
 
49
  if (mentionMatch) {
50
  setShowMentionList(true);
 
44
 
45
  const handleInputChange = (text: string, position: number, targetId: string | null = null) => {
46
  const textBeforeCursor = text.slice(0, position);
47
+ const mentionMatch = textBeforeCursor.match(/@([^\s@]*)$/);
48
 
49
  if (mentionMatch) {
50
  setShowMentionList(true);
tasks/ai.py CHANGED
@@ -331,7 +331,7 @@ async def refresh_active_workspace_insights(ctx, **kwargs):
331
  for ws_id in active_ws_ids:
332
  await enqueue_task(ctx.get("redis") if isinstance(ctx, dict) else None, "generate_workspace_insights", str(ws_id))
333
 
334
- async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
335
  """
336
  Generate background AI insights for a workspace.
337
  Uses direct DB queries — does NOT import from the API layer to avoid circular dependencies.
@@ -355,7 +355,7 @@ async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
355
  count_rows = (await db.execute(count_stmt)).all()
356
  total_tickets = sum(r.cnt for r in count_rows)
357
 
358
- # 2. SLA breach count (open tickets past their expected resolution time)
359
  now = datetime.utcnow()
360
  breach_stmt = select(sqlfunc.count(Ticket.id)).where(
361
  Ticket.workspace_id == ws_uuid,
@@ -372,21 +372,23 @@ async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
372
  ))
373
  avg_csat = round(float((await db.execute(csat_stmt)).scalar() or 0), 2)
374
 
375
- # 4. Personnel load — top 5 agents by open ticket count
376
- load_stmt = (
377
- select(User.full_name, sqlfunc.count(Ticket.id).label("cnt"))
378
- .join(Ticket, Ticket.assigned_to == User.id)
379
- .where(
380
- Ticket.workspace_id == ws_uuid,
381
- Ticket.deleted_at.is_(None),
382
- Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED])
 
 
 
 
 
 
383
  )
384
- .group_by(User.full_name)
385
- .order_by(sqlfunc.count(Ticket.id).desc())
386
- .limit(5)
387
- )
388
- load_rows = (await db.execute(load_stmt)).all()
389
- load_str = ", ".join([f"{r.full_name} ({r.cnt})" for r in load_rows]) or "No current assignments"
390
 
391
  # 5. Sample of 10 most recent tickets
392
  sample_stmt = (
@@ -400,24 +402,32 @@ async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
400
 
401
  # 6. LLM analysis
402
  llm = get_llm(timeout=300)
 
 
 
 
 
 
 
 
403
  prompt = f"""
404
- You are the Nexus Workspace Strategy Engine.
405
- Analyze the following workspace telemetry and provide a high-fidelity operational directive.
406
 
407
  TELEMETRY:
408
  - Active Tickets: {total_tickets}
409
  - SLA Breached: {breach_count}
410
  - User CSAT: {avg_csat}/5.0
411
- - Personnel Load: {load_str}
412
 
413
  TICKET SAMPLE:
414
  {sample}
415
 
416
  Respond strictly in JSON format:
417
  {{
418
- "summary": "2 sentences. One on overall health, one on primary bottleneck.",
419
- "actions": ["Specific Actionable Directive 1", "Specific Actionable Directive 2", "Specific Actionable Directive 3"],
420
- "markdown_narrative": "A premium high-fidelity Markdown report. Use headers (##) for 'Strategic Health' and 'Operational Bottlenecks'. ENSURE double newlines before every header and between paragraphs. Include a '### Risk Analysis' section. Professional, executive tone. Mention specific ticket volume or SLA metrics where appropriate.",
421
  "metric_insights": {{
422
  "intensity": "...",
423
  "velocity": "...",
@@ -429,23 +439,25 @@ async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
429
  resp = await llm.ainvoke(prompt)
430
  json_str = str(resp.content).strip().replace("```json", "").replace("```", "")
431
 
432
- # Clean control characters (like literal newlines inside strings) that break json.loads
433
  import re
434
- json_str = re.sub(r'[\x00-\x1F\x7F]', '', json_str)
435
 
436
  insights = json.loads(json_str)
437
 
438
- # 7. Dual Caching (Dashboard + Reports)
439
- # Structured JSON for the tactical dashboard
440
- await set_cached_search(f"dashboard:insights:{workspace_id}:system", insights, ttl=43200)
441
 
442
- # Markdown narrative for the high-fidelity reports/analytics page
 
 
 
 
443
  narrative = {
444
- "insights": insights.get("markdown_narrative") or f"## Strategic Health\n\n{insights.get('summary')}\n\n## Operational Bottlenecks\n\n**Key Actions:**\n" + "\n".join([f"- {a}" for a in insights.get("actions", [])]),
445
  "generated_at": datetime.utcnow().isoformat(),
446
  "status": "COMPLETED"
447
  }
448
- await set_cached_search(f"insights:narrative:v4:{workspace_id}", narrative, ttl=43200)
449
 
450
  # 8. Real-time Synchronization
451
  # Broadcast to all connected clients in this workspace to trigger auto-refresh
 
331
  for ws_id in active_ws_ids:
332
  await enqueue_task(ctx.get("redis") if isinstance(ctx, dict) else None, "generate_workspace_insights", str(ws_id))
333
 
334
+ async def generate_workspace_insights(ctx, workspace_id: str, role: str = "internal", **kwargs):
335
  """
336
  Generate background AI insights for a workspace.
337
  Uses direct DB queries — does NOT import from the API layer to avoid circular dependencies.
 
355
  count_rows = (await db.execute(count_stmt)).all()
356
  total_tickets = sum(r.cnt for r in count_rows)
357
 
358
+ # 2. SLA breach count
359
  now = datetime.utcnow()
360
  breach_stmt = select(sqlfunc.count(Ticket.id)).where(
361
  Ticket.workspace_id == ws_uuid,
 
372
  ))
373
  avg_csat = round(float((await db.execute(csat_stmt)).scalar() or 0), 2)
374
 
375
+ # 4. Personnel load (Internal Only)
376
+ load_str = ""
377
+ if role == "internal":
378
+ load_stmt = (
379
+ select(User.full_name, sqlfunc.count(Ticket.id).label("cnt"))
380
+ .join(Ticket, Ticket.assigned_to == User.id)
381
+ .where(
382
+ Ticket.workspace_id == ws_uuid,
383
+ Ticket.deleted_at.is_(None),
384
+ Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED])
385
+ )
386
+ .group_by(User.full_name)
387
+ .order_by(sqlfunc.count(Ticket.id).desc())
388
+ .limit(5)
389
  )
390
+ load_rows = (await db.execute(load_stmt)).all()
391
+ load_str = ", ".join([f"{r.full_name} ({r.cnt})" for r in load_rows]) or "No current assignments"
 
 
 
 
392
 
393
  # 5. Sample of 10 most recent tickets
394
  sample_stmt = (
 
402
 
403
  # 6. LLM analysis
404
  llm = get_llm(timeout=300)
405
+
406
+ if role == "internal":
407
+ role_guidance = "You are the Internal Operations Strategist. Focus on operational efficiency, tactical throughput, and resource optimization. Mention specific agents or bottlenecks where appropriate."
408
+ header1, header2 = "Strategic Health", "Operational Bottlenecks"
409
+ else:
410
+ role_guidance = "You are the Customer Success Strategist. Focus on service delivery health, satisfaction trends, and strategic value. NEVER mention internal agent names. Focus on outcomes and SLA adherence from the customer perspective."
411
+ header1, header2 = "Service Delivery Health", "Strategic Support Value"
412
+
413
  prompt = f"""
414
+ {role_guidance}
415
+ Analyze the following workspace telemetry for a {role} stakeholder.
416
 
417
  TELEMETRY:
418
  - Active Tickets: {total_tickets}
419
  - SLA Breached: {breach_count}
420
  - User CSAT: {avg_csat}/5.0
421
+ {f'- Personnel Load: {load_str}' if role == 'internal' else ''}
422
 
423
  TICKET SAMPLE:
424
  {sample}
425
 
426
  Respond strictly in JSON format:
427
  {{
428
+ "summary": "2 sentences. One on overall health, one on primary observation from a {role} perspective.",
429
+ "actions": ["Directive 1", "Directive 2", "Directive 3"],
430
+ "markdown_narrative": "A premium high-fidelity Markdown report. Use headers (## ) for '{header1}' and '{header2}'. ENSURE a space after the hashes. EACH HEADER MUST BE ON ITS OWN LINE with double newlines (\\\\n\\\\n) BEFORE AND AFTER. Professional, executive tone.",
431
  "metric_insights": {{
432
  "intensity": "...",
433
  "velocity": "...",
 
439
  resp = await llm.ainvoke(prompt)
440
  json_str = str(resp.content).strip().replace("```json", "").replace("```", "")
441
 
 
442
  import re
443
+ json_str = re.sub(r'[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]', '', json_str)
444
 
445
  insights = json.loads(json_str)
446
 
447
+ # 7. Role-Specific Caching
448
+ await set_cached_search(f"dashboard:insights:{workspace_id}:{role}", insights, ttl=43200)
 
449
 
450
+ # Ensure markdown_narrative has good defaults if LLM output is weird
451
+ raw_narrative = insights.get("markdown_narrative")
452
+ if not raw_narrative or len(raw_narrative) < 50:
453
+ raw_narrative = f"## {header1}\\n\\n{insights.get('summary')}\\n\\n## {header2}\\n\\n**Key Actions:**\\n\\n" + "\\n".join([f"- {a}" for a in insights.get("actions", [])])
454
+
455
  narrative = {
456
+ "insights": raw_narrative,
457
  "generated_at": datetime.utcnow().isoformat(),
458
  "status": "COMPLETED"
459
  }
460
+ await set_cached_search(f"insights:narrative:v4:{workspace_id}:{role}", narrative, ttl=43200)
461
 
462
  # 8. Real-time Synchronization
463
  # Broadcast to all connected clients in this workspace to trigger auto-refresh