Spaces:
Paused

dushyantsingh0 Claude Sonnet 4.6 commited on
Commit
f2cc4e3
·
1 Parent(s): 7b2ff9f

enterprise pptx/pdf report overhaul with role-aware content

Browse files

Complete rewrite of generate_enterprise_pptx and generate_enterprise_pdf
in tasks/stories.py for production-grade visual output.

PPTX (10+ slides, was ~5):
- Title slide: dark navy + brand identity panel + KPI strip
- TOC slide with numbered section descriptions
- KPI Dashboard: 6 color-coded metric cards (CSAT, resolution time,
velocity, priority counts, resolution rate)
- Status Distribution: native PPTX column chart + breakdown panel
- 30-Day Trends: 3 native line charts (velocity / CSAT / resolution hours)
- Priority Analysis: native column chart + color-coded progress bars
- Role-specific section slides: content + highlights panel layout
- Strategic Roadmap: phase cards with arrow connectors
- Signals Audit: color-coded table (status/priority highlighted)
- Consistent footer with slide numbers on every slide

PDF improvements:
- KPI strip on title page and KPI row on executive summary
- Bar charts: gridlines, drop-shadow, value labels above bars
- Line charts: gridlines, y-axis scale labels, endpoint dot markers
- Priority section with color-coded progress bars
- Signals table expanded to 5 columns (added CREATED date)
- kpi_box() and section_header() helpers for consistent styling

LLM prompt (role-aware content):
- Internal roles (sc_admin/lead/superadmin): Operational Throughput,
Resource & Priority Intelligence, SLA & Service Excellence,
Team Performance Signals
- customer_admin: Service Delivery Health, Customer Experience,
Issue Escalation Analysis, Relationship Health
- Hard requirements: exactly 4 sections, 5 roadmap items, real data only

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (1) hide show
  1. tasks/stories.py +1178 -460
tasks/stories.py CHANGED
@@ -14,20 +14,26 @@ from core.websockets import manager
14
 
15
  logger = logging.getLogger(__name__)
16
 
 
17
  # Enterprise Color Palette
18
- BRAND_PURPLE = (124, 58, 237)
19
- BRAND_GREEN = (16, 185, 129)
20
- BRAND_AMBER = (245, 158, 11)
21
- TEXT_MAIN = (31, 41, 55)
22
- TEXT_MUTED = (107, 114, 128)
23
- BG_LIGHT = (249, 250, 251)
 
 
 
 
 
 
 
 
24
 
25
  async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, workspace_id: UUID, role: str):
26
- """
27
- Background job to generate a professional, enterprise-grade workspace story (PDF/PPT).
28
- """
29
  async with async_session_factory() as db:
30
- # 1. Update status to PROCESSING
31
  await db.execute(
32
  update(WorkspaceStory)
33
  .where(WorkspaceStory.id == story_id)
@@ -42,75 +48,77 @@ 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 (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()),
@@ -121,135 +129,168 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
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,
131
- "timestamp": datetime.utcnow().isoformat()
132
  }
133
 
134
  story_stmt = select(WorkspaceStory).where(WorkspaceStory.id == story_id)
135
- story_res = await db.execute(story_stmt)
136
- story_obj = story_res.scalar_one_or_none()
137
-
138
  if not story_obj:
139
  return
140
 
141
  custom_spec = story_obj.custom_instructions
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)
183
  from langchain_core.messages import SystemMessage, HumanMessage
184
-
185
  res = await llm.ainvoke([
186
- SystemMessage(content="You are a JSON report generator. You output raw JSON only, no markdown, no preamble."),
187
- HumanMessage(content=prompt)
188
  ])
189
-
190
- # Robust JSON extraction
191
  import re
192
  content = res.content.strip()
193
- json_match = re.search(r'\{.*\}', content, re.DOTALL)
194
  if json_match:
195
  content = json_match.group(0)
196
-
197
  try:
198
  report_data = json.loads(content)
199
  except Exception as json_err:
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
  }
210
 
211
- # 4. Binary Document Generation
212
  file_name = f"Strategic_Story_{story_id}.{file_type}"
213
- binary_content = b""
214
-
215
  if file_type == "pdf":
216
  binary_content = generate_enterprise_pdf(report_data, context_data)
217
  elif file_type == "pptx":
218
  binary_content = generate_enterprise_pptx(report_data, context_data)
219
  else:
220
- binary_content = content.encode('utf-8')
221
 
222
- # 5. Upload and Finalize
223
  storage = get_storage_provider()
224
  storage_result = await storage.upload(
225
  file_content=binary_content,
226
  filename=file_name,
227
- workspace_id=workspace_id
228
  )
229
-
230
  file_url = await storage.get_url(storage_result.path)
231
- if not file_url.startswith('http') and not file_url.startswith('/'):
232
  file_url = f"/{file_url}"
233
-
234
  await db.execute(
235
  update(WorkspaceStory)
236
  .where(WorkspaceStory.id == story_id)
237
  .values(
238
  status=StoryStatus.COMPLETED,
239
  file_path=file_url,
240
- metadata_json={"narrative_preview": report_data.get("executive_summary", "")[:500]}
241
  )
242
  )
243
  await db.commit()
244
-
245
  await manager.broadcast_to_workspace(workspace_id, {
246
  "event": "nexus_story_updated",
247
  "story_id": str(story_id),
248
- "status": "completed"
249
  })
250
 
251
  except Exception as e:
252
- logger.error(f"❌ Enterprise story failed: {str(e)}")
253
  import traceback
254
  traceback.print_exc()
255
  await db.execute(
@@ -258,27 +299,32 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
258
  .values(status=StoryStatus.FAILED, metadata_json={"error": str(e)})
259
  )
260
  await db.commit()
261
-
262
  await manager.broadcast_to_workspace(workspace_id, {
263
  "event": "nexus_story_updated",
264
  "story_id": str(story_id),
265
  "status": "failed",
266
- "error": str(e)
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):
276
  if self.page_no() > 1:
277
  self.set_font("helvetica", "B", 8)
278
  self.set_text_color(*TEXT_MUTED)
279
- self.cell(0, 10, f"NEXUS STRATEGIC REPORT | {report['title'].upper()}", align="R")
280
- self.ln(10)
281
  self.set_draw_color(*BRAND_PURPLE)
 
282
  self.line(10, self.get_y(), 200, self.get_y())
283
  self.ln(5)
284
 
@@ -290,417 +336,1089 @@ def generate_enterprise_pdf(report, context):
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
-
314
- pdf.set_xy(25, 60)
315
- pdf.set_font("helvetica", "B", 36)
316
  pdf.set_text_color(*BRAND_PURPLE)
317
- pdf.multi_cell(0, 12, report['title'].upper())
318
-
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()}")
326
-
327
- pdf.set_xy(25, 240)
328
- pdf.set_font("helvetica", "", 10)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  pdf.set_text_color(*TEXT_MUTED)
330
- pdf.cell(0, 10, f"GENERATED: {datetime.now().strftime('%d %B %Y | %H:%M UTC')}")
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)
355
  pdf.set_text_color(*TEXT_MAIN)
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:
453
- header = table.row()
454
- header.cell("ID", style=FontFace(emphasis="BOLD", fill_color=BRAND_PURPLE, color=(255, 255, 255)))
455
- header.cell("TITLE", style=FontFace(emphasis="BOLD", fill_color=BRAND_PURPLE, color=(255, 255, 255)))
456
- header.cell("STATUS", style=FontFace(emphasis="BOLD", fill_color=BRAND_PURPLE, color=(255, 255, 255)))
457
- header.cell("PRIORITY", style=FontFace(emphasis="BOLD", fill_color=BRAND_PURPLE, color=(255, 255, 255)))
458
-
459
- for t in context['recent_tickets']:
 
 
460
  row = table.row()
461
- row.cell(t['id'])
462
- row.cell(t['title'][:40] + "..." if len(t['title']) > 40 else t['title'])
463
- row.cell(t['status'])
464
- row.cell(t['priority'])
 
 
 
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
535
  from pptx.dml.color import RGBColor
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)
559
- title_shape.top = Inches(0.1)
560
- title_shape.width = prs.slide_width - Inches(1)
561
- title_shape.height = Inches(0.6)
562
-
563
- title_tf = title_shape.text_frame
564
- p = title_tf.paragraphs[0]
565
- p.font.size = Pt(28)
566
- p.font.bold = True
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)
584
- p.font.bold = True
585
- p.font.color.rgb = RGBColor(*BRAND_PURPLE)
586
-
587
- subtitle_p = tf.add_paragraph()
588
- subtitle_p.text = f"Strategic Workspace Narrative\nRecipient: {context['role'].replace('_', ' ').upper()}"
589
- subtitle_p.font.size = Pt(18)
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
 
 
 
597
  tf.word_wrap = True
598
- p = tf.add_paragraph()
599
- p.text = report['executive_summary']
600
- p.font.size = Pt(18)
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)
 
14
 
15
  logger = logging.getLogger(__name__)
16
 
17
+ # ---------------------------------------------------------------------------
18
  # Enterprise Color Palette
19
+ # ---------------------------------------------------------------------------
20
+ BRAND_PURPLE = (124, 58, 237)
21
+ BRAND_PURPLE_DARK = (76, 29, 149)
22
+ BRAND_PURPLE_LIGHT= (167, 139, 250)
23
+ BRAND_GREEN = (16, 185, 129)
24
+ BRAND_AMBER = (245, 158, 11)
25
+ BRAND_RED = (239, 68, 68)
26
+ BRAND_BLUE = (14, 165, 233)
27
+ TEXT_MAIN = (31, 41, 55)
28
+ TEXT_MUTED = (107, 114, 128)
29
+ BG_LIGHT = (249, 250, 251)
30
+ BG_WHITE = (255, 255, 255)
31
+ BG_DARK = (12, 8, 36)
32
+
33
 
34
  async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, workspace_id: UUID, role: str):
35
+ """Background job: builds a production-grade workspace strategic narrative (PDF / PPTX)."""
 
 
36
  async with async_session_factory() as db:
 
37
  await db.execute(
38
  update(WorkspaceStory)
39
  .where(WorkspaceStory.id == story_id)
 
48
  })
49
 
50
  try:
51
+ from sqlalchemy import func
 
52
  from datetime import timedelta
53
  from models.feedback import Feedback
54
+
55
  thirty_days_ago = datetime.utcnow() - timedelta(days=30)
