Spaces:
Paused

dushyantsingh0 commited on
Commit
7b2ff9f
·
1 Parent(s): 8a37e38

backend stabilization

Browse files
api/v1/dashboard.py CHANGED
@@ -287,6 +287,7 @@ async def get_agent_queue(
287
  search_query: Optional[str] = None,
288
  creator_query: Optional[str] = None,
289
  ticket_id_filter: Optional[str] = None,
 
290
  limit: int = 500,
291
  refresh: bool = False,
292
  current_user: User = Depends(get_current_user),
@@ -309,7 +310,7 @@ async def get_agent_queue(
309
 
310
  target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
311
 
312
- cache_params = f"{status_filter}:{priority_filter}:{search_query}:{creator_query}:{ticket_id_filter}"
313
  cache_key = f"dashboard:queue:{portal}:{role_class}:{target_ws}:{current_user.id}:{cache_params}"
314
 
315
  if refresh:
@@ -329,7 +330,8 @@ async def get_agent_queue(
329
  priority_filter=priority_filter,
330
  search_query=search_query,
331
  creator_query=creator_query,
332
- ticket_id_filter=ticket_id_filter
 
333
  )
334
 
335
  res_data = res["items"]
 
287
  search_query: Optional[str] = None,
288
  creator_query: Optional[str] = None,
289
  ticket_id_filter: Optional[str] = None,
290
+ sort_by: str = "created_at",
291
  limit: int = 500,
292
  refresh: bool = False,
293
  current_user: User = Depends(get_current_user),
 
310
 
311
  target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
312
 
313
+ cache_params = f"{status_filter}:{priority_filter}:{search_query}:{creator_query}:{ticket_id_filter}:{sort_by}"
314
  cache_key = f"dashboard:queue:{portal}:{role_class}:{target_ws}:{current_user.id}:{cache_params}"
315
 
316
  if refresh:
 
330
  priority_filter=priority_filter,
331
  search_query=search_query,
332
  creator_query=creator_query,
333
+ ticket_id_filter=ticket_id_filter,
334
+ sort_by=sort_by
335
  )
336
 
337
  res_data = res["items"]
frontend/apps/customer/src/components/TicketList.tsx CHANGED
@@ -37,7 +37,7 @@ export const TicketList: React.FC<TicketListProps> = ({ setActive, setSelectedTi
37
  const [statusFilter, setStatusFilter] = useState("ALL");
38
  const [priorityFilter, setPriorityFilter] = useState("ALL");
39
  const [categoryFilter] = useState("ALL");
40
- const [sortBy, setSortBy] = useState<"created_at" | "updated_at" | "resolved_at">("created_at");
41
  const [displayMode, setDisplayMode] = useState<"TABLE" | "KANBAN">("TABLE");
42
  const [ticketIdFilter, setTicketIdFilter] = useState("");
43
 
@@ -374,7 +374,7 @@ export const TicketList: React.FC<TicketListProps> = ({ setActive, setSelectedTi
374
  <td style={{ padding: "24px" }}><PriorityBadge priority={t.priority} /></td>
375
  <td style={{ padding: "24px" }}><StatusBadge status={t.status} /></td>
376
  <td style={{ padding: "24px", fontSize: 12, fontWeight: 700, color: COLORS.gray400 }}>
377
- {new Date(t.updated_at).toLocaleDateString()}
378
  </td>
379
  </motion.tr>
380
  ))}
@@ -589,3 +589,16 @@ const filterInputStyle: React.CSSProperties = {
589
  const filterIconStyle: React.CSSProperties = {
590
  position: "absolute", left: 16, top: "50%", transform: "translateY(-50%)", color: COLORS.primary, opacity: 0.6
591
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  const [statusFilter, setStatusFilter] = useState("ALL");
38
  const [priorityFilter, setPriorityFilter] = useState("ALL");
39
  const [categoryFilter] = useState("ALL");
40
+ const [sortBy, setSortBy] = useState<"created_at" | "updated_at" | "resolved_at">("updated_at");
41
  const [displayMode, setDisplayMode] = useState<"TABLE" | "KANBAN">("TABLE");
42
  const [ticketIdFilter, setTicketIdFilter] = useState("");
43
 
 
374
  <td style={{ padding: "24px" }}><PriorityBadge priority={t.priority} /></td>
375
  <td style={{ padding: "24px" }}><StatusBadge status={t.status} /></td>
376
  <td style={{ padding: "24px", fontSize: 12, fontWeight: 700, color: COLORS.gray400 }}>
377
+ {formatRelativeTime(t.updated_at)}
378
  </td>
379
  </motion.tr>
380
  ))}
 
589
  const filterIconStyle: React.CSSProperties = {
590
  position: "absolute", left: 16, top: "50%", transform: "translateY(-50%)", color: COLORS.primary, opacity: 0.6
591
  };
592
+
593
+ const formatRelativeTime = (dateStr: string) => {
594
+ const date = new Date(dateStr);
595
+ const now = new Date();
596
+ const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
597
+
598
+ if (diffInSeconds < 60) return 'JUST NOW';
599
+ if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}M AGO`;
600
+ if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}H AGO`;
601
+ if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)}D AGO`;
602
+
603
+ return date.toLocaleDateString();
604
+ };
frontend/apps/internal/src/components/TicketBoard.tsx CHANGED
@@ -33,6 +33,11 @@ const OWNERSHIP_OPTIONS = [
33
  { id: 'my', label: 'My Tickets' },
34
  ];
35
 
 
 
 
 
 
36
  interface TicketBoardProps {
37
  workspaceId?: string;
38
  onSelect: (t: any) => void;
@@ -47,6 +52,7 @@ export const TicketBoard: React.FC<TicketBoardProps> = ({ workspaceId, onSelect
47
  year: 'All',
48
  month: 'All',
49
  ownership: 'all',
 
50
  search: ''
51
  });
52
  const [searchValue, setSearchValue] = useState('');
@@ -59,8 +65,9 @@ export const TicketBoard: React.FC<TicketBoardProps> = ({ workspaceId, onSelect
59
  priority_filter: filters.priority === 'All' ? undefined : filters.priority,
60
  search_query: isIdSearch ? undefined : filters.search || undefined,
61
  ticket_id_filter: isIdSearch ? filters.search : undefined,
 
62
  };
63
- }, [filters.status, filters.priority, filters.search]);
64
 
65
  const { tickets, loading, refresh } = useAgentQueue(workspaceId, agentQueueParams);
66
  const { users } = useUsers(workspaceId);
@@ -159,6 +166,13 @@ export const TicketBoard: React.FC<TicketBoardProps> = ({ workspaceId, onSelect
159
  </div>
160
 
161
  <div className={styles.filtersTier}>
 
 
 
 
 
 
 
162
  <Dropdown
163
  label="Ownership"
164
  options={OWNERSHIP_OPTIONS}
 
33
  { id: 'my', label: 'My Tickets' },
34
  ];
35
 
36
+ const SEQUENCE_OPTIONS = [
37
+ { id: 'updated_at', label: 'Recency' },
38
+ { id: 'created_at', label: 'Inception' },
39
+ ];
40
+
41
  interface TicketBoardProps {
42
  workspaceId?: string;
43
  onSelect: (t: any) => void;
 
52
  year: 'All',
53
  month: 'All',
54
  ownership: 'all',
55
+ sort_by: 'updated_at',
56
  search: ''
57
  });
58
  const [searchValue, setSearchValue] = useState('');
 
65
  priority_filter: filters.priority === 'All' ? undefined : filters.priority,
66
  search_query: isIdSearch ? undefined : filters.search || undefined,
67
  ticket_id_filter: isIdSearch ? filters.search : undefined,
68
+ sort_by: filters.sort_by
69
  };
70
+ }, [filters.status, filters.priority, filters.search, filters.sort_by]);
71
 
72
  const { tickets, loading, refresh } = useAgentQueue(workspaceId, agentQueueParams);
73
  const { users } = useUsers(workspaceId);
 
166
  </div>
167
 
168
  <div className={styles.filtersTier}>
169
+ <Dropdown
170
+ label="Sequence"
171
+ options={SEQUENCE_OPTIONS}
172
+ value={filters.sort_by}
173
+ onChange={(v) => setFilters(prev => ({ ...prev, sort_by: v }))}
174
+ width="120px"
175
+ />
176
  <Dropdown
177
  label="Ownership"
178
  options={OWNERSHIP_OPTIONS}
frontend/packages/shared/src/hooks/useTickets.ts CHANGED
@@ -142,11 +142,12 @@ export const useAgentQueue = (
142
  search_query?: string;
143
  creator_query?: string;
144
  ticket_id_filter?: string;
 
145
  } = {}
146
  ) => {
147
  // Destructure to primitives so useCallback gets stable references and does not
148
  // create a new function (and trigger infinite re-fetches) on every render.
149
- const { status_filter, priority_filter, search_query, creator_query, ticket_id_filter } = params;
150
 
151
  const wsKey = workspaceId || 'default';
152
  const [localQueue, setLocalQueue] = useState<Ticket[]>(globalQueueMap[wsKey] || []);
@@ -170,7 +171,7 @@ export const useAgentQueue = (
170
  const fetchQueue = useCallback(async (force: boolean = false) => {
171
  const lastFetch = lastQueueFetchMap[wsKey] || 0;
172
  const isStale = Date.now() - lastFetch > STALE_WINDOW;
173
- const hasFilters = !!(status_filter || priority_filter || search_query || creator_query || ticket_id_filter);
174
 
175
  // Bypass cache when filters are active or a forced refresh was requested
176
  if (!force && !hasFilters && (globalQueueMap[wsKey] || []).length > 0 && !isStale) return;
@@ -190,6 +191,7 @@ export const useAgentQueue = (
190
  if (search_query) queryParams.append('search_query', search_query);
191
  if (creator_query) queryParams.append('creator_query', creator_query);
192
  if (ticket_id_filter) queryParams.append('ticket_id_filter', ticket_id_filter);
 
193
  if (force) queryParams.append('refresh', 'true');
194
 
195
  const qs = queryParams.toString();
@@ -208,7 +210,7 @@ export const useAgentQueue = (
208
  }
209
  // Only primitive values in deps — no object references that would cause
210
  // a new useCallback identity on every render.
211
- }, [wsKey, workspaceId, status_filter, priority_filter, search_query, creator_query, ticket_id_filter]);
212
 
213
  const { token } = useAuth();
214
 
 
142
  search_query?: string;
143
  creator_query?: string;
144
  ticket_id_filter?: string;
145
+ sort_by?: string;
146
  } = {}
147
  ) => {
148
  // Destructure to primitives so useCallback gets stable references and does not
149
  // create a new function (and trigger infinite re-fetches) on every render.
150
+ const { status_filter, priority_filter, search_query, creator_query, ticket_id_filter, sort_by } = params;
151
 
152
  const wsKey = workspaceId || 'default';
153
  const [localQueue, setLocalQueue] = useState<Ticket[]>(globalQueueMap[wsKey] || []);
 
171
  const fetchQueue = useCallback(async (force: boolean = false) => {
172
  const lastFetch = lastQueueFetchMap[wsKey] || 0;
173
  const isStale = Date.now() - lastFetch > STALE_WINDOW;
174
+ const hasFilters = !!(status_filter || priority_filter || search_query || creator_query || ticket_id_filter || sort_by);
175
 
176
  // Bypass cache when filters are active or a forced refresh was requested
177
  if (!force && !hasFilters && (globalQueueMap[wsKey] || []).length > 0 && !isStale) return;
 
191
  if (search_query) queryParams.append('search_query', search_query);
192
  if (creator_query) queryParams.append('creator_query', creator_query);
193
  if (ticket_id_filter) queryParams.append('ticket_id_filter', ticket_id_filter);
194
+ if (sort_by) queryParams.append('sort_by', sort_by);
195
  if (force) queryParams.append('refresh', 'true');
196
 
197
  const qs = queryParams.toString();
 
210
  }
211
  // Only primitive values in deps — no object references that would cause
212
  // a new useCallback identity on every render.
213
+ }, [wsKey, workspaceId, status_filter, priority_filter, search_query, creator_query, ticket_id_filter, sort_by]);
214
 
215
  const { token } = useAuth();
216
 
tasks/stories.py CHANGED
@@ -42,28 +42,89 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
42
  })
43
 
44
  try:
45
- # 2. Gather data for the story
46
- from sqlalchemy import func
 
 
47
 
48
- # Aggregate status distribution
 
 
49
  status_stmt = select(Ticket.status, func.count(Ticket.id)).where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)).group_by(Ticket.status)
50
- status_res = await db.execute(status_stmt)
51
- status_map = {str(row[0].value if hasattr(row[0], 'value') else row[0]): row[1] for row in status_res.all()}
52
 
53
- # Get priority distribution
54
  prio_stmt = select(Ticket.priority, func.count(Ticket.id)).where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)).group_by(Ticket.priority)
55
  prio_map = {str(row[0].value if hasattr(row[0], 'value') else row[0]): row[1] for row in (await db.execute(prio_stmt)).all()}
56
 
57
- ticket_stmt = select(Ticket).where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)).order_by(Ticket.created_at.desc()).limit(15)
58
- res = await db.execute(ticket_stmt)
59
- tickets = res.scalars().all()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  context_data = {
62
- "total_active_tickets": sum(status_map.values()),
63
- "status_distribution": status_map,
64
- "priority_distribution": prio_map,
 
 
 
 
 
 
 
 
65
  "recent_tickets": [
66
- {"id": str(t.id)[:8], "title": t.title, "status": t.status.value, "priority": t.priority.value}
67
  for t in tickets
68
  ],
69
  "role": role,
@@ -81,29 +142,41 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
81
  file_type = story_obj.file_type or "pdf"
82
 
83
  # 3. Structured LLM Narrative Generation
84
- role_flavor = "strategic alignment and executive oversight" if role in ["customer_admin", "3sc_admin"] else "operational efficiency and tactical throughput"
 
85
 
86
  prompt = f"""
87
- You are the Nexus Enterprise Strategist. Generate a high-level workspace narrative for a {role}.
88
 
89
  Focus: {role_flavor}.
90
  User Specific Goals: {custom_spec or "Standard workspace health overview."}
91
 
92
- Data Context:
93
  {json.dumps(context_data, indent=2)}
94
 
95
- Output strictly as a JSON object with the following structure. Do not include any other text, markdown blocks, or commentary.
96
 
 
97
  {{
98
- "title": "Title for the report",
99
- "executive_summary": "2-3 paragraphs of high-level analysis",
100
- "key_achievements": ["Achievement 1", "Achievement 2", ...],
101
- "critical_risks": ["Risk 1", "Risk 2", ...],
102
- "strategic_roadmap": ["Initiative 1", "Initiative 2", ...],
103
- "analytical_insight": "A sentence interpreting the status/priority distribution charts."
 
 
 
 
 
 
 
 
 
 
104
  }}
105
 
106
- Ensure the tone is professional, forensic, and objective. Avoid fluff.
107
  """
108
 
109
  llm = get_llm(is_heavy_task=True)
@@ -127,9 +200,10 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
127
  logger.warning(f"LLM failed to return valid JSON: {json_err}. Raw: {content[:200]}...")
128
  report_data = {
129
  "title": "Workspace Health Report",
130
- "executive_summary": content[:1000],
131
- "key_achievements": ["Data synthesis completed."],
132
- "critical_risks": ["Manual parsing engaged."],
 
133
  "strategic_roadmap": ["Verify JSON pipeline."],
134
  "analytical_insight": "Automated insight generation pending."
135
  }
@@ -193,8 +267,9 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
193
  })
194
 
195
  def generate_enterprise_pdf(report, context):
196
- """Generates a multi-page PDF with charts, tables, and professional formatting."""
197
  from fpdf import FPDF
 
198
 
199
  class EnterprisePDF(FPDF):
200
  def header(self):
@@ -213,15 +288,26 @@ def generate_enterprise_pdf(report, context):
213
  self.set_text_color(*TEXT_MUTED)
214
  self.cell(0, 10, f"Page {self.page_no()} | Generated by Nexus AI Orchestrator", align="C")
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  pdf = EnterprisePDF()
217
  pdf.set_auto_page_break(auto=True, margin=15)
218
 
219
- # PAGE 1: TITLE PAGE
220
  pdf.add_page()
221
  pdf.set_fill_color(*BG_LIGHT)
222
  pdf.rect(0, 0, 210, 297, "F")
223
-
224
- # Decorative bar
225
  pdf.set_fill_color(*BRAND_PURPLE)
226
  pdf.rect(0, 0, 10, 297, "F")
227
 
@@ -233,7 +319,7 @@ def generate_enterprise_pdf(report, context):
233
  pdf.set_xy(25, 110)
234
  pdf.set_font("helvetica", "", 14)
235
  pdf.set_text_color(*TEXT_MAIN)
236
- pdf.cell(0, 10, f"WORKSPACE STRATEGIC NARRATIVE")
237
  pdf.ln(10)
238
  pdf.set_font("helvetica", "B", 12)
239
  pdf.cell(0, 10, f"RECIPIENT: {context['role'].replace('_', ' ').upper()}")
@@ -245,11 +331,24 @@ def generate_enterprise_pdf(report, context):
245
  pdf.ln(6)
246
  pdf.cell(0, 10, "STRICTLY CONFIDENTIAL | NEXUS INTERNAL USE ONLY")
247
 
248
- # PAGE 2: EXECUTIVE SUMMARY & ANALYTICS
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  pdf.add_page()
250
  pdf.set_font("helvetica", "B", 18)
251
  pdf.set_text_color(*BRAND_PURPLE)
252
- pdf.cell(0, 10, "EXECUTIVE SUMMARY")
253
  pdf.ln(15)
254
 
255
  pdf.set_font("helvetica", "", 11)
@@ -257,101 +356,97 @@ def generate_enterprise_pdf(report, context):
257
  pdf.multi_cell(0, 6, report['executive_summary'])
258
  pdf.ln(10)
259
 
260
- # STATUS BAR CHART (Manual Drawing)
261
  pdf.set_font("helvetica", "B", 14)
262
- pdf.cell(0, 10, "TICKET DISTRIBUTION BY STATUS")
263
- pdf.ln(12)
264
-
265
- statuses = context['status_distribution']
266
- max_val = max(statuses.values()) if statuses else 1
267
- chart_y = pdf.get_y()
268
- bar_width = 30
269
- spacing = 5
270
- chart_height = 40
271
 
272
- x_start = 20
273
- for i, (label, count) in enumerate(statuses.items()):
274
- # Draw Bar
275
- h = (count / max_val) * chart_height
276
- pdf.set_fill_color(*BRAND_PURPLE)
277
- pdf.rect(x_start + (i * (bar_width + spacing)), chart_y + (chart_height - h), bar_width, h, "F")
278
-
279
- # Label
280
- pdf.set_xy(x_start + (i * (bar_width + spacing)), chart_y + chart_height + 2)
281
- pdf.set_font("helvetica", "B", 8)
282
- pdf.set_text_color(*TEXT_MUTED)
283
- pdf.cell(bar_width, 5, label[:12], align="C")
284
-
285
- # Count
286
- pdf.set_xy(x_start + (i * (bar_width + spacing)), chart_y + (chart_height - h) - 5)
287
- pdf.cell(bar_width, 5, str(count), align="C")
288
-
289
- pdf.set_y(chart_y + chart_height + 15)
290
  pdf.set_font("helvetica", "I", 10)
291
- pdf.set_text_color(*TEXT_MAIN)
292
- pdf.multi_cell(0, 5, report['analytical_insight'])
293
- pdf.ln(10)
294
 
295
- # PAGE 3: ACHIEVEMENTS & RISKS
296
  pdf.add_page()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
 
298
- # Achievements Box
299
- pdf.set_fill_color(240, 253, 244) # Very light green
300
- pdf.rect(10, 20, 190, 80, "F")
301
- pdf.set_xy(15, 25)
302
  pdf.set_font("helvetica", "B", 14)
303
- pdf.set_text_color(*BRAND_GREEN)
304
- pdf.cell(0, 10, "KEY ACHIEVEMENTS")
305
- pdf.ln(10)
306
- pdf.set_font("helvetica", "", 11)
307
  pdf.set_text_color(*TEXT_MAIN)
308
- for ach in report['key_achievements']:
309
- pdf.set_x(20)
310
- pdf.cell(5, 7, "-", 0, 0)
311
- pdf.multi_cell(0, 7, ach)
312
-
313
- # Risks Box
314
- pdf.set_fill_color(254, 242, 242) # Very light red
315
- pdf.rect(10, 110, 190, 80, "F")
316
- pdf.set_xy(15, 115)
317
- pdf.set_font("helvetica", "B", 14)
318
- pdf.set_text_color((220, 38, 38))
319
- pdf.cell(0, 10, "CRITICAL RISKS & BOTTLENECKS")
320
  pdf.ln(10)
321
- pdf.set_font("helvetica", "", 11)
322
- pdf.set_text_color(*TEXT_MAIN)
323
- for risk in report['critical_risks']:
324
- pdf.set_x(20)
325
- pdf.cell(5, 7, "!", 0, 0)
326
- pdf.multi_cell(0, 7, risk)
327
-
328
- # PAGE 4: STRATEGIC ROADMAP & DATA TABLE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  pdf.add_page()
330
- pdf.set_font("helvetica", "B", 16)
331
  pdf.set_text_color(*BRAND_PURPLE)
332
- pdf.cell(0, 10, "FORWARD STRATEGIC ROADMAP")
333
- pdf.ln(12)
334
 
335
- pdf.set_font("helvetica", "", 11)
336
- pdf.set_text_color(*TEXT_MAIN)
337
- for i, item in enumerate(report['strategic_roadmap']):
338
- pdf.set_fill_color(*BG_LIGHT)
339
  pdf.set_font("helvetica", "B", 11)
340
- pdf.cell(0, 10, f"INITIATIVE {i+1}: {item}", 1, 1, "L", fill=True)
341
- pdf.ln(2)
 
 
 
342
 
343
- pdf.ln(10)
344
- pdf.set_font("helvetica", "B", 14)
345
- pdf.cell(0, 10, "RECENT SIGNALS AUDIT")
346
- pdf.ln(12)
 
 
347
 
348
- # Signals Table
349
- from fpdf.fonts import FontFace
350
  with pdf.table(
351
  borders_layout="HORIZONTAL_LINES",
352
  cell_fill_color=(250, 250, 250),
353
  cell_fill_mode="ROWS",
354
- line_height=8,
355
  text_align=("LEFT", "LEFT", "CENTER", "CENTER"),
356
  width=190
357
  ) as table:
@@ -370,8 +465,70 @@ def generate_enterprise_pdf(report, context):
370
 
371
  return pdf.output(dest='S')
372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  def generate_enterprise_pptx(report, context):
374
- """Generates a professional PowerPoint deck with production-grade layouts."""
375
  from pptx import Presentation
376
  from pptx.util import Inches, Pt
377
  from pptx.enum.text import PP_ALIGN
@@ -379,25 +536,23 @@ def generate_enterprise_pptx(report, context):
379
  from pptx.enum.shapes import MSO_SHAPE
380
 
381
  prs = Presentation()
382
- # Set to 16:9 widescreen
383
  prs.slide_width = Inches(13.333)
384
  prs.slide_height = Inches(7.5)
385
 
386
  def add_branded_slide(title_text):
387
- slide = prs.slides.add_slide(prs.slide_layouts[5]) # Blank with title
388
- # Background light gray
389
  background = slide.background
390
- fill = background.fill
391
- fill.solid()
392
- fill.foreground_color.rgb = RGBColor(250, 250, 252)
393
 
394
- # Header Bar
395
  rect = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, prs.slide_width, Inches(0.8))
396
  rect.fill.solid()
397
  rect.fill.foreground_color.rgb = RGBColor(*BRAND_PURPLE)
398
  rect.line.fill.background()
399
 
400
- # Title text
401
  title_shape = slide.shapes.title
402
  title_shape.text = title_text.upper()
403
  title_shape.left = Inches(0.5)
@@ -412,27 +567,17 @@ def generate_enterprise_pptx(report, context):
412
  p.font.color.rgb = RGBColor(255, 255, 255)
413
  p.alignment = PP_ALIGN.LEFT
414
 
415
- # Footer watermark
416
- footer = slide.shapes.add_textbox(Inches(0.5), prs.slide_height - Inches(0.5), Inches(4), Inches(0.4))
417
- fp = footer.text_frame.paragraphs[0]
418
- fp.text = "NEXUS STRATEGIC AUDIT | CONFIDENTIAL"
419
- fp.font.size = Pt(9)
420
- fp.font.color.rgb = RGBColor(*TEXT_MUTED)
421
-
422
  return slide
423
 
424
- # SLIDE 1: TITLE (Custom Layout)
425
- slide = prs.slides.add_slide(prs.slide_layouts[6]) # Blank
426
- # Full height purple accent
427
  accent = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, Inches(4), prs.slide_height)
428
  accent.fill.solid()
429
  accent.fill.foreground_color.rgb = RGBColor(*BRAND_PURPLE)
430
  accent.line.fill.background()
431
 
432
- # Title Box
433
  title_box = slide.shapes.add_textbox(Inches(4.5), Inches(2.5), Inches(8), Inches(2))
434
  tf = title_box.text_frame
435
- tf.word_wrap = True
436
  p = tf.add_paragraph()
437
  p.text = report['title'].upper()
438
  p.font.size = Pt(48)
@@ -445,7 +590,7 @@ def generate_enterprise_pptx(report, context):
445
  subtitle_p.font.color.rgb = RGBColor(*TEXT_MUTED)
446
  subtitle_p.space_before = Pt(20)
447
 
448
- # SLIDE 2: EXECUTIVE SUMMARY
449
  slide = add_branded_slide("EXECUTIVE SUMMARY")
450
  body_box = slide.shapes.add_textbox(Inches(1), Inches(1.5), Inches(11), Inches(5))
451
  tf = body_box.text_frame
@@ -456,120 +601,106 @@ def generate_enterprise_pptx(report, context):
456
  p.font.color.rgb = RGBColor(*TEXT_MAIN)
457
  p.line_spacing = 1.2
458
 
459
- # SLIDE 3: TICKET ANALYTICS
460
- slide = add_branded_slide("ECOSYSTEM ANALYTICS")
461
 
462
- # Status Table
463
- statuses = context['status_distribution']
464
- rows, cols = len(statuses) + 1, 2
465
- table_shape = slide.shapes.add_table(rows, cols, Inches(1), Inches(2), Inches(5), Inches(4))
466
- table = table_shape.table
467
 
468
- # Header styling
469
- table.cell(0, 0).text = "WORKFLOW STATUS"
470
- table.cell(0, 1).text = "TOTAL"
471
- for c in range(2):
472
- cell = table.cell(0, c)
473
- cell.fill.solid()
474
- cell.fill.foreground_color.rgb = RGBColor(*BRAND_PURPLE)
475
- p = cell.text_frame.paragraphs[0]
476
- p.font.bold = True
477
- p.font.color.rgb = RGBColor(255, 255, 255)
478
 
479
- for i, (k, v) in enumerate(statuses.items()):
480
- table.cell(i+1, 0).text = k.upper()
481
- table.cell(i+1, 1).text = str(v)
482
- table.cell(i+1, 1).text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
483
-
484
- # Insight Column
485
- txBox = slide.shapes.add_textbox(Inches(7), Inches(2), Inches(5), Inches(4))
486
- tf = txBox.text_frame
487
- tf.word_wrap = True
488
- p = tf.add_paragraph()
489
- p.text = "STRATEGIC INSIGHT"
490
- p.font.bold = True
491
- p.font.size = Pt(14)
492
- p.font.color.rgb = RGBColor(*BRAND_PURPLE)
493
-
494
- p2 = tf.add_paragraph()
495
- p2.text = report['analytical_insight']
496
- p2.font.size = Pt(20)
497
- p2.font.italic = True
498
- p2.font.color.rgb = RGBColor(*TEXT_MAIN)
499
- p2.space_before = Pt(15)
500
-
501
- # SLIDE 4: OUTCOMES (Achievements & Risks)
502
- slide = add_branded_slide("STRATEGIC OUTCOMES")
503
 
504
- # Left: Achievements
505
- slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Inches(0.5), Inches(1.5), Inches(6), Inches(0.4)).fill.solid()
506
- slide.shapes[-1].fill.foreground_color.rgb = RGBColor(*BRAND_GREEN)
507
- slide.shapes[-1].line.fill.background()
508
- ach_title = slide.shapes.add_textbox(Inches(0.5), Inches(1.5), Inches(6), Inches(0.4))
509
- ach_p = ach_title.text_frame.paragraphs[0]
510
- ach_p.text = "KEY ACHIEVEMENTS"
511
- ach_p.font.bold = True
512
- ach_p.font.color.rgb = RGBColor(255, 255, 255)
513
- ach_p.alignment = PP_ALIGN.CENTER
514
-
515
- ach_list = slide.shapes.add_textbox(Inches(0.5), Inches(2.1), Inches(6), Inches(4))
516
- tf = ach_list.text_frame
517
- for ach in report['key_achievements']:
518
- p = tf.add_paragraph()
519
- p.text = ach
520
- p.font.size = Pt(14)
521
- p.bullet = True
522
- p.space_after = Pt(10)
523
-
524
- # Right: Risks
525
- slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Inches(6.8), Inches(1.5), Inches(6), Inches(0.4)).fill.solid()
526
- slide.shapes[-1].fill.foreground_color.rgb = RGBColor(220, 38, 38)
527
- slide.shapes[-1].line.fill.background()
528
- risk_title = slide.shapes.add_textbox(Inches(6.8), Inches(1.5), Inches(6), Inches(0.4))
529
- risk_p = risk_title.text_frame.paragraphs[0]
530
- risk_p.text = "CRITICAL RISKS"
531
- risk_p.font.bold = True
532
- risk_p.font.color.rgb = RGBColor(255, 255, 255)
533
- risk_p.alignment = PP_ALIGN.CENTER
534
-
535
- risk_list = slide.shapes.add_textbox(Inches(6.8), Inches(2.1), Inches(6), Inches(4))
536
- tf = risk_list.text_frame
537
- for risk in report['critical_risks']:
 
538
  p = tf.add_paragraph()
539
- p.text = risk
540
- p.font.size = Pt(14)
541
- p.bullet = True
542
- p.space_after = Pt(10)
543
-
544
- # SLIDE 5: ROADMAP (Visualized as Phases)
545
- slide = add_branded_slide("FUTURE ROADMAP")
546
-
547
- phases = report['strategic_roadmap']
548
- width = (prs.slide_width - Inches(2)) / len(phases) if phases else 1
549
-
550
- for i, phase in enumerate(phases):
551
- left = Inches(1) + (i * width)
552
- # Phase Header
553
- box = slide.shapes.add_shape(MSO_SHAPE.CHEVRON, left, Inches(2), width - Inches(0.2), Inches(1))
554
- box.fill.solid()
555
- box.fill.foreground_color.rgb = RGBColor(*BRAND_PURPLE)
556
- box.line.fill.background()
557
 
558
- p_txt = slide.shapes.add_textbox(left, Inches(2.2), width - Inches(0.2), Inches(0.6))
559
- tp = p_txt.text_frame.paragraphs[0]
560
- tp.text = f"PHASE {i+1}"
561
- tp.font.bold = True
562
- tp.font.color.rgb = RGBColor(255, 255, 255)
563
- tp.alignment = PP_ALIGN.CENTER
 
564
 
565
- # Content
566
- c_box = slide.shapes.add_textbox(left, Inches(3.2), width - Inches(0.2), Inches(3))
567
- ctf = c_box.text_frame
568
- ctf.word_wrap = True
569
- cp = ctf.paragraphs[0]
570
- cp.text = phase
571
- cp.font.size = Pt(14)
572
- cp.alignment = PP_ALIGN.CENTER
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
 
574
  pptx_io = io.BytesIO()
575
  prs.save(pptx_io)
 
42
  })
43
 
44
  try:
45
+ # 2. Gather data for the story (30-Day Lookback)
46
+ from sqlalchemy import func, case
47
+ from datetime import timedelta
48
+ from models.feedback import Feedback
49
 
50
+ thirty_days_ago = datetime.utcnow() - timedelta(days=30)
51
+
52
+ # 2.1 Snapshot Aggregates
53
  status_stmt = select(Ticket.status, func.count(Ticket.id)).where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)).group_by(Ticket.status)
54
+ status_map = {str(row[0].value if hasattr(row[0], 'value') else row[0]): row[1] for row in (await db.execute(status_stmt)).all()}
 
55
 
 
56
  prio_stmt = select(Ticket.priority, func.count(Ticket.id)).where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)).group_by(Ticket.priority)
57
  prio_map = {str(row[0].value if hasattr(row[0], 'value') else row[0]): row[1] for row in (await db.execute(prio_stmt)).all()}
58
 
59
+ # 2.2 Trend Aggregates (30 Days)
60
+ # Velocity: Tickets created per day
61
+ velocity_stmt = select(
62
+ func.date_trunc('day', Ticket.created_at).label('day'),
63
+ func.count(Ticket.id)
64
+ ).where(
65
+ Ticket.workspace_id == workspace_id,
66
+ Ticket.created_at >= thirty_days_ago,
67
+ Ticket.deleted_at.is_(None)
68
+ ).group_by('day').order_by('day')
69
+ velocity_data = {row[0].strftime('%Y-%m-%d'): row[1] for row in (await db.execute(velocity_stmt)).all()}
70
+
71
+ # CSAT Trend: Average rating per day
72
+ csat_stmt = select(
73
+ func.date_trunc('day', Feedback.created_at).label('day'),
74
+ func.avg(Feedback.rating)
75
+ ).where(
76
+ Feedback.workspace_id == workspace_id,
77
+ Feedback.created_at >= thirty_days_ago
78
+ ).group_by('day').order_by('day')
79
+ csat_data = {row[0].strftime('%Y-%m-%d'): round(float(row[1]), 2) for row in (await db.execute(csat_stmt)).all()}
80
+
81
+ # Resolution Performance: Average resolution time (hours) per day (based on resolution date)
82
+ res_perf_stmt = select(
83
+ func.date_trunc('day', Ticket.resolved_at).label('day'),
84
+ func.avg(func.extract('epoch', Ticket.resolved_at - Ticket.created_at) / 3600.0)
85
+ ).where(
86
+ Ticket.workspace_id == workspace_id,
87
+ Ticket.resolved_at >= thirty_days_ago,
88
+ Ticket.deleted_at.is_(None)
89
+ ).group_by('day').order_by('day')
90
+ res_perf_data = {row[0].strftime('%Y-%m-%d'): round(float(row[1]), 2) for row in (await db.execute(res_perf_stmt)).all()}
91
+
92
+ # Priority Distribution Trend (Creation volume per priority per day)
93
+ prio_trend_stmt = select(
94
+ func.date_trunc('day', Ticket.created_at).label('day'),
95
+ Ticket.priority,
96
+ func.count(Ticket.id)
97
+ ).where(
98
+ Ticket.workspace_id == workspace_id,
99
+ Ticket.created_at >= thirty_days_ago,
100
+ Ticket.deleted_at.is_(None)
101
+ ).group_by('day', Ticket.priority).order_by('day')
102
+
103
+ prio_trend_raw = (await db.execute(prio_trend_stmt)).all()
104
+ prio_trend_data = {}
105
+ for day_dt, prio, count in prio_trend_raw:
106
+ day_str = day_dt.strftime('%Y-%m-%d')
107
+ if day_str not in prio_trend_data:
108
+ prio_trend_data[day_str] = {}
109
+ prio_trend_data[day_str][prio.value] = count
110
+
111
+ ticket_stmt = select(Ticket).where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)).order_by(Ticket.created_at.desc()).limit(20)
112
+ tickets = (await db.execute(ticket_stmt)).scalars().all()
113
 
114
  context_data = {
115
+ "snapshot": {
116
+ "total_active_tickets": sum(status_map.values()),
117
+ "status_distribution": status_map,
118
+ "priority_distribution": prio_map,
119
+ },
120
+ "trends_30d": {
121
+ "velocity": velocity_data,
122
+ "csat": csat_data,
123
+ "resolution_hours": res_perf_data,
124
+ "priority_shift": prio_trend_data
125
+ },
126
  "recent_tickets": [
127
+ {"id": str(t.id)[:8], "title": t.title, "status": t.status.value, "priority": t.priority.value, "created_at": t.created_at.isoformat()}
128
  for t in tickets
129
  ],
130
  "role": role,
 
142
  file_type = story_obj.file_type or "pdf"
143
 
144
  # 3. Structured LLM Narrative Generation
145
+ is_internal = role in ["3sc_admin", "superadmin", "sc_admin", "sc_lead", "sc_agent"]
146
+ role_flavor = "operational efficiency, tactical throughput, and resource optimization" if is_internal else "strategic alignment, service excellence, and relationship health"
147
 
148
  prompt = f"""
149
+ You are the Nexus Enterprise Strategist. Generate a high-level, forensic workspace narrative for a {role}.
150
 
151
  Focus: {role_flavor}.
152
  User Specific Goals: {custom_spec or "Standard workspace health overview."}
153
 
154
+ Data Context (30-Day Telemetry):
155
  {json.dumps(context_data, indent=2)}
156
 
157
+ Output strictly as a JSON object. Do not include preamble or markdown.
158
 
159
+ Structure:
160
  {{
161
+ "title": "Professional Report Title",
162
+ "executive_summary": "2-3 paragraphs of high-level forensic analysis based on the 30-day trends.",
163
+ "sections": [
164
+ {{
165
+ "title": "Section Title (e.g. Service Reliability / Operational Throughput)",
166
+ "content": "Deep dive analysis interpreting the velocity and SLA data.",
167
+ "highlights": ["Data-backed highlight 1", "..."]
168
+ }},
169
+ {{
170
+ "title": "Section Title (e.g. Customer Satisfaction / Resource Allocation)",
171
+ "content": "Analysis of CSAT trends or Priority Pressure.",
172
+ "highlights": ["..."]
173
+ }}
174
+ ],
175
+ "strategic_roadmap": ["Strategic Initiative 1", "..."],
176
+ "analytical_insight": "A single, powerful sentence interpreting the core trend shift seen in the 30-day window."
177
  }}
178
 
179
+ Tone: Professional, objective, and data-driven. Avoid generic praise.
180
  """
181
 
182
  llm = get_llm(is_heavy_task=True)
 
200
  logger.warning(f"LLM failed to return valid JSON: {json_err}. Raw: {content[:200]}...")
201
  report_data = {
202
  "title": "Workspace Health Report",
203
+ "executive_summary": "System generated summary due to parsing failure.",
204
+ "sections": [
205
+ {"title": "Operational Overview", "content": "Recent telemetry synthesis completed.", "highlights": ["Data collection successful."]}
206
+ ],
207
  "strategic_roadmap": ["Verify JSON pipeline."],
208
  "analytical_insight": "Automated insight generation pending."
209
  }
 
267
  })
268
 
269
  def generate_enterprise_pdf(report, context):
270
+ """Generates a professional, production-grade PDF with TOC, trends, and role-based depth."""
271
  from fpdf import FPDF
272
+ from fpdf.fonts import FontFace
273
 
274
  class EnterprisePDF(FPDF):
275
  def header(self):
 
288
  self.set_text_color(*TEXT_MUTED)
289
  self.cell(0, 10, f"Page {self.page_no()} | Generated by Nexus AI Orchestrator", align="C")
290
 
291
+ def add_toc(self, items):
292
+ self.add_page()
293
+ self.set_font("helvetica", "B", 24)
294
+ self.set_text_color(*BRAND_PURPLE)
295
+ self.cell(0, 20, "TABLE OF CONTENTS", ln=1)
296
+ self.ln(10)
297
+ self.set_font("helvetica", "B", 12)
298
+ self.set_text_color(*TEXT_MAIN)
299
+ for title, page in items:
300
+ self.cell(170, 10, title, border="B")
301
+ self.cell(20, 10, str(page), border="B", align="R")
302
+ self.ln(12)
303
+
304
  pdf = EnterprisePDF()
305
  pdf.set_auto_page_break(auto=True, margin=15)
306
 
307
+ # 1. TITLE PAGE
308
  pdf.add_page()
309
  pdf.set_fill_color(*BG_LIGHT)
310
  pdf.rect(0, 0, 210, 297, "F")
 
 
311
  pdf.set_fill_color(*BRAND_PURPLE)
312
  pdf.rect(0, 0, 10, 297, "F")
313
 
 
319
  pdf.set_xy(25, 110)
320
  pdf.set_font("helvetica", "", 14)
321
  pdf.set_text_color(*TEXT_MAIN)
322
+ pdf.cell(0, 10, "WORKSPACE STRATEGIC NARRATIVE")
323
  pdf.ln(10)
324
  pdf.set_font("helvetica", "B", 12)
325
  pdf.cell(0, 10, f"RECIPIENT: {context['role'].replace('_', ' ').upper()}")
 
331
  pdf.ln(6)
332
  pdf.cell(0, 10, "STRICTLY CONFIDENTIAL | NEXUS INTERNAL USE ONLY")
333
 
334
+ # 2. TABLE OF CONTENTS
335
+ toc_items = [
336
+ ("Executive Summary", 3),
337
+ ("Historical Trend Analysis", 4),
338
+ ("Priority & Resource Allocation", 5),
339
+ ]
340
+ for i, section in enumerate(report.get("sections", [])):
341
+ toc_items.append((section['title'], 6 + i))
342
+ toc_items.append(("Strategic Roadmap", 6 + len(report.get("sections", []))))
343
+ toc_items.append(("Recent Signals Audit", 7 + len(report.get("sections", []))))
344
+
345
+ pdf.add_toc(toc_items)
346
+
347
+ # 3. EXECUTIVE SUMMARY
348
  pdf.add_page()
349
  pdf.set_font("helvetica", "B", 18)
350
  pdf.set_text_color(*BRAND_PURPLE)
351
+ pdf.cell(0, 10, "1. EXECUTIVE SUMMARY")
352
  pdf.ln(15)
353
 
354
  pdf.set_font("helvetica", "", 11)
 
356
  pdf.multi_cell(0, 6, report['executive_summary'])
357
  pdf.ln(10)
358
 
359
+ # Snapshot Distribution
360
  pdf.set_font("helvetica", "B", 14)
361
+ pdf.cell(0, 10, "Current Status Distribution")
362
+ pdf.ln(10)
363
+ _draw_bar_chart(pdf, context['snapshot']['status_distribution'], 20, pdf.get_y(), 170, 40, "Tickets by Status")
 
 
 
 
 
 
364
 
365
+ pdf.set_y(pdf.get_y() + 60)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  pdf.set_font("helvetica", "I", 10)
367
+ pdf.multi_cell(0, 5, report.get('analytical_insight', ""))
 
 
368
 
369
+ # 4. TREND ANALYSIS (30 Days)
370
  pdf.add_page()
371
+ pdf.set_font("helvetica", "B", 18)
372
+ pdf.set_text_color(*BRAND_PURPLE)
373
+ pdf.cell(0, 10, "2. HISTORICAL TREND ANALYSIS (30 DAYS)")
374
+ pdf.ln(15)
375
+
376
+ # Velocity Chart
377
+ _draw_line_chart(pdf, context['trends_30d']['velocity'], 20, pdf.get_y() + 5, 170, 40, "Ticket Velocity (Daily Volume)")
378
+
379
+ # CSAT or SLA Chart
380
+ pdf.set_y(pdf.get_y() + 65)
381
+ if context['trends_30d']['csat']:
382
+ _draw_line_chart(pdf, context['trends_30d']['csat'], 20, pdf.get_y() + 5, 170, 40, "CSAT Trend (Avg Rating)", color=BRAND_GREEN)
383
+ else:
384
+ _draw_line_chart(pdf, context['trends_30d']['resolution_hours'], 20, pdf.get_y() + 5, 170, 40, "Resolution Performance (Avg Hours)", color=BRAND_AMBER)
385
+
386
+ # 5. PRIORITY EVOLUTION
387
+ pdf.add_page()
388
+ pdf.set_font("helvetica", "B", 18)
389
+ pdf.set_text_color(*BRAND_PURPLE)
390
+ pdf.cell(0, 10, "3. PRIORITY & RESOURCE ALLOCATION")
391
+ pdf.ln(15)
392
 
 
 
 
 
393
  pdf.set_font("helvetica", "B", 14)
 
 
 
 
394
  pdf.set_text_color(*TEXT_MAIN)
395
+ pdf.cell(0, 10, "Priority Snapshot")
 
 
 
 
 
 
 
 
 
 
 
396
  pdf.ln(10)
397
+ _draw_bar_chart(pdf, context['snapshot']['priority_distribution'], 20, pdf.get_y(), 170, 40, "Current Priority Volume", color=BRAND_AMBER)
398
+
399
+ # 6. ROLE-SPECIFIC SECTIONS
400
+ for i, section in enumerate(report.get("sections", [])):
401
+ pdf.add_page()
402
+ pdf.set_font("helvetica", "B", 18)
403
+ pdf.set_text_color(*BRAND_PURPLE)
404
+ pdf.cell(0, 10, f"{4+i}. {section['title'].upper()}")
405
+ pdf.ln(15)
406
+
407
+ pdf.set_font("helvetica", "", 11)
408
+ pdf.set_text_color(*TEXT_MAIN)
409
+ pdf.multi_cell(0, 6, section['content'])
410
+ pdf.ln(10)
411
+
412
+ pdf.set_fill_color(*BG_LIGHT)
413
+ pdf.set_font("helvetica", "B", 10)
414
+ pdf.cell(0, 10, "KEY TAKEAWAYS", ln=1, fill=True)
415
+ pdf.set_font("helvetica", "", 10)
416
+ for highlight in section.get("highlights", []):
417
+ pdf.cell(10, 8, ">", align="C")
418
+ pdf.multi_cell(0, 8, highlight)
419
+ pdf.ln(2)
420
+
421
+ # 7. STRATEGIC ROADMAP
422
  pdf.add_page()
423
+ pdf.set_font("helvetica", "B", 18)
424
  pdf.set_text_color(*BRAND_PURPLE)
425
+ pdf.cell(0, 10, f"{4+len(report.get('sections', []))}. STRATEGIC ROADMAP")
426
+ pdf.ln(15)
427
 
428
+ for i, item in enumerate(report.get('strategic_roadmap', [])):
429
+ pdf.set_fill_color(*BRAND_PURPLE)
430
+ pdf.set_text_color(255, 255, 255)
 
431
  pdf.set_font("helvetica", "B", 11)
432
+ pdf.cell(30, 12, f"INITIATIVE {i+1}", fill=True, align="C")
433
+ pdf.set_fill_color(*BG_LIGHT)
434
+ pdf.set_text_color(*TEXT_MAIN)
435
+ pdf.cell(160, 12, f" {item}", fill=True)
436
+ pdf.ln(15)
437
 
438
+ # 8. SIGNALS AUDIT
439
+ pdf.add_page()
440
+ pdf.set_font("helvetica", "B", 18)
441
+ pdf.set_text_color(*BRAND_PURPLE)
442
+ pdf.cell(0, 10, f"{5+len(report.get('sections', []))}. RECENT SIGNALS AUDIT")
443
+ pdf.ln(15)
444
 
 
 
445
  with pdf.table(
446
  borders_layout="HORIZONTAL_LINES",
447
  cell_fill_color=(250, 250, 250),
448
  cell_fill_mode="ROWS",
449
+ line_height=10,
450
  text_align=("LEFT", "LEFT", "CENTER", "CENTER"),
451
  width=190
452
  ) as table:
 
465
 
466
  return pdf.output(dest='S')
467
 
468
+ def _draw_bar_chart(pdf, data, x, y, width, height, title, color=BRAND_PURPLE):
469
+ pdf.set_font("helvetica", "B", 10)
470
+ pdf.set_text_color(*TEXT_MAIN)
471
+ pdf.set_xy(x, y - 5)
472
+ pdf.cell(width, 5, title, align="C")
473
+
474
+ if not data: return
475
+
476
+ max_val = max(data.values()) if data.values() else 1
477
+ bar_width = width / (len(data) * 1.5)
478
+ spacing = bar_width * 0.5
479
+
480
+ for i, (label, count) in enumerate(data.items()):
481
+ h = (count / max_val) * height
482
+ pdf.set_fill_color(*color)
483
+ pdf.rect(x + (i * (bar_width + spacing)), y + height - h, bar_width, h, "F")
484
+
485
+ pdf.set_xy(x + (i * (bar_width + spacing)), y + height + 2)
486
+ pdf.set_font("helvetica", "B", 7)
487
+ pdf.set_text_color(*TEXT_MUTED)
488
+ pdf.cell(bar_width, 4, label[:10], align="C")
489
+
490
+ pdf.set_xy(x + (i * (bar_width + spacing)), y + height - h - 5)
491
+ pdf.cell(bar_width, 4, str(count), align="C")
492
+
493
+ def _draw_line_chart(pdf, data, x, y, width, height, title, color=BRAND_PURPLE):
494
+ pdf.set_font("helvetica", "B", 10)
495
+ pdf.set_text_color(*TEXT_MAIN)
496
+ pdf.set_xy(x, y - 5)
497
+ pdf.cell(width, 5, title, align="C")
498
+
499
+ # Axes
500
+ pdf.set_draw_color(220, 220, 220)
501
+ pdf.line(x, y, x, y + height)
502
+ pdf.line(x, y + height, x + width, y + height)
503
+
504
+ if not data:
505
+ pdf.set_xy(x, y + height / 2)
506
+ pdf.cell(width, 10, "INSUFFICIENT DATA POINTS", align="C")
507
+ return
508
+
509
+ points = list(data.values())
510
+ max_val = max(points) if points else 1
511
+ if max_val == 0: max_val = 1
512
+
513
+ x_step = width / (len(points) - 1) if len(points) > 1 else width
514
+
515
+ pdf.set_draw_color(*color)
516
+ pdf.set_line_width(0.6)
517
+
518
+ prev_x, prev_y = None, None
519
+ for i, val in enumerate(points):
520
+ px = x + (i * x_step)
521
+ py = y + height - (val / max_val * height)
522
+
523
+ if prev_x is not None:
524
+ pdf.line(prev_x, prev_y, px, py)
525
+
526
+ pdf.set_fill_color(*color)
527
+ pdf.circle(px, py, 0.8, "F")
528
+ prev_x, prev_y = px, py
529
+
530
  def generate_enterprise_pptx(report, context):
531
+ """Generates a professional, executive PowerPoint deck with trend deep-dives."""
532
  from pptx import Presentation
533
  from pptx.util import Inches, Pt
534
  from pptx.enum.text import PP_ALIGN
 
536
  from pptx.enum.shapes import MSO_SHAPE
537
 
538
  prs = Presentation()
539
+ # 16:9 widescreen
540
  prs.slide_width = Inches(13.333)
541
  prs.slide_height = Inches(7.5)
542
 
543
  def add_branded_slide(title_text):
544
+ slide = prs.slides.add_slide(prs.slide_layouts[5])
 
545
  background = slide.background
546
+ background.fill.solid()
547
+ background.fill.foreground_color.rgb = RGBColor(250, 250, 252)
 
548
 
549
+ # Header bar
550
  rect = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, prs.slide_width, Inches(0.8))
551
  rect.fill.solid()
552
  rect.fill.foreground_color.rgb = RGBColor(*BRAND_PURPLE)
553
  rect.line.fill.background()
554
 
555
+ # Title
556
  title_shape = slide.shapes.title
557
  title_shape.text = title_text.upper()
558
  title_shape.left = Inches(0.5)
 
567
  p.font.color.rgb = RGBColor(255, 255, 255)
568
  p.alignment = PP_ALIGN.LEFT
569
 
 
 
 
 
 
 
 
570
  return slide
571
 
572
+ # 1. TITLE SLIDE
573
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
 
574
  accent = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, Inches(4), prs.slide_height)
575
  accent.fill.solid()
576
  accent.fill.foreground_color.rgb = RGBColor(*BRAND_PURPLE)
577
  accent.line.fill.background()
578
 
 
579
  title_box = slide.shapes.add_textbox(Inches(4.5), Inches(2.5), Inches(8), Inches(2))
580
  tf = title_box.text_frame
 
581
  p = tf.add_paragraph()
582
  p.text = report['title'].upper()
583
  p.font.size = Pt(48)
 
590
  subtitle_p.font.color.rgb = RGBColor(*TEXT_MUTED)
591
  subtitle_p.space_before = Pt(20)
592
 
593
+ # 2. EXECUTIVE SUMMARY
594
  slide = add_branded_slide("EXECUTIVE SUMMARY")
595
  body_box = slide.shapes.add_textbox(Inches(1), Inches(1.5), Inches(11), Inches(5))
596
  tf = body_box.text_frame
 
601
  p.font.color.rgb = RGBColor(*TEXT_MAIN)
602
  p.line_spacing = 1.2
603
 
604
+ # 3. ANALYTICAL TRENDS (30 DAYS)
605
+ slide = add_branded_slide("30-DAY ANALYTICAL TRENDS")
606
 
607
+ # Summary Table for Trends
608
+ trends = context['trends_30d']
609
+ rows, cols = 4, 3
610
+ left, top, width, height = Inches(1), Inches(1.5), Inches(11), Inches(3)
611
+ table = slide.shapes.add_table(rows, cols, left, top, width, height).table
612
 
613
+ table.cell(0, 0).text = "METRIC"
614
+ table.cell(0, 1).text = "PEAK PERFORMANCE"
615
+ table.cell(0, 2).text = "MONTHLY AVG"
 
 
 
 
 
 
 
616
 
617
+ metrics = [
618
+ ("Ticket Velocity", list(trends['velocity'].values()) if trends['velocity'] else [0]),
619
+ ("CSAT Rating", list(trends['csat'].values()) if trends['csat'] else [0]),
620
+ ("Resolution Time", list(trends['resolution_hours'].values()) if trends['resolution_hours'] else [0])
621
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
622
 
623
+ for i, (name, points) in enumerate(metrics):
624
+ table.cell(i+1, 0).text = name
625
+ table.cell(i+1, 1).text = str(max(points))
626
+ avg = round(sum(points) / len(points), 2) if points else 0
627
+ table.cell(i+1, 2).text = str(avg)
628
+
629
+ # Styling Table
630
+ for r in range(rows):
631
+ for c in range(cols):
632
+ cell = table.cell(r, c)
633
+ if r == 0:
634
+ cell.fill.solid()
635
+ cell.fill.foreground_color.rgb = RGBColor(*BRAND_PURPLE)
636
+ cell.text_frame.paragraphs[0].font.color.rgb = RGBColor(255, 255, 255)
637
+ cell.text_frame.paragraphs[0].font.bold = True
638
+ cell.text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
639
+
640
+ # Analytical Insight Box
641
+ insight_box = slide.shapes.add_textbox(Inches(1), Inches(5), Inches(11), Inches(2))
642
+ itf = insight_box.text_frame
643
+ ip = itf.add_paragraph()
644
+ ip.text = f"KEY INSIGHT: {report.get('analytical_insight', '')}"
645
+ ip.font.size = Pt(20)
646
+ ip.font.bold = True
647
+ ip.font.italic = True
648
+ ip.font.color.rgb = RGBColor(*BRAND_PURPLE)
649
+
650
+ # 4. ROLE-SPECIFIC DEEP DIVES
651
+ for section in report.get("sections", []):
652
+ slide = add_branded_slide(section['title'])
653
+
654
+ # Main Content
655
+ box = slide.shapes.add_textbox(Inches(1), Inches(1.5), Inches(6), Inches(5))
656
+ tf = box.text_frame
657
+ tf.word_wrap = True
658
  p = tf.add_paragraph()
659
+ p.text = section['content']
660
+ p.font.size = Pt(16)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
 
662
+ # Highlights Column
663
+ h_box = slide.shapes.add_textbox(Inches(7.5), Inches(1.5), Inches(5), Inches(5))
664
+ htf = h_box.text_frame
665
+ hp = htf.add_paragraph()
666
+ hp.text = "STRATEGIC HIGHLIGHTS"
667
+ hp.font.bold = True
668
+ hp.font.color.rgb = RGBColor(*BRAND_PURPLE)
669
 
670
+ for highlight in section.get("highlights", []):
671
+ p = htf.add_paragraph()
672
+ p.text = highlight
673
+ p.bullet = True
674
+ p.font.size = Pt(14)
675
+ p.space_before = Pt(10)
676
+
677
+ # 5. ROADMAP
678
+ slide = add_branded_slide("STRATEGIC ROADMAP")
679
+ roadmap = report.get('strategic_roadmap', [])
680
+ num_phases = len(roadmap)
681
+ if num_phases > 0:
682
+ width = (prs.slide_width - Inches(2)) / num_phases
683
+ for i, item in enumerate(roadmap):
684
+ left = Inches(1) + (i * width)
685
+ shape = slide.shapes.add_shape(MSO_SHAPE.CHEVRON, left, Inches(2), width - Inches(0.2), Inches(1))
686
+ shape.fill.solid()
687
+ shape.fill.foreground_color.rgb = RGBColor(*BRAND_PURPLE)
688
+ shape.line.fill.background()
689
+
690
+ p_txt = slide.shapes.add_textbox(left, Inches(2.2), width - Inches(0.2), Inches(0.6))
691
+ tp = p_txt.text_frame.paragraphs[0]
692
+ tp.text = f"PHASE {i+1}"
693
+ tp.font.bold = True
694
+ tp.font.color.rgb = RGBColor(255, 255, 255)
695
+ tp.alignment = PP_ALIGN.CENTER
696
+
697
+ c_box = slide.shapes.add_textbox(left, Inches(3.2), width - Inches(0.2), Inches(3))
698
+ ctf = c_box.text_frame
699
+ ctf.word_wrap = True
700
+ cp = ctf.paragraphs[0]
701
+ cp.text = item
702
+ cp.font.size = Pt(14)
703
+ cp.alignment = PP_ALIGN.CENTER
704
 
705
  pptx_io = io.BytesIO()
706
  prs.save(pptx_io)