56
+
57
+ # --- Snapshot aggregates ---
58
+ status_stmt = (
59
+ select(Ticket.status, func.count(Ticket.id))
60
+ .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None))
61
+ .group_by(Ticket.status)
62
+ )
63
+ status_map = {
64
+ str(r[0].value if hasattr(r[0], "value") else r[0]): r[1]
65
+ for r in (await db.execute(status_stmt)).all()
66
+ }
67
+
68
+ prio_stmt = (
69
+ select(Ticket.priority, func.count(Ticket.id))
70
+ .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None))
71
+ .group_by(Ticket.priority)
72
+ )
73
+ prio_map = {
74
+ str(r[0].value if hasattr(r[0], "value") else r[0]): r[1]
75
+ for r in (await db.execute(prio_stmt)).all()
76
+ }
77
+
78
+ # --- Trend aggregates (30 days) ---
79
+ velocity_stmt = (
80
+ select(func.date_trunc("day", Ticket.created_at).label("day"), func.count(Ticket.id))
81
+ .where(Ticket.workspace_id == workspace_id, Ticket.created_at >= thirty_days_ago, Ticket.deleted_at.is_(None))
82
+ .group_by("day").order_by("day")
83
+ )
84
+ velocity_data = {r[0].strftime("%Y-%m-%d"): r[1] for r in (await db.execute(velocity_stmt)).all()}
85
+
86
+ csat_stmt = (
87
+ select(func.date_trunc("day", Feedback.created_at).label("day"), func.avg(Feedback.rating))
88
+ .where(Feedback.workspace_id == workspace_id, Feedback.created_at >= thirty_days_ago)
89
+ .group_by("day").order_by("day")
90
+ )
91
+ csat_data = {r[0].strftime("%Y-%m-%d"): round(float(r[1]), 2) for r in (await db.execute(csat_stmt)).all()}
92
+
93
+ res_perf_stmt = (
94
+ select(
95
+ func.date_trunc("day", Ticket.resolved_at).label("day"),
96
+ func.avg(func.extract("epoch", Ticket.resolved_at - Ticket.created_at) / 3600.0),
97
+ )
98
+ .where(Ticket.workspace_id == workspace_id, Ticket.resolved_at >= thirty_days_ago, Ticket.deleted_at.is_(None))
99
+ .group_by("day").order_by("day")
100
+ )
101
+ res_perf_data = {r[0].strftime("%Y-%m-%d"): round(float(r[1]), 2) for r in (await db.execute(res_perf_stmt)).all()}
102
+
103
+ prio_trend_stmt = (
104
+ select(func.date_trunc("day", Ticket.created_at).label("day"), Ticket.priority, func.count(Ticket.id))
105
+ .where(Ticket.workspace_id == workspace_id, Ticket.created_at >= thirty_days_ago, Ticket.deleted_at.is_(None))
106
+ .group_by("day", Ticket.priority).order_by("day")
107
+ )
108
  prio_trend_raw = (await db.execute(prio_trend_stmt)).all()
109
+ prio_trend_data: dict = {}
110
  for day_dt, prio, count in prio_trend_raw:
111
+ ds = day_dt.strftime("%Y-%m-%d")
112
+ prio_trend_data.setdefault(ds, {})[prio.value] = count
 
 
113
 
114
+ ticket_stmt = (
115
+ select(Ticket)
116
+ .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None))
117
+ .order_by(Ticket.created_at.desc())
118
+ .limit(20)
119
+ )
120
  tickets = (await db.execute(ticket_stmt)).scalars().all()
121
+
122
  context_data = {
123
  "snapshot": {
124
  "total_active_tickets": sum(status_map.values()),
 
129
  "velocity": velocity_data,
130
  "csat": csat_data,
131
  "resolution_hours": res_perf_data,
132
+ "priority_shift": prio_trend_data,
133
  },
134
  "recent_tickets": [
135
+ {
136
+ "id": str(t.id)[:8],
137
+ "title": t.title,
138
+ "status": t.status.value,
139
+ "priority": t.priority.value,
140
+ "created_at": t.created_at.isoformat(),
141
+ }
142
  for t in tickets
143
  ],
144
  "role": role,
145
+ "timestamp": datetime.utcnow().isoformat(),
146
  }
147
 
148
  story_stmt = select(WorkspaceStory).where(WorkspaceStory.id == story_id)
149
+ story_obj = (await db.execute(story_stmt)).scalar_one_or_none()
 
 
150
  if not story_obj:
151
  return
152
 
153
  custom_spec = story_obj.custom_instructions
154
  file_type = story_obj.file_type or "pdf"
155
 
156
+ # --- Role-aware prompt construction ---
157
  is_internal = role in ["3sc_admin", "superadmin", "sc_admin", "sc_lead", "sc_agent"]
158
+
159
+ if is_internal:
160
+ role_flavor = "operational efficiency, tactical throughput, and resource optimization"
161
+ section_guidance = """
162
+ Generate exactly 4 sections tailored to an internal operations lead:
163
+ 1. "Operational Throughput" — velocity trends, bottlenecks, open vs in-progress ratio
164
+ 2. "Resource & Priority Intelligence" — P0/P1 pressure, allocation gaps, burndown risk
165
+ 3. "SLA & Service Excellence" — resolution time analysis, breach risk, SLA alignment
166
+ 4. "Team Performance Signals" — implied staff efficiency from resolution trends
167
+ """
168
+ else:
169
+ role_flavor = "strategic alignment, service excellence, and relationship health"
170
+ section_guidance = """
171
+ Generate exactly 4 sections tailored to a customer admin stakeholder:
172
+ 1. "Service Delivery Health" — ticket status overview from the customer lens
173
+ 2. "Customer Experience & Satisfaction" — CSAT trends, responsiveness signals
174
+ 3. "Issue Escalation Analysis" — high-priority tickets, outstanding items, resolution velocity
175
+ 4. "Relationship Health & Recommendations" — overall service health score, risk signals, improvements
176
+ """
177
+
178
  prompt = f"""
179
+ You are the Nexus Enterprise Strategist AI. Generate a high-fidelity, forensic workspace narrative for a {role}.
180
+
181
+ Focus: {role_flavor}.
182
+ User-Specific Goals: {custom_spec or "Standard workspace health overview."}
183
+
184
+ Data Context (30-Day Telemetry):
185
+ {json.dumps(context_data, indent=2)}
186
+
187
+ {section_guidance}
188
+
189
+ Output strictly as a JSON object. No preamble, no markdown fences, no explanation. Raw JSON only.
190
+
191
+ Required JSON structure:
192
+ {{
193
+ "title": "Descriptive, professional report title (e.g. 'Q2 Service Excellence Report — Customer Workspace')",
194
+ "executive_summary": "3 tight paragraphs of forensic, data-backed analysis referencing specific numbers from the telemetry.",
195
+ "sections": [
196
+ {{
197
+ "title": "Section Title",
198
+ "content": "3-5 sentences of analytical depth. Cite real numbers from the data. Avoid generic statements.",
199
+ "highlights": [
200
+ "Specific, data-backed highlight with numbers (e.g. '6 P0 tickets active — 40% above 30-day baseline')",
201
+ "...",
202
+ "..."
203
+ ]
204
+ }}
205
+ ],
206
+ "strategic_roadmap": [
207
+ "Specific, actionable initiative referencing the data (e.g. 'Introduce triage SLA for P0 tickets targeting < 2h first-response')",
208
+ "...",
209
+ "...",
210
+ "...",
211
+ "..."
212
+ ],
213
+ "analytical_insight": "One powerful sentence that distills the single most critical trend found in the 30-day window."
214
+ }}
215
+
216
+ Rules:
217
+ - sections array MUST have exactly 4 objects
218
+ - strategic_roadmap MUST have exactly 5 items
219
+ - All numbers cited must come from the provided data
220
+ - Tone: professional, direct, objective. Zero filler. Zero corporate fluff.
221
+ """
222
+
223
  llm = get_llm(is_heavy_task=True)
224
  from langchain_core.messages import SystemMessage, HumanMessage
225
+
226
  res = await llm.ainvoke([
227
+ SystemMessage(content="You are a JSON-only report generator. Output raw JSON. No markdown. No explanation."),
228
+ HumanMessage(content=prompt),
229
  ])
230
+
 
231
  import re
232
  content = res.content.strip()
233
+ json_match = re.search(r"\{.*\}", content, re.DOTALL)
234
  if json_match:
235
  content = json_match.group(0)
236
+
237
  try:
238
  report_data = json.loads(content)
239
  except Exception as json_err:
240
+ logger.warning(f"LLM JSON parse failed: {json_err}. Raw: {content[:300]}...")
241
  report_data = {
242
+ "title": "Workspace Strategic Health Report",
243
+ "executive_summary": "System-generated summary. LLM narrative unavailable.",
244
  "sections": [
245
+ {
246
+ "title": "Operational Overview",
247
+ "content": "Telemetry collection completed successfully.",
248
+ "highlights": ["Data pipeline nominal.", "Manual review recommended."],
249
+ }
250
+ ] * 4,
251
+ "strategic_roadmap": [f"Initiative {i+1}: Review workspace telemetry." for i in range(5)],
252
+ "analytical_insight": "Automated insight generation requires manual review.",
253
  }
254
 
255
+ # --- Generate binary document ---
256
  file_name = f"Strategic_Story_{story_id}.{file_type}"
 
 
257
  if file_type == "pdf":
258
  binary_content = generate_enterprise_pdf(report_data, context_data)
259
  elif file_type == "pptx":
260
  binary_content = generate_enterprise_pptx(report_data, context_data)
261
  else:
262
+ binary_content = content.encode("utf-8")
263
 
 
264
  storage = get_storage_provider()
265
  storage_result = await storage.upload(
266
  file_content=binary_content,
267
  filename=file_name,
268
+ workspace_id=workspace_id,
269
  )
270
+
271
  file_url = await storage.get_url(storage_result.path)
272
+ if not file_url.startswith("http") and not file_url.startswith("/"):
273
  file_url = f"/{file_url}"
274
+
275
  await db.execute(
276
  update(WorkspaceStory)
277
  .where(WorkspaceStory.id == story_id)
278
  .values(
279
  status=StoryStatus.COMPLETED,
280
  file_path=file_url,
281
+ metadata_json={"narrative_preview": report_data.get("executive_summary", "")[:500]},
282
  )
283
  )
284
  await db.commit()
285
+
286
  await manager.broadcast_to_workspace(workspace_id, {
287
  "event": "nexus_story_updated",
288
  "story_id": str(story_id),
289
+ "status": "completed",
290
  })
291
 
292
  except Exception as e:
293
+ logger.error(f"Enterprise story generation failed: {e}")
294
  import traceback
295
  traceback.print_exc()
296
  await db.execute(
 
299
  .values(status=StoryStatus.FAILED, metadata_json={"error": str(e)})
300
  )
301
  await db.commit()
 
302
  await manager.broadcast_to_workspace(workspace_id, {
303
  "event": "nexus_story_updated",
304
  "story_id": str(story_id),
305
  "status": "failed",
306
+ "error": str(e),
307
  })
308
 
309
+
310
+ # ===========================================================================
311
+ # PDF GENERATION — fpdf2
312
+ # ===========================================================================
313
+
314
  def generate_enterprise_pdf(report, context):
315
+ """Production-grade PDF: TOC, KPI summary, trend charts, role-specific sections."""
316
  from fpdf import FPDF
317
  from fpdf.fonts import FontFace
318
+
319
  class EnterprisePDF(FPDF):
320
  def header(self):
321
  if self.page_no() > 1:
322
  self.set_font("helvetica", "B", 8)
323
  self.set_text_color(*TEXT_MUTED)
324
+ self.cell(0, 10, f"NEXUS STRATEGIC REPORT | {report['title'].upper()}", align="R")
325
+ self.ln(8)
326
  self.set_draw_color(*BRAND_PURPLE)
327
+ self.set_line_width(0.4)
328
  self.line(10, self.get_y(), 200, self.get_y())
329
  self.ln(5)
330
 
 
336
 
337
  def add_toc(self, items):
338
  self.add_page()
339
+ self.set_font("helvetica", "B", 22)
340
  self.set_text_color(*BRAND_PURPLE)
341
+ self.cell(0, 14, "TABLE OF CONTENTS", ln=1)
342
+ self.set_draw_color(*BRAND_PURPLE)
343
+ self.set_line_width(0.5)
344
+ self.line(10, self.get_y(), 200, self.get_y())
345
+ self.ln(8)
346
+ for i, (title, page) in enumerate(items):
347
+ self.set_font("helvetica", "B", 11)
348
+ self.set_text_color(*TEXT_MAIN)
349
+ self.set_fill_color(*(BG_LIGHT if i % 2 == 0 else BG_WHITE))
350
+ self.cell(8, 9, str(i + 1), fill=True)
351
+ self.cell(165, 9, f" {title}", fill=True)
352
+ self.cell(17, 9, str(page), fill=True, align="R")
353
+ self.ln(11)
354
+
355
+ def kpi_box(self, x, y, w, h, label, value, sub, color):
356
+ self.set_fill_color(*BG_WHITE)
357
+ self.rect(x, y, w, h, "F")
358
+ self.set_fill_color(*color)
359
+ self.rect(x, y, w, 1.5, "F")
360
+ self.set_xy(x + 2, y + 3)
361
+ self.set_font("helvetica", "B", 18)
362
+ self.set_text_color(*color)
363
+ self.cell(w - 4, 8, str(value), align="C")
364
+ self.set_xy(x + 2, y + 11)
365
+ self.set_font("helvetica", "B", 7)
366
  self.set_text_color(*TEXT_MAIN)
367
+ self.cell(w - 4, 4, label, align="C")
368
+ self.set_xy(x + 2, y + 15)
369
+ self.set_font("helvetica", "", 6)
370
+ self.set_text_color(*TEXT_MUTED)
371
+ self.cell(w - 4, 4, sub, align="C")
372
+
373
+ def section_header(self, num, title):
374
+ self.set_fill_color(*BRAND_PURPLE)
375
+ self.set_text_color(*BG_WHITE)
376
+ self.set_font("helvetica", "B", 14)
377
+ self.cell(0, 11, f" {num}. {title.upper()}", fill=True, ln=1)
378
+ self.ln(6)
379
 
380
  pdf = EnterprisePDF()
381
+ pdf.set_auto_page_break(auto=True, margin=18)
382
+
383
+ # -------------------------------------------------------------------------
384
  # 1. TITLE PAGE
385
+ # -------------------------------------------------------------------------
386
  pdf.add_page()
387
  pdf.set_fill_color(*BG_LIGHT)
388
  pdf.rect(0, 0, 210, 297, "F")
389
+ pdf.set_fill_color(*BG_DARK)
390
+ pdf.rect(0, 0, 14, 297, "F")
391
  pdf.set_fill_color(*BRAND_PURPLE)
392
  pdf.rect(0, 0, 10, 297, "F")
393
+
394
+ pdf.set_xy(22, 55)
395
+ pdf.set_font("helvetica", "B", 38)
396
  pdf.set_text_color(*BRAND_PURPLE)
397
+ pdf.multi_cell(0, 14, report["title"].upper())
398
+
399
+ pdf.set_xy(22, 118)
400
+ pdf.set_draw_color(*BRAND_PURPLE_LIGHT)
401
+ pdf.set_line_width(0.5)
402
+ pdf.line(22, 118, 185, 118)
403
+
404
+ pdf.set_xy(22, 124)
405
+ pdf.set_font("helvetica", "", 13)
406
  pdf.set_text_color(*TEXT_MAIN)
407
+ pdf.cell(0, 8, "WORKSPACE STRATEGIC NARRATIVE")
408
+ pdf.ln(9)
409
+ pdf.set_font("helvetica", "B", 11)
410
+ pdf.cell(0, 8, f"RECIPIENT: {context['role'].replace('_', ' ').upper()}")
411
+
412
+ # KPI preview strip on title page
413
+ snapshot = context["snapshot"]
414
+ prio_map = snapshot["priority_distribution"]
415
+ total = snapshot["total_active_tickets"] or 1
416
+ csat_vals = list(context["trends_30d"]["csat"].values())
417
+ avg_csat = round(sum(csat_vals) / len(csat_vals), 1) if csat_vals else 0
418
+ res_vals = list(context["trends_30d"]["resolution_hours"].values())
419
+ avg_res = round(sum(res_vals) / len(res_vals), 1) if res_vals else 0
420
+ high_prio = (
421
+ prio_map.get("P0", prio_map.get("p0", 0))
422
+ + prio_map.get("P1", prio_map.get("p1", 0))
423
+ )
424
+
425
+ kpi_box_w = 36
426
+ kpi_box_h = 22
427
+ kpi_y = 155
428
+ kpis = [
429
+ ("TOTAL TICKETS", total, "Active", BRAND_PURPLE),
430
+ ("AVG CSAT", f"{avg_csat}/5", "30-day avg", BRAND_GREEN if avg_csat >= 4 else BRAND_AMBER),
431
+ ("AVG RESOLUTION", f"{avg_res}h", "Per ticket", BRAND_AMBER if avg_res > 24 else BRAND_GREEN),
432
+ ("HIGH PRIORITY", high_prio, "P0 + P1", BRAND_RED if high_prio > 5 else BRAND_AMBER),
433
+ ]
434
+ for i, (label, value, sub, color) in enumerate(kpis):
435
+ pdf.kpi_box(22 + i * (kpi_box_w + 4), kpi_y, kpi_box_w, kpi_box_h, label, value, sub, color)
436
+
437
+ pdf.set_xy(22, 248)
438
+ pdf.set_font("helvetica", "", 9)
439
  pdf.set_text_color(*TEXT_MUTED)
440
+ pdf.cell(0, 8, f"GENERATED: {datetime.now().strftime('%d %B %Y | %H:%M UTC')}")
441
  pdf.ln(6)
442
+ pdf.cell(0, 8, "STRICTLY CONFIDENTIAL | NEXUS INTERNAL USE ONLY")
443
 
444
+ # -------------------------------------------------------------------------
445
  # 2. TABLE OF CONTENTS
446
+ # -------------------------------------------------------------------------
447
  toc_items = [
448
  ("Executive Summary", 3),
449
+ ("KPI Overview", 3),
450
  ("Historical Trend Analysis", 4),
451
  ("Priority & Resource Allocation", 5),
452
  ]
453
+ for i, sec in enumerate(report.get("sections", [])):
454
+ toc_items.append((sec["title"], 6 + i))
455
  toc_items.append(("Strategic Roadmap", 6 + len(report.get("sections", []))))
456
  toc_items.append(("Recent Signals Audit", 7 + len(report.get("sections", []))))
 
457
  pdf.add_toc(toc_items)
458
 
459
+ # -------------------------------------------------------------------------
460
+ # 3. EXECUTIVE SUMMARY + KPI BOXES
461
+ # -------------------------------------------------------------------------
462
  pdf.add_page()
463
+ pdf.section_header(1, "Executive Summary")
464
+
465
+ pdf.set_font("helvetica", "", 10.5)
 
 
 
466
  pdf.set_text_color(*TEXT_MAIN)
467
+ pdf.multi_cell(0, 6, report["executive_summary"])
468
+ pdf.ln(8)
469
+
470
+ # KPI row
471
+ status_dist = snapshot["status_distribution"]
472
+ resolved = status_dist.get("resolved", status_dist.get("RESOLVED", 0))
473
+ closed = status_dist.get("closed", status_dist.get("CLOSED", 0))
474
+ res_rate = f"{round((resolved + closed) / total * 100)}%" if total else "0%"
475
+
476
+ vel_vals = list(context["trends_30d"]["velocity"].values())
477
+ avg_vel = round(sum(vel_vals) / len(vel_vals), 1) if vel_vals else 0
478
+
479
+ kpi_row2 = [
480
+ ("TICKETS", total, "Total active", BRAND_PURPLE),
481
+ ("RESOLUTION RATE", res_rate, "Closed + Resolved", BRAND_GREEN),
482
+ ("CSAT SCORE", f"{avg_csat}/5", "Avg 30d rating", BRAND_GREEN if avg_csat >= 4 else BRAND_AMBER),
483
+ ("RES. TIME", f"{avg_res}h", "Avg per ticket", BRAND_AMBER if avg_res > 24 else BRAND_GREEN),
484
+ ("DAILY VELOCITY", avg_vel, "Avg tickets/day", BRAND_PURPLE),
485
+ ]
486
+ kw = 34
487
+ for i, (lbl, val, sub, col) in enumerate(kpi_row2):
488
+ pdf.kpi_box(10 + i * (kw + 2), pdf.get_y(), kw, 22, lbl, val, sub, col)
489
+ pdf.ln(30)
490
+
491
+ # Status distribution chart
492
+ pdf.set_font("helvetica", "B", 13)
493
+ pdf.set_text_color(*TEXT_MAIN)
494
+ pdf.cell(0, 8, "Current Status Distribution")
495
  pdf.ln(10)
496
+ _draw_bar_chart(pdf, status_dist, 10, pdf.get_y(), 185, 45, "Tickets by Status")
 
 
 
 
497
 
498
+ pdf.set_y(pdf.get_y() + 58)
499
+ pdf.set_fill_color(*BRAND_PURPLE_LIGHT)
500
+ insight = report.get("analytical_insight", "")
501
+ if insight:
502
+ pdf.set_fill_color(237, 233, 254)
503
+ pdf.set_text_color(*BRAND_PURPLE_DARK)
504
+ pdf.set_font("helvetica", "I", 10)
505
+ pdf.cell(5, 10, "", fill=True)
506
+ pdf.multi_cell(180, 6, f" KEY INSIGHT: {insight}", fill=True)
507
+
508
+ # -------------------------------------------------------------------------
509
+ # 4. TREND ANALYSIS
510
+ # -------------------------------------------------------------------------
511
  pdf.add_page()
512
+ pdf.section_header(2, "Historical Trend Analysis (30 Days)")
513
+
514
+ _draw_line_chart(pdf, context["trends_30d"]["velocity"], 10, pdf.get_y() + 5, 185, 45, "Ticket Velocity (Daily Volume)")
515
+ pdf.set_y(pdf.get_y() + 62)
516
+
517
+ if context["trends_30d"]["csat"]:
518
+ _draw_line_chart(pdf, context["trends_30d"]["csat"], 10, pdf.get_y() + 5, 185, 45, "CSAT Trend (Avg Rating)", color=BRAND_GREEN)
519
+ pdf.set_y(pdf.get_y() + 62)
520
+
521
+ if context["trends_30d"]["resolution_hours"]:
522
+ _draw_line_chart(pdf, context["trends_30d"]["resolution_hours"], 10, pdf.get_y() + 5, 185, 45, "Resolution Performance (Avg Hours)", color=BRAND_AMBER)
523
+
524
+ # -------------------------------------------------------------------------
525
+ # 5. PRIORITY & RESOURCE ALLOCATION
526
+ # -------------------------------------------------------------------------
 
527
  pdf.add_page()
528
+ pdf.section_header(3, "Priority & Resource Allocation")
529
+
530
+ pdf.set_font("helvetica", "B", 12)
 
 
 
531
  pdf.set_text_color(*TEXT_MAIN)
532
+ pdf.cell(0, 8, "Priority Volume Snapshot")
533
  pdf.ln(10)
534
+ _draw_bar_chart(pdf, prio_map, 10, pdf.get_y(), 185, 45, "Current Priority Distribution", color=BRAND_AMBER)
535
+
536
+ pdf.set_y(pdf.get_y() + 60)
537
+ pdf.set_font("helvetica", "B", 11)
538
+ pdf.cell(0, 8, "Priority Breakdown")
539
+ pdf.ln(6)
540
 
541
+ total_prio = sum(prio_map.values()) or 1
542
+ prio_color_map = {
543
+ "p0": BRAND_RED, "P0": BRAND_RED,
544
+ "p1": BRAND_AMBER, "P1": BRAND_AMBER,
545
+ "p2": BRAND_GREEN, "P2": BRAND_GREEN,
546
+ "p3": BRAND_BLUE, "P3": BRAND_BLUE,
547
+ }
548
+ for prio, cnt in prio_map.items():
549
+ pct = round(cnt / total_prio * 100)
550
+ color = prio_color_map.get(prio, BRAND_PURPLE)
551
+ pdf.set_fill_color(*color)
552
+ pdf.set_text_color(*BG_WHITE)
553
+ pdf.set_font("helvetica", "B", 9)
554
+ pdf.cell(20, 8, prio.upper(), fill=True, align="C")
555
+ bar_w = (pct / 100) * 130
556
+ pdf.set_fill_color(*color)
557
+ pdf.cell(bar_w if bar_w > 1 else 1, 8, "", fill=True)
558
+ pdf.set_fill_color(*BG_LIGHT)
559
+ pdf.cell(130 - (bar_w if bar_w > 1 else 1), 8, "", fill=True)
560
+ pdf.set_text_color(*TEXT_MAIN)
561
+ pdf.set_font("helvetica", "", 9)
562
+ pdf.cell(35, 8, f" {cnt} tickets ({pct}%)")
563
+ pdf.ln(10)
564
+
565
+ # -------------------------------------------------------------------------
566
  # 6. ROLE-SPECIFIC SECTIONS
567
+ # -------------------------------------------------------------------------
568
  for i, section in enumerate(report.get("sections", [])):
569
  pdf.add_page()
570
+ pdf.section_header(4 + i, section["title"])
571
+
572
+ pdf.set_font("helvetica", "", 10.5)
 
 
 
573
  pdf.set_text_color(*TEXT_MAIN)
574
+ pdf.multi_cell(0, 6.5, section["content"])
575
+ pdf.ln(8)
576
+
577
+ if section.get("highlights"):
578
+ pdf.set_fill_color(*BG_LIGHT)
579
+ pdf.set_font("helvetica", "B", 10)
580
+ pdf.set_text_color(*BRAND_PURPLE)
581
+ pdf.cell(0, 9, " KEY TAKEAWAYS", fill=True, ln=1)
 
 
582
  pdf.ln(2)
583
 
584
+ for highlight in section["highlights"]:
585
+ pdf.set_fill_color(*BRAND_PURPLE)
586
+ pdf.set_text_color(*BG_WHITE)
587
+ pdf.set_font("helvetica", "B", 8)
588
+ pdf.cell(6, 8, "", fill=True)
589
+ pdf.set_fill_color(237, 233, 254)
590
+ pdf.set_text_color(*TEXT_MAIN)
591
+ pdf.set_font("helvetica", "", 10)
592
+ pdf.multi_cell(184, 8, f" {highlight}", fill=True)
593
+ pdf.ln(2)
594
+
595
+ # -------------------------------------------------------------------------
596
  # 7. STRATEGIC ROADMAP
597
+ # -------------------------------------------------------------------------
598
  pdf.add_page()
599
+ pdf.section_header(4 + len(report.get("sections", [])), "Strategic Roadmap")
600
+
601
+ for i, item in enumerate(report.get("strategic_roadmap", [])):
602
+ phase_colors = [BRAND_PURPLE, BRAND_PURPLE_DARK, BRAND_BLUE, BRAND_GREEN, BRAND_AMBER]
603
+ color = phase_colors[i % len(phase_colors)]
604
+ pdf.set_fill_color(*color)
605
+ pdf.set_text_color(*BG_WHITE)
606
+ pdf.set_font("helvetica", "B", 10)
607
+ pdf.cell(32, 12, f" PHASE {i+1}", fill=True)
 
608
  pdf.set_fill_color(*BG_LIGHT)
609
  pdf.set_text_color(*TEXT_MAIN)
610
+ pdf.set_font("helvetica", "", 10)
611
+ pdf.multi_cell(158, 12, f" {item}", fill=True)
612
+ pdf.ln(4)
613
 
614
+ # -------------------------------------------------------------------------
615
+ # 8. RECENT SIGNALS AUDIT
616
+ # -------------------------------------------------------------------------
617
  pdf.add_page()
618
+ pdf.section_header(5 + len(report.get("sections", [])), "Recent Signals Audit")
619
+
 
 
 
620
  with pdf.table(
621
  borders_layout="HORIZONTAL_LINES",
622
+ cell_fill_color=(250, 248, 255),
623
  cell_fill_mode="ROWS",
624
  line_height=10,
625
+ text_align=("LEFT", "LEFT", "CENTER", "CENTER", "LEFT"),
626
+ width=190,
627
  ) as table:
628
+ hdr = table.row()
629
+ hdr_style = FontFace(emphasis="BOLD", fill_color=BRAND_PURPLE, color=(255, 255, 255))
630
+ hdr.cell("ID", style=hdr_style)
631
+ hdr.cell("TITLE", style=hdr_style)
632
+ hdr.cell("STATUS", style=hdr_style)
633
+ hdr.cell("PRIORITY", style=hdr_style)
634
+ hdr.cell("CREATED", style=hdr_style)
635
+
636
+ for t in context["recent_tickets"]:
637
  row = table.row()
638
+ row.cell(t["id"])
639
+ row.cell(t["title"][:50] + ("..." if len(t["title"]) > 50 else ""))
640
+ row.cell(t["status"].upper())
641
+ row.cell(t["priority"].upper())
642
+ row.cell(t["created_at"][:10])
643
+
644
+ return pdf.output(dest="S")
645
 
 
646
 
647
  def _draw_bar_chart(pdf, data, x, y, width, height, title, color=BRAND_PURPLE):
648
+ """Draws a styled bar chart with value labels, baseline, and grid."""
649
+ if not data:
650
+ return
651
+
652
+ # Title
653
+ pdf.set_font("helvetica", "B", 9)
654
  pdf.set_text_color(*TEXT_MAIN)
655
+ pdf.set_xy(x, y - 6)
656
  pdf.cell(width, 5, title, align="C")
657
+
 
 
658
  max_val = max(data.values()) if data.values() else 1
659
+ n = len(data)
660
+ bar_width = (width * 0.65) / n
661
  spacing = bar_width * 0.5
662
+ total_bars_w = n * (bar_width + spacing) - spacing
663
+ start_x = x + (width - total_bars_w) / 2
664
+
665
+ # Grid lines (light horizontal)
666
+ pdf.set_draw_color(220, 220, 230)
667
+ pdf.set_line_width(0.2)
668
+ for g in range(1, 5):
669
+ gy = y + height - (g / 4) * height
670
+ pdf.line(x, gy, x + width, gy)
671
+
672
+ # Baseline
673
+ pdf.set_draw_color(*TEXT_MUTED)
674
+ pdf.set_line_width(0.5)
675
+ pdf.line(x, y + height, x + width, y + height)
676
+
677
  for i, (label, count) in enumerate(data.items()):
678
+ bx = start_x + i * (bar_width + spacing)
679
+ h = (count / max_val) * height if max_val > 0 else 0
680
+
681
+ # Bar shadow (subtle)
682
+ pdf.set_fill_color(200, 195, 220)
683
+ pdf.rect(bx + 0.8, y + height - h + 0.8, bar_width, h, "F")
684
+
685
+ # Bar
686
  pdf.set_fill_color(*color)
687
+ pdf.rect(bx, y + height - h, bar_width, h, "F")
688
+
689
+ # Value label above bar
690
+ pdf.set_xy(bx, y + height - h - 5)
691
  pdf.set_font("helvetica", "B", 7)
692
+ pdf.set_text_color(*TEXT_MAIN)
 
 
 
693
  pdf.cell(bar_width, 4, str(count), align="C")
694
 
695
+ # X-axis label
696
+ pdf.set_xy(bx, y + height + 2)
697
+ pdf.set_font("helvetica", "", 6)
698
+ pdf.set_text_color(*TEXT_MUTED)
699
+ pdf.cell(bar_width, 4, str(label)[:10], align="C")
700
+
701
+
702
  def _draw_line_chart(pdf, data, x, y, width, height, title, color=BRAND_PURPLE):
703
+ """Draws a styled line chart with area fill, gridlines, and endpoint marker."""
704
+ # Title
705
+ pdf.set_font("helvetica", "B", 9)
706
  pdf.set_text_color(*TEXT_MAIN)
707
+ pdf.set_xy(x, y - 6)
708
  pdf.cell(width, 5, title, align="C")
709
+
710
  # Axes
711
+ pdf.set_draw_color(200, 200, 215)
712
+ pdf.set_line_width(0.3)
713
  pdf.line(x, y, x, y + height)
714
  pdf.line(x, y + height, x + width, y + height)
715
+
716
+ if not data:
717
  pdf.set_xy(x, y + height / 2)
718
+ pdf.set_font("helvetica", "I", 9)
719
+ pdf.set_text_color(*TEXT_MUTED)
720
+ pdf.cell(width, 10, "NO DATA AVAILABLE FOR THIS PERIOD", align="C")
721
  return
722
+
723
  points = list(data.values())
724
  max_val = max(points) if points else 1
725
+ if max_val == 0:
726
+ max_val = 1
727
+
728
+ # Horizontal grid lines
729
+ pdf.set_draw_color(230, 228, 240)
730
+ pdf.set_line_width(0.2)
731
+ for g in range(1, 5):
732
+ gy = y + height - (g / 4) * height
733
+ pdf.line(x, gy, x + width, gy)
734
+ val_label = round(max_val * g / 4, 1)
735
+ pdf.set_xy(x - 12, gy - 2)
736
+ pdf.set_font("helvetica", "", 5)
737
+ pdf.set_text_color(*TEXT_MUTED)
738
+ pdf.cell(10, 4, str(val_label), align="R")
739
+
740
  x_step = width / (len(points) - 1) if len(points) > 1 else width
741
+
742
+ # Draw line
743
  pdf.set_draw_color(*color)
744
+ pdf.set_line_width(0.7)
745
+
746
  prev_x, prev_y = None, None
747
  for i, val in enumerate(points):
748
+ px = x + i * x_step
749
  py = y + height - (val / max_val * height)
 
750
  if prev_x is not None:
751
  pdf.line(prev_x, prev_y, px, py)
 
 
 
752
  prev_x, prev_y = px, py
753
 
754
+ # Endpoint dot markers at first and last
755
+ for i in (0, len(points) - 1):
756
+ px = x + i * x_step
757
+ py = y + height - (points[i] / max_val * height)
758
+ pdf.set_fill_color(*color)
759
+ pdf.ellipse(px - 1.2, py - 1.2, 2.4, 2.4, "F")
760
+ pdf.set_xy(px - 6, py - 6)
761
+ pdf.set_font("helvetica", "B", 6)
762
+ pdf.set_text_color(*color)
763
+ pdf.cell(12, 4, str(round(points[i], 1)), align="C")
764
+
765
+
766
+ # ===========================================================================
767
+ # PPTX GENERATION — python-pptx
768
+ # ===========================================================================
769
+
770
  def generate_enterprise_pptx(report, context):
771
+ """
772
+ Production-grade PPTX deck: 10+ slides with native charts, KPI dashboard,
773
+ role-aware sections, consistent footer, and enterprise visual hierarchy.
774
+ """
775
  from pptx import Presentation
776
  from pptx.util import Inches, Pt
777
  from pptx.enum.text import PP_ALIGN
778
  from pptx.dml.color import RGBColor
779
+ from pptx.chart.data import CategoryChartData
780
+ from pptx.enum.chart import XL_CHART_TYPE
781
+
782
+ RECT = 1 # MSO_AUTO_SHAPE_TYPE.RECTANGLE integer value
783
+
784
  prs = Presentation()
785
+ prs.slide_width = Inches(13.333)
 
786
  prs.slide_height = Inches(7.5)
787
+ W = prs.slide_width
788
+ H = prs.slide_height
789
+
790
+ # ---- Color helpers ----
791
+ C_PURPLE = RGBColor(*BRAND_PURPLE)
792
+ C_PURPLE_D = RGBColor(*BRAND_PURPLE_DARK)
793
+ C_PURPLE_L = RGBColor(*BRAND_PURPLE_LIGHT)
794
+ C_GREEN = RGBColor(*BRAND_GREEN)
795
+ C_AMBER = RGBColor(*BRAND_AMBER)
796
+ C_RED = RGBColor(*BRAND_RED)
797
+ C_BLUE = RGBColor(*BRAND_BLUE)
798
+ C_DARK = RGBColor(*TEXT_MAIN)
799
+ C_MUTED = RGBColor(*TEXT_MUTED)
800
+ C_WHITE = RGBColor(255, 255, 255)
801
+ C_BG = RGBColor(247, 246, 252)
802
+ C_CARD = RGBColor(255, 255, 255)
803
+ C_BG_DARK = RGBColor(*BG_DARK)
804
+ C_ACCENT = RGBColor(237, 233, 254)
805
+
806
+ def set_bg(slide, color: RGBColor):
807
+ bg = slide.background
808
+ fill = bg.fill
809
+ fill.solid()
810
+ fill.fore_color.rgb = color
811
+
812
+ def add_rect(slide, left, top, width, height, color: RGBColor, line_color=None):
813
+ shape = slide.shapes.add_shape(RECT, left, top, width, height)
814
+ shape.fill.solid()
815
+ shape.fill.fore_color.rgb = color
816
+ if line_color:
817
+ shape.line.color.rgb = line_color
818
+ else:
819
+ shape.line.fill.background()
820
+ return shape
821
+
822
+ def add_text(slide, text, left, top, width, height, size,
823
+ bold=False, italic=False, color: RGBColor = None,
824
+ align=PP_ALIGN.LEFT, wrap=True):
825
+ tb = slide.shapes.add_textbox(left, top, width, height)
826
+ tf = tb.text_frame
827
+ tf.word_wrap = wrap
828
+ p = tf.paragraphs[0]
829
+ p.text = str(text)
830
+ p.font.size = Pt(size)
831
+ p.font.bold = bold
832
+ p.font.italic = italic
833
+ p.font.color.rgb = color or C_DARK
834
+ p.alignment = align
835
+ return tb
836
+
837
+ def add_footer(slide, slide_num, total):
838
+ add_rect(slide, 0, H - Inches(0.32), W, Inches(0.32), RGBColor(20, 12, 50))
839
+ add_text(
840
+ slide, "NEXUS ENTERPRISE STRATEGIC REPORT | STRICTLY CONFIDENTIAL",
841
+ Inches(0.3), H - Inches(0.28), W - Inches(2.5), Inches(0.25),
842
+ 7, color=RGBColor(160, 140, 210),
843
+ )
844
+ add_text(
845
+ slide, f"{slide_num} / {total}",
846
+ W - Inches(2), H - Inches(0.28), Inches(1.7), Inches(0.25),
847
+ 7, bold=True, color=C_WHITE, align=PP_ALIGN.RIGHT,
848
+ )
849
+
850
+ def add_slide_header(slide, title_text, slide_num, total):
851
+ add_rect(slide, 0, 0, W, Inches(0.65), C_PURPLE)
852
+ add_text(
853
+ slide, title_text,
854
+ Inches(0.5), Inches(0.1), W - Inches(1), Inches(0.45),
855
+ 19, bold=True, color=C_WHITE,
856
+ )
857
+ add_footer(slide, slide_num, total)
858
  return slide
859
 
860
+ # -------------------------------------------------------------------------
861
+ # Pre-calculate metrics
862
+ # -------------------------------------------------------------------------
863
+ snapshot = context["snapshot"]
864
+ trends = context["trends_30d"]
865
+ status_dist = snapshot["status_distribution"]
866
+ prio_dist = snapshot["priority_distribution"]
867
+ total_tickets = snapshot["total_active_tickets"] or 1
868
+
869
+ csat_vals = list(trends["csat"].values()) if trends["csat"] else []
870
+ avg_csat = round(sum(csat_vals) / len(csat_vals), 1) if csat_vals else 0
871
+
872
+ res_vals = list(trends["resolution_hours"].values()) if trends["resolution_hours"] else []
873
+ avg_res = round(sum(res_vals) / len(res_vals), 1) if res_vals else 0
874
+
875
+ vel_vals = list(trends["velocity"].values()) if trends["velocity"] else []
876
+ avg_vel = round(sum(vel_vals) / len(vel_vals), 1) if vel_vals else 0
877
+
878
+ resolved = status_dist.get("resolved", status_dist.get("RESOLVED", 0))
879
+ closed = status_dist.get("closed", status_dist.get("CLOSED", 0))
880
+ res_rate_pct = round((resolved + closed) / total_tickets * 100) if total_tickets else 0
881
+
882
+ high_prio = (
883
+ prio_dist.get("P0", prio_dist.get("p0", 0))
884
+ + prio_dist.get("P1", prio_dist.get("p1", 0))
885
+ )
886
+
887
+ sections = report.get("sections", [])
888
+ roadmap = report.get("strategic_roadmap", [])
889
+ recent_tickets = context.get("recent_tickets", [])
890
+
891
+ # Total slides: title(1) + TOC(1) + KPI(1) + exec(1) + status(1) + trends(1) + priority(1) + sections + roadmap(1) + signals(1)
892
+ total_slides = 8 + len(sections)
893
+ snum = [0]
894
+
895
+ def ns():
896
+ snum[0] += 1
897
+ return snum[0]
898
+
899
+ # =========================================================================
900
+ # SLIDE 1 — TITLE
901
+ # =========================================================================
902
  slide = prs.slides.add_slide(prs.slide_layouts[6])
903
+ set_bg(slide, C_BG_DARK)
904
+
905
+ # Left accent panel
906
+ add_rect(slide, 0, 0, Inches(4.4), H, C_PURPLE)
907
+ add_rect(slide, Inches(4.4), 0, Inches(0.06), H, C_PURPLE_L)
908
+ add_rect(slide, Inches(4.6), Inches(0.8), Inches(0.03), H - Inches(1.6), RGBColor(80, 40, 150))
909
+
910
+ # Left: brand identity
911
+ add_text(slide, "NEXUS", Inches(0.4), Inches(0.9), Inches(3.8), Inches(1.1),
912
+ 48, bold=True, color=C_WHITE)
913
+ add_text(slide, "AI ORCHESTRATOR", Inches(0.4), Inches(2.0), Inches(3.8), Inches(0.45),
914
+ 12, color=C_PURPLE_L)
915
+ add_rect(slide, Inches(0.4), Inches(2.6), Inches(2.8), Inches(0.04), C_PURPLE_L)
916
+ add_text(slide, "ENTERPRISE STRATEGIC REPORT", Inches(0.4), Inches(2.75), Inches(3.8), Inches(0.4),
917
+ 9.5, color=RGBColor(190, 175, 230))
918
+
919
+ date_str = datetime.now().strftime("%d %B %Y")
920
+ add_text(slide, date_str, Inches(0.4), H - Inches(1.5), Inches(3.8), Inches(0.35),
921
+ 9, color=RGBColor(150, 135, 200))
922
+ add_rect(slide, Inches(0.4), H - Inches(1.05), Inches(1.5), Inches(0.32), C_AMBER)
923
+ add_text(slide, "CONFIDENTIAL", Inches(0.4), H - Inches(1.02), Inches(1.5), Inches(0.28),
924
+ 8, bold=True, color=RGBColor(20, 10, 5), align=PP_ALIGN.CENTER)
925
+
926
+ # Right: report title + meta
927
+ tb = slide.shapes.add_textbox(Inches(4.9), Inches(1.6), Inches(8), Inches(2.8))
928
+ tf = tb.text_frame
929
  tf.word_wrap = True
930
+ p = tf.paragraphs[0]
931
+ p.text = report["title"].upper()
932
+ p.font.size = Pt(34)
933
+ p.font.bold = True
934
+ p.font.color.rgb = C_WHITE
935
  p.line_spacing = 1.2
936
 
937
+ add_text(slide, "Workspace Strategic Narrative", Inches(4.9), Inches(4.6), Inches(8), Inches(0.4),
938
+ 15, color=RGBColor(175, 165, 215))
939
+
940
+ role_display = context["role"].replace("_", " ").upper()
941
+ add_rect(slide, Inches(4.9), Inches(5.2), Inches(4), Inches(0.52), C_PURPLE)
942
+ add_text(slide, f"RECIPIENT: {role_display}", Inches(5.05), Inches(5.28), Inches(3.8), Inches(0.4),
943
+ 11, bold=True, color=C_WHITE)
944
+
945
+ # Bottom KPI strip
946
+ kpi_strip = [
947
+ (str(total_tickets), "TOTAL TICKETS", C_PURPLE_L),
948
+ (f"{avg_csat}/5", "AVG CSAT", C_GREEN if avg_csat >= 4 else C_AMBER),
949
+ (f"{avg_res}h", "AVG RES. TIME", C_AMBER if avg_res > 24 else C_GREEN),
950
+ (str(high_prio), "HIGH PRIORITY", C_RED if high_prio > 5 else C_AMBER),
951
+ ]
952
+ kw = Inches(1.9)
953
+ for i, (val, lbl, col) in enumerate(kpi_strip):
954
+ kx = Inches(4.9) + i * (kw + Inches(0.1))
955
+ add_rect(slide, kx, H - Inches(1.4), kw, Inches(0.85), RGBColor(28, 18, 60))
956
+ add_rect(slide, kx, H - Inches(1.4), kw, Inches(0.06), col)
957
+ add_text(slide, val, kx, H - Inches(1.28), kw, Inches(0.45), 22, bold=True, color=col, align=PP_ALIGN.CENTER)
958
+ add_text(slide, lbl, kx, H - Inches(0.82), kw, Inches(0.28), 7, color=C_MUTED, align=PP_ALIGN.CENTER)
959
+
960
+ ns() # slide 1 counted
961
+
962
+ # =========================================================================
963
+ # SLIDE 2 — TABLE OF CONTENTS
964
+ # =========================================================================
965
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
966
+ set_bg(slide, C_BG)
967
+ add_slide_header(slide, "TABLE OF CONTENTS", ns(), total_slides)
968
+
969
+ toc_items = [
970
+ ("KPI Dashboard", "Key performance indicators at a glance"),
971
+ ("Executive Summary", "Strategic narrative and analytical insight"),
972
+ ("Ticket Status Distribution", "Current workspace ticket health"),
973
+ ("30-Day Trend Analysis", "Velocity, CSAT, and resolution performance"),
974
+ ("Priority & Resource Allocation", "Priority distribution and pressure analysis"),
975
+ ]
976
+ for sec in sections:
977
+ toc_items.append((sec["title"], (sec.get("content", "") or "")[:55] + "..."))
978
+ toc_items.append(("Strategic Roadmap", "Recommended initiatives and action plan"))
979
+ toc_items.append(("Recent Signals Audit", "Latest ticket activity log"))
980
+
981
+ for i, (title, desc) in enumerate(toc_items):
982
+ row_top = Inches(0.85) + i * Inches(0.56)
983
+ num_bg = C_PURPLE if i % 2 == 0 else C_PURPLE_D
984
+ add_rect(slide, Inches(0.35), row_top + Inches(0.06), Inches(0.38), Inches(0.38), num_bg)
985
+ add_text(slide, str(i + 1), Inches(0.35), row_top + Inches(0.07), Inches(0.38), Inches(0.36),
986
+ 12, bold=True, color=C_WHITE, align=PP_ALIGN.CENTER)
987
+ add_text(slide, title, Inches(0.88), row_top + Inches(0.04), Inches(4.8), Inches(0.45),
988
+ 12, bold=True, color=C_DARK)
989
+ add_text(slide, desc[:72], Inches(6.0), row_top + Inches(0.08), Inches(7.0), Inches(0.38),
990
+ 9, color=C_MUTED)
991
+ if i < len(toc_items) - 1:
992
+ add_rect(slide, Inches(0.35), row_top + Inches(0.5), W - Inches(0.7), Inches(0.005),
993
+ RGBColor(218, 212, 238))
994
+
995
+ # =========================================================================
996
+ # SLIDE 3 — KPI DASHBOARD
997
+ # =========================================================================
998
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
999
+ set_bg(slide, C_BG)
1000
+ add_slide_header(slide, "KPI DASHBOARD", ns(), total_slides)
1001
+
1002
+ kpi_cards = [
1003
+ ("TOTAL\nACTIVE TICKETS", str(total_tickets), "All statuses combined", C_PURPLE),
1004
+ ("AVG CSAT\nSCORE", f"{avg_csat}/5", "30-day customer satisfaction", C_GREEN if avg_csat >= 4 else C_AMBER),
1005
+ ("AVG RESOLUTION\nTIME", f"{avg_res}h", "Per ticket, 30-day avg", C_AMBER if avg_res > 24 else C_GREEN),
1006
+ ("HIGH PRIORITY\nCOUNT", str(high_prio), "P0 + P1 combined", C_RED if high_prio > 5 else C_AMBER),
1007
+ ("DAILY TICKET\nVELOCITY", str(avg_vel), "30-day avg per day", C_PURPLE),
1008
+ ("RESOLUTION\nRATE", f"{res_rate_pct}%", "Closed + Resolved", C_GREEN if res_rate_pct >= 60 else C_AMBER),
1009
  ]
1010
+
1011
+ card_w = Inches(2.0)
1012
+ card_h = Inches(2.6)
1013
+ gap = Inches(0.22)
1014
+ start_x = Inches(0.25)
1015
+ card_y = Inches(0.85)
1016
+
1017
+ for i, (label, value, desc, col) in enumerate(kpi_cards):
1018
+ cx = start_x + i * (card_w + gap)
1019
+ # Shadow
1020
+ add_rect(slide, cx + Inches(0.05), card_y + Inches(0.05), card_w, card_h, RGBColor(210, 204, 232))
1021
+ # Card
1022
+ add_rect(slide, cx, card_y, card_w, card_h, C_CARD)
1023
+ # Top color stripe
1024
+ add_rect(slide, cx, card_y, card_w, Inches(0.09), col)
1025
+ # Value
1026
+ add_text(slide, value, cx + Inches(0.1), card_y + Inches(0.18), card_w - Inches(0.2), Inches(0.95),
1027
+ 28, bold=True, color=col, align=PP_ALIGN.CENTER)
1028
+ # Label
1029
+ tb_lbl = slide.shapes.add_textbox(cx + Inches(0.1), card_y + Inches(1.1), card_w - Inches(0.2), Inches(0.8))
1030
+ tf_lbl = tb_lbl.text_frame
1031
+ tf_lbl.word_wrap = True
1032
+ p_lbl = tf_lbl.paragraphs[0]
1033
+ p_lbl.text = label
1034
+ p_lbl.font.size = Pt(9.5)
1035
+ p_lbl.font.bold = True
1036
+ p_lbl.font.color.rgb = C_DARK
1037
+ p_lbl.alignment = PP_ALIGN.CENTER
1038
+ # Desc
1039
+ add_text(slide, desc, cx + Inches(0.1), card_y + Inches(2.0), card_w - Inches(0.2), Inches(0.38),
1040
+ 7.5, color=C_MUTED, align=PP_ALIGN.CENTER)
1041
+
1042
+ # Trend summary below cards
1043
+ add_rect(slide, Inches(0.25), Inches(3.65), W - Inches(0.5), Inches(0.05), RGBColor(220, 214, 240))
1044
+
1045
+ status_summary_items = [(k.upper(), v) for k, v in list(status_dist.items())[:5]]
1046
+ status_colors = [C_PURPLE, C_GREEN, C_AMBER, C_BLUE, C_RED]
1047
+ legend_x = Inches(0.3)
1048
+ add_text(slide, "STATUS DISTRIBUTION:", legend_x, Inches(3.82), Inches(2.2), Inches(0.35),
1049
+ 9, bold=True, color=C_MUTED)
1050
+ for j, ((st, cnt), col) in enumerate(zip(status_summary_items, status_colors)):
1051
+ bx = Inches(2.6) + j * Inches(2.1)
1052
+ add_rect(slide, bx, Inches(3.9), Inches(0.18), Inches(0.18), col)
1053
+ add_text(slide, f"{st}: {cnt}", bx + Inches(0.25), Inches(3.85), Inches(1.8), Inches(0.3),
1054
+ 9, color=C_DARK)
1055
+
1056
+ # =========================================================================
1057
+ # SLIDE 4 — EXECUTIVE SUMMARY
1058
+ # =========================================================================
1059
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
1060
+ set_bg(slide, C_BG)
1061
+ add_slide_header(slide, "EXECUTIVE SUMMARY", ns(), total_slides)
1062
+
1063
+ # Summary text
1064
+ tb_sum = slide.shapes.add_textbox(Inches(0.5), Inches(0.85), Inches(8.0), Inches(5.8))
1065
+ tf_sum = tb_sum.text_frame
1066
+ tf_sum.word_wrap = True
1067
+ p_sum = tf_sum.paragraphs[0]
1068
+ p_sum.text = report["executive_summary"]
1069
+ p_sum.font.size = Pt(12.5)
1070
+ p_sum.font.color.rgb = C_DARK
1071
+ p_sum.line_spacing = 1.45
1072
+
1073
+ # Right: insight callout
1074
+ add_rect(slide, Inches(8.85), Inches(0.85), Inches(4.15), Inches(3.1), C_ACCENT)
1075
+ add_rect(slide, Inches(8.85), Inches(0.85), Inches(0.08), Inches(3.1), C_PURPLE)
1076
+ add_text(slide, "KEY INSIGHT", Inches(9.05), Inches(0.98), Inches(3.8), Inches(0.35),
1077
+ 8.5, bold=True, color=C_PURPLE)
1078
+ tb_ins = slide.shapes.add_textbox(Inches(9.05), Inches(1.45), Inches(3.8), Inches(2.3))
1079
+ tf_ins = tb_ins.text_frame
1080
+ tf_ins.word_wrap = True
1081
+ p_ins = tf_ins.paragraphs[0]
1082
+ p_ins.text = report.get("analytical_insight", "")
1083
+ p_ins.font.size = Pt(11.5)
1084
+ p_ins.font.italic = True
1085
+ p_ins.font.color.rgb = C_PURPLE_D
1086
+ p_ins.line_spacing = 1.35
1087
+
1088
+ # Right: status snapshot box
1089
+ add_rect(slide, Inches(8.85), Inches(4.1), Inches(4.15), Inches(2.55), C_CARD)
1090
+ add_rect(slide, Inches(8.85), Inches(4.1), Inches(4.15), Inches(0.07), C_PURPLE)
1091
+ add_text(slide, "STATUS SNAPSHOT", Inches(9.05), Inches(4.22), Inches(3.8), Inches(0.32),
1092
+ 8.5, bold=True, color=C_PURPLE)
1093
+
1094
+ st_colors = [C_PURPLE, C_GREEN, C_AMBER, C_BLUE, C_RED]
1095
+ for j, (st, cnt) in enumerate(list(status_dist.items())[:4]):
1096
+ sy = Inches(4.65) + j * Inches(0.45)
1097
+ add_rect(slide, Inches(9.05), sy + Inches(0.08), Inches(0.14), Inches(0.14), st_colors[j % 5])
1098
+ add_text(slide, st.upper(), Inches(9.28), sy, Inches(2.3), Inches(0.35), 10, bold=True, color=C_DARK)
1099
+ add_text(slide, str(cnt), Inches(11.7), sy, Inches(1.1), Inches(0.35), 10, bold=True,
1100
+ color=st_colors[j % 5], align=PP_ALIGN.RIGHT)
1101
+
1102
+ # =========================================================================
1103
+ # SLIDE 5 — STATUS DISTRIBUTION (native bar chart)
1104
+ # =========================================================================
1105
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
1106
+ set_bg(slide, C_BG)
1107
+ add_slide_header(slide, "TICKET STATUS DISTRIBUTION", ns(), total_slides)
1108
+
1109
+ if status_dist:
1110
+ chart_data = CategoryChartData()
1111
+ chart_data.categories = [k.upper() for k in status_dist.keys()]
1112
+ chart_data.add_series("Tickets", list(status_dist.values()))
1113
+
1114
+ chart_frame = slide.shapes.add_chart(
1115
+ XL_CHART_TYPE.COLUMN_CLUSTERED,
1116
+ Inches(0.4), Inches(0.85),
1117
+ Inches(8.5), Inches(5.8),
1118
+ chart_data,
1119
+ )
1120
+ chart = chart_frame.chart
1121
+ chart.has_legend = False
1122
+ chart.has_title = False
1123
+ try:
1124
+ for series in chart.plots[0].series:
1125
+ series.format.fill.solid()
1126
+ series.format.fill.fore_color.rgb = C_PURPLE
1127
+ chart.value_axis.has_major_gridlines = True
1128
+ chart.category_axis.tick_labels.font.size = Pt(11)
1129
+ chart.category_axis.tick_labels.font.bold = True
1130
+ except Exception:
1131
+ pass
1132
+
1133
+ # Right breakdown panel
1134
+ add_rect(slide, Inches(9.2), Inches(0.85), Inches(3.85), Inches(5.8), C_CARD)
1135
+ add_rect(slide, Inches(9.2), Inches(0.85), Inches(3.85), Inches(0.07), C_PURPLE)
1136
+ add_text(slide, "BREAKDOWN", Inches(9.4), Inches(0.98), Inches(3.4), Inches(0.35),
1137
+ 10.5, bold=True, color=C_PURPLE)
1138
+
1139
+ total_st = sum(status_dist.values()) or 1
1140
+ st_colors2 = [C_PURPLE, C_GREEN, C_AMBER, C_RED, C_BLUE]
1141
+ for j, (st, cnt) in enumerate(status_dist.items()):
1142
+ pct = round(cnt / total_st * 100)
1143
+ ry = Inches(1.52) + j * Inches(0.82)
1144
+ col = st_colors2[j % 5]
1145
+ add_rect(slide, Inches(9.4), ry, Inches(0.16), Inches(0.5), col)
1146
+ add_text(slide, st.upper(), Inches(9.68), ry, Inches(2.8), Inches(0.3), 10, bold=True, color=C_DARK)
1147
+ add_text(slide, f"{cnt} tickets ({pct}%)", Inches(9.68), ry + Inches(0.28), Inches(2.8), Inches(0.25),
1148
+ 9, color=C_MUTED)
1149
+
1150
+ # =========================================================================
1151
+ # SLIDE 6 — 30-DAY TRENDS (3 native line charts)
1152
+ # =========================================================================
1153
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
1154
+ set_bg(slide, C_BG)
1155
+ add_slide_header(slide, "30-DAY ANALYTICAL TRENDS", ns(), total_slides)
1156
+
1157
+ def _sample(d, max_pts=14):
1158
+ if not d:
1159
+ return [], []
1160
+ keys, vals = list(d.keys()), list(d.values())
1161
+ step = max(1, len(keys) // max_pts)
1162
+ sk = keys[::step]
1163
+ sv = vals[::step]
1164
+ return [k[5:] for k in sk], sv # MM-DD labels
1165
+
1166
+ # Velocity (top left)
1167
+ vel_labels, vel_data = _sample(trends["velocity"])
1168
+ if vel_labels:
1169
+ cd_vel = CategoryChartData()
1170
+ cd_vel.categories = vel_labels
1171
+ cd_vel.add_series("Daily Volume", vel_data)
1172
+ ch_vel = slide.shapes.add_chart(
1173
+ XL_CHART_TYPE.LINE_MARKERS, Inches(0.3), Inches(0.8), Inches(6.2), Inches(2.9), cd_vel
1174
+ ).chart
1175
+ ch_vel.has_legend = False
1176
+ ch_vel.has_title = True
1177
+ ch_vel.chart_title.text_frame.text = "Ticket Velocity (Daily Volume)"
1178
+ ch_vel.chart_title.text_frame.paragraphs[0].font.size = Pt(10)
1179
+ try:
1180
+ for s in ch_vel.plots[0].series:
1181
+ s.format.line.color.rgb = C_PURPLE
1182
+ s.format.line.width = Pt(1.8)
1183
+ except Exception:
1184
+ pass
1185
+
1186
+ # CSAT (top right)
1187
+ csat_labels, csat_data = _sample(trends["csat"])
1188
+ if csat_labels:
1189
+ cd_csat = CategoryChartData()
1190
+ cd_csat.categories = csat_labels
1191
+ cd_csat.add_series("CSAT Rating", csat_data)
1192
+ ch_csat = slide.shapes.add_chart(
1193
+ XL_CHART_TYPE.LINE_MARKERS, Inches(6.8), Inches(0.8), Inches(6.2), Inches(2.9), cd_csat
1194
+ ).chart
1195
+ ch_csat.has_legend = False
1196
+ ch_csat.has_title = True
1197
+ ch_csat.chart_title.text_frame.text = "CSAT Trend (Avg Rating)"
1198
+ ch_csat.chart_title.text_frame.paragraphs[0].font.size = Pt(10)
1199
+ try:
1200
+ for s in ch_csat.plots[0].series:
1201
+ s.format.line.color.rgb = C_GREEN
1202
+ s.format.line.width = Pt(1.8)
1203
+ except Exception:
1204
+ pass
1205
+
1206
+ # Resolution time (bottom full width)
1207
+ res_labels, res_data = _sample(trends["resolution_hours"])
1208
+ if res_labels:
1209
+ cd_res = CategoryChartData()
1210
+ cd_res.categories = res_labels
1211
+ cd_res.add_series("Avg Hours", res_data)
1212
+ ch_res = slide.shapes.add_chart(
1213
+ XL_CHART_TYPE.LINE_MARKERS, Inches(0.3), Inches(3.9), Inches(12.7), Inches(2.8), cd_res
1214
+ ).chart
1215
+ ch_res.has_legend = False
1216
+ ch_res.has_title = True
1217
+ ch_res.chart_title.text_frame.text = "Resolution Performance — Avg Hours per Day (30-Day Window)"
1218
+ ch_res.chart_title.text_frame.paragraphs[0].font.size = Pt(10)
1219
+ try:
1220
+ for s in ch_res.plots[0].series:
1221
+ s.format.line.color.rgb = C_AMBER
1222
+ s.format.line.width = Pt(1.8)
1223
+ except Exception:
1224
+ pass
1225
+
1226
+ # =========================================================================
1227
+ # SLIDE 7 — PRIORITY ANALYSIS (native bar chart)
1228
+ # =========================================================================
1229
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
1230
+ set_bg(slide, C_BG)
1231
+ add_slide_header(slide, "PRIORITY & RESOURCE ALLOCATION", ns(), total_slides)
1232
+
1233
+ if prio_dist:
1234
+ cd_prio = CategoryChartData()
1235
+ cd_prio.categories = [k.upper() for k in prio_dist.keys()]
1236
+ cd_prio.add_series("Count", list(prio_dist.values()))
1237
+ ch_prio = slide.shapes.add_chart(
1238
+ XL_CHART_TYPE.COLUMN_CLUSTERED, Inches(0.4), Inches(0.85), Inches(7.8), Inches(5.8), cd_prio
1239
+ ).chart
1240
+ ch_prio.has_legend = False
1241
+ ch_prio.has_title = True
1242
+ ch_prio.chart_title.text_frame.text = "Current Priority Volume"
1243
+ ch_prio.chart_title.text_frame.paragraphs[0].font.size = Pt(11)
1244
+ try:
1245
+ for s in ch_prio.plots[0].series:
1246
+ s.format.fill.solid()
1247
+ s.format.fill.fore_color.rgb = C_AMBER
1248
+ except Exception:
1249
+ pass
1250
+
1251
+ # Right: priority intelligence
1252
+ add_rect(slide, Inches(8.5), Inches(0.85), Inches(4.55), Inches(5.8), C_CARD)
1253
+ add_rect(slide, Inches(8.5), Inches(0.85), Inches(4.55), Inches(0.07), C_AMBER)
1254
+ add_text(slide, "PRIORITY INTELLIGENCE", Inches(8.7), Inches(0.98), Inches(4.2), Inches(0.35),
1255
+ 10.5, bold=True, color=RGBColor(*BRAND_AMBER))
1256
+
1257
+ total_prio = sum(prio_dist.values()) or 1
1258
+ prio_c_map = {
1259
+ "P0": C_RED, "p0": C_RED,
1260
+ "P1": C_AMBER, "p1": C_AMBER,
1261
+ "P2": C_GREEN, "p2": C_GREEN,
1262
+ "P3": C_BLUE, "p3": C_BLUE,
1263
+ }
1264
+ for j, (prio, cnt) in enumerate(prio_dist.items()):
1265
+ pct = round(cnt / total_prio * 100)
1266
+ py = Inches(1.55) + j * Inches(0.98)
1267
+ col = prio_c_map.get(prio, C_PURPLE)
1268
+ add_text(slide, prio.upper(), Inches(8.7), py, Inches(0.8), Inches(0.38),
1269
+ 12, bold=True, color=col)
1270
+ bar_fill = Inches(3.5) * (pct / 100)
1271
+ add_rect(slide, Inches(9.6), py + Inches(0.1), Inches(3.2), Inches(0.2), RGBColor(230, 224, 242))
1272
+ if bar_fill > 0:
1273
+ add_rect(slide, Inches(9.6), py + Inches(0.1), bar_fill, Inches(0.2), col)
1274
+ add_text(slide, f"{cnt} ({pct}%)", Inches(12.9), py, Inches(0.9), Inches(0.38),
1275
+ 9, color=C_MUTED, align=PP_ALIGN.RIGHT)
1276
+
1277
+ # =========================================================================
1278
+ # ROLE-SPECIFIC SECTION SLIDES
1279
+ # =========================================================================
1280
+ for i, section in enumerate(sections):
1281
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
1282
+ set_bg(slide, C_BG)
1283
+ add_slide_header(slide, section["title"].upper(), ns(), total_slides)
1284
+
1285
+ # Section badge
1286
+ add_rect(slide, Inches(0.3), Inches(0.72), Inches(0.55), Inches(0.55), C_PURPLE_D)
1287
+ add_text(slide, str(8 + i), Inches(0.3), Inches(0.74), Inches(0.55), Inches(0.5),
1288
+ 12, bold=True, color=C_WHITE, align=PP_ALIGN.CENTER)
1289
+
1290
+ # Content (left 60%)
1291
+ content = section.get("content", "")
1292
+ tb_c = slide.shapes.add_textbox(Inches(0.5), Inches(1.45), Inches(7.8), Inches(5.5))
1293
+ tf_c = tb_c.text_frame
1294
+ tf_c.word_wrap = True
1295
+ p_c = tf_c.paragraphs[0]
1296
+ p_c.text = content
1297
+ p_c.font.size = Pt(12)
1298
+ p_c.font.color.rgb = C_DARK
1299
+ p_c.line_spacing = 1.5
1300
+
1301
+ # Highlights panel (right 35%)
1302
+ add_rect(slide, Inches(8.6), Inches(0.72), Inches(4.45), Inches(6.26), C_CARD)
1303
+ add_rect(slide, Inches(8.6), Inches(0.72), Inches(0.07), Inches(6.26), C_PURPLE)
1304
+ add_text(slide, "KEY HIGHLIGHTS", Inches(8.82), Inches(0.84), Inches(4.0), Inches(0.38),
1305
+ 10, bold=True, color=C_PURPLE)
1306
+
1307
+ highlights = section.get("highlights", [])[:6]
1308
+ for j, hl in enumerate(highlights):
1309
+ hy = Inches(1.38) + j * Inches(0.78)
1310
+ dot_col = C_PURPLE if j % 2 == 0 else C_AMBER
1311
+ add_rect(slide, Inches(8.82), hy + Inches(0.1), Inches(0.12), Inches(0.12), dot_col)
1312
+ tb_hl = slide.shapes.add_textbox(Inches(9.08), hy, Inches(3.82), Inches(0.72))
1313
+ tf_hl = tb_hl.text_frame
1314
+ tf_hl.word_wrap = True
1315
+ p_hl = tf_hl.paragraphs[0]
1316
+ p_hl.text = hl
1317
+ p_hl.font.size = Pt(10)
1318
+ p_hl.font.color.rgb = C_DARK
1319
+ p_hl.line_spacing = 1.25
1320
+
1321
+ # =========================================================================
1322
+ # ROADMAP SLIDE
1323
+ # =========================================================================
1324
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
1325
+ set_bg(slide, C_BG)
1326
+ add_slide_header(slide, "STRATEGIC ROADMAP", ns(), total_slides)
1327
+
1328
+ if roadmap:
1329
+ num = min(len(roadmap), 5)
1330
+ card_w = (W - Inches(0.9)) / num - Inches(0.18)
1331
+ phase_colors = [C_PURPLE, C_PURPLE_D, C_BLUE, C_GREEN, C_AMBER]
1332
+
1333
+ for i, item in enumerate(roadmap[:num]):
1334
+ cx = Inches(0.4) + i * (card_w + Inches(0.18))
1335
+ col = phase_colors[i % len(phase_colors)]
1336
+
1337
+ # Phase header
1338
+ add_rect(slide, cx, Inches(1.0), card_w, Inches(0.65), col)
1339
+ add_text(slide, f"PHASE {i + 1}", cx, Inches(1.1), card_w, Inches(0.45),
1340
+ 11, bold=True, color=C_WHITE, align=PP_ALIGN.CENTER)
1341
+
1342
+ # Arrow connector
1343
+ if i < num - 1:
1344
+ add_rect(slide, cx + card_w + Inches(0.02), Inches(1.25), Inches(0.14), Inches(0.14), C_AMBER)
1345
+
1346
+ # Content card
1347
+ add_rect(slide, cx, Inches(1.65), card_w, Inches(5.2), C_CARD)
1348
+ add_rect(slide, cx, Inches(1.65), card_w, Inches(0.05), col)
1349
+
1350
+ tb_rm = slide.shapes.add_textbox(
1351
+ cx + Inches(0.18), Inches(1.82), card_w - Inches(0.36), Inches(4.8)
1352
+ )
1353
+ tf_rm = tb_rm.text_frame
1354
+ tf_rm.word_wrap = True
1355
+ p_rm = tf_rm.paragraphs[0]
1356
+ p_rm.text = item
1357
+ p_rm.font.size = Pt(10)
1358
+ p_rm.font.color.rgb = C_DARK
1359
+ p_rm.line_spacing = 1.4
1360
+
1361
+ # =========================================================================
1362
+ # RECENT SIGNALS SLIDE
1363
+ # =========================================================================
1364
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
1365
+ set_bg(slide, C_BG)
1366
+ add_slide_header(slide, "RECENT SIGNALS AUDIT", ns(), total_slides)
1367
+
1368
+ tickets_to_show = recent_tickets[:12]
1369
+ if tickets_to_show:
1370
+ rows = len(tickets_to_show) + 1
1371
+ tbl = slide.shapes.add_table(
1372
+ rows, 5, Inches(0.3), Inches(0.82), W - Inches(0.6), Inches(6.25)
1373
+ ).table
1374
+
1375
+ col_widths = [Inches(1.3), Inches(6.5), Inches(2.2), Inches(1.5), Inches(1.5)]
1376
+ headers = ["TICKET ID", "TITLE", "STATUS", "PRIORITY", "CREATED"]
1377
+ for j, (hdr, cw) in enumerate(zip(headers, col_widths)):
1378
+ tbl.columns[j].width = cw
1379
+ cell = tbl.cell(0, j)
1380
+ cell.text = hdr
1381
+ cell.fill.solid()
1382
+ cell.fill.fore_color.rgb = C_PURPLE
1383
+ p = cell.text_frame.paragraphs[0]
1384
+ p.font.color.rgb = C_WHITE
1385
+ p.font.bold = True
1386
+ p.font.size = Pt(10)
1387
+ p.alignment = PP_ALIGN.CENTER
1388
+
1389
+ st_c_map = {
1390
+ "open": C_RED, "in_progress": C_AMBER,
1391
+ "acknowledged": C_BLUE, "resolved": C_GREEN, "closed": C_MUTED,
1392
+ }
1393
+ pr_c_map = {
1394
+ "p0": C_RED, "p1": C_AMBER, "p2": C_GREEN, "p3": C_BLUE,
1395
+ }
1396
+
1397
+ for r_i, t in enumerate(tickets_to_show):
1398
+ row_bg = RGBColor(247, 245, 254) if r_i % 2 == 0 else C_CARD
1399
+ cells_data = [
1400
+ t.get("id", "")[:8],
1401
+ (t.get("title", "") or "")[:70],
1402
+ t.get("status", "").upper(),
1403
+ t.get("priority", "").upper(),
1404
+ (t.get("created_at", "") or "")[:10],
1405
+ ]
1406
+ for c_i, txt in enumerate(cells_data):
1407
+ cell = tbl.cell(r_i + 1, c_i)
1408
  cell.fill.solid()
1409
+ cell.fill.fore_color.rgb = row_bg
1410
+ cell.text = str(txt)
1411
+ p = cell.text_frame.paragraphs[0]
1412
+ p.font.size = Pt(9.5)
1413
+ p.alignment = PP_ALIGN.LEFT if c_i == 1 else PP_ALIGN.CENTER
1414
+ if c_i == 2:
1415
+ p.font.color.rgb = st_c_map.get(t.get("status", "").lower(), C_DARK)
1416
+ p.font.bold = True
1417
+ elif c_i == 3:
1418
+ p.font.color.rgb = pr_c_map.get(t.get("priority", "").lower(), C_DARK)
1419
+ p.font.bold = True
1420
+ else:
1421
+ p.font.color.rgb = C_DARK
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1422
 
1423
  pptx_io = io.BytesIO()
1424
  prs.save(pptx_io)