-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreporter.py
More file actions
1147 lines (979 loc) · 38 KB
/
Copy pathreporter.py
File metadata and controls
1147 lines (979 loc) · 38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
reporter.py — PDF report generation for the Excel Workbook Risk Diagnostic Tool.
Produces a structured multi-page PDF report using ReportLab Platypus.
Report structure:
1. Cover page — filename, timestamp, RAG badge, finding counts
2. Executive summary — auto-generated plain-English paragraph
3. Findings by category — one section per checker category
4. High-sensitivity sheets summary
5. Appendix — full tabular listing sorted by severity descending
"""
from __future__ import annotations
import io
from collections import Counter, defaultdict
from datetime import datetime
from pathlib import Path
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import cm, mm
from reportlab.platypus import (
HRFlowable,
NextPageTemplate,
PageBreak,
Paragraph,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
from reportlab.platypus.frames import Frame
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
import settings
from models import Finding, WorkbookAnalysisResult, AICommentary
# ---------------------------------------------------------------------------
# Colour palette
# ---------------------------------------------------------------------------
_COLOUR_RED = colors.HexColor("#C0392B")
_COLOUR_AMBER = colors.HexColor("#E67E22")
_COLOUR_GREEN = colors.HexColor("#27AE60")
_COLOUR_HIGH = colors.HexColor("#FADBD8") # Light red background
_COLOUR_HIGH_BORDER = colors.HexColor("#C0392B")
_COLOUR_MEDIUM = colors.HexColor("#FDEBD0") # Light orange background
_COLOUR_MEDIUM_BORDER = colors.HexColor("#E67E22")
_COLOUR_LOW = colors.HexColor("#D5F5E3") # Light green background
_COLOUR_LOW_BORDER = colors.HexColor("#27AE60")
_COLOUR_HEADER_BG = colors.HexColor("#2C3E50") # Dark slate header
_COLOUR_HEADER_TEXT = colors.white
_COLOUR_ROW_ALT = colors.HexColor("#F8F9FA") # Alternate row tint
_COLOUR_LIGHT_GREY = colors.HexColor("#ECF0F1")
_COLOUR_TEXT = colors.HexColor("#2C3E50")
_COLOUR_AI_BLUE = colors.HexColor("#EBF4FF") # AI purpose/sheets background
_COLOUR_AI_YELLOW = colors.HexColor("#FFFDE7") # AI assumptions background
_COLOUR_AI_LABEL = colors.HexColor("#7F8C8D") # AI label text (grey)
# ---------------------------------------------------------------------------
# Page dimensions
# ---------------------------------------------------------------------------
PAGE_WIDTH, PAGE_HEIGHT = A4
LEFT_MARGIN = 2 * cm
RIGHT_MARGIN = 2 * cm
TOP_MARGIN = 2 * cm
BOTTOM_MARGIN = 2 * cm
# ---------------------------------------------------------------------------
# Styles
# ---------------------------------------------------------------------------
_BASE_STYLES = getSampleStyleSheet()
def _build_styles() -> dict[str, ParagraphStyle]:
"""
Build and return a dictionary of named ParagraphStyle objects used
throughout the report.
Returns:
Dict mapping style name to ParagraphStyle.
"""
styles: dict[str, ParagraphStyle] = {}
styles["cover_title"] = ParagraphStyle(
"cover_title",
fontName="Helvetica-Bold",
fontSize=22,
textColor=_COLOUR_TEXT,
spaceAfter=8,
alignment=TA_CENTER,
)
styles["cover_subtitle"] = ParagraphStyle(
"cover_subtitle",
fontName="Helvetica",
fontSize=12,
textColor=colors.HexColor("#7F8C8D"),
spaceAfter=4,
alignment=TA_CENTER,
)
styles["cover_rag"] = ParagraphStyle(
"cover_rag",
fontName="Helvetica-Bold",
fontSize=28,
textColor=colors.white,
alignment=TA_CENTER,
)
styles["section_heading"] = ParagraphStyle(
"section_heading",
fontName="Helvetica-Bold",
fontSize=14,
textColor=_COLOUR_TEXT,
spaceBefore=14,
spaceAfter=6,
borderPad=4,
)
styles["subsection_heading"] = ParagraphStyle(
"subsection_heading",
fontName="Helvetica-Bold",
fontSize=11,
textColor=_COLOUR_TEXT,
spaceBefore=10,
spaceAfter=4,
)
styles["body"] = ParagraphStyle(
"body_text",
fontName="Helvetica",
fontSize=9,
textColor=_COLOUR_TEXT,
spaceAfter=4,
leading=13,
)
styles["body_italic"] = ParagraphStyle(
"body_italic",
fontName="Helvetica-Oblique",
fontSize=9,
textColor=colors.HexColor("#7F8C8D"),
spaceAfter=4,
leading=13,
)
styles["cell_small"] = ParagraphStyle(
"cell_small",
fontName="Helvetica",
fontSize=8,
textColor=_COLOUR_TEXT,
leading=10,
wordWrap="CJK",
)
styles["cell_small_bold"] = ParagraphStyle(
"cell_small_bold",
fontName="Helvetica-Bold",
fontSize=8,
textColor=_COLOUR_TEXT,
leading=10,
)
styles["cell_mono"] = ParagraphStyle(
"cell_mono",
fontName="Courier",
fontSize=7,
textColor=_COLOUR_TEXT,
leading=9,
wordWrap="CJK",
)
styles["table_header"] = ParagraphStyle(
"table_header",
fontName="Helvetica-Bold",
fontSize=8,
textColor=colors.white,
leading=10,
)
return styles
_STYLES = _build_styles()
# ---------------------------------------------------------------------------
# RAG helpers
# ---------------------------------------------------------------------------
def _rag_colour(rag: str) -> colors.Color:
"""
Map a RAG rating string to its ReportLab colour.
Args:
rag: "Red", "Amber", or "Green".
Returns:
ReportLab Color object.
"""
return {"Red": _COLOUR_RED, "Amber": _COLOUR_AMBER, "Green": _COLOUR_GREEN}.get(
rag, _COLOUR_LIGHT_GREY
)
def _severity_bg_colour(severity: str) -> colors.Color:
"""Return the background colour for a severity badge cell."""
return {
"High": _COLOUR_HIGH,
"Medium": _COLOUR_MEDIUM,
"Low": _COLOUR_LOW,
}.get(severity, _COLOUR_LIGHT_GREY)
def _severity_text_colour(severity: str) -> colors.Color:
"""Return the text/border colour for a severity badge."""
return {
"High": _COLOUR_HIGH_BORDER,
"Medium": _COLOUR_MEDIUM_BORDER,
"Low": _COLOUR_LOW_BORDER,
}.get(severity, _COLOUR_TEXT)
# ---------------------------------------------------------------------------
# Executive summary generator
# ---------------------------------------------------------------------------
def _generate_executive_summary(result: WorkbookAnalysisResult) -> str:
"""
Build a plain-English executive summary paragraph from the analysis
findings. Generated programmatically from finding aggregates — no
hardcoded template text.
Args:
result: The completed WorkbookAnalysisResult.
Returns:
Multi-sentence summary string.
"""
if result.error_message:
return (
f"This workbook could not be analysed: {result.error_message} "
"No automated findings are available."
)
counts = result.count_by_severity()
total = len(result.findings)
n_high = counts["High"]
n_medium = counts["Medium"]
n_low = counts["Low"]
# Sentence 1: overall finding count
if total == 0:
return (
f"No risk findings were detected in '{result.filename}'. "
f"The workbook achieved a risk score of {result.total_score} "
f"({result.rag_rating} rating)."
)
parts: list[str] = []
parts.append(
f"Analysis of '{result.filename}' identified {total} finding(s): "
f"{n_high} High, {n_medium} Medium, and {n_low} Low severity. "
f"The overall risk score is {result.total_score} "
f"({result.rag_rating} rating)."
)
# Sentence 2: top categories
cat_counts: Counter = Counter(f.category for f in result.findings)
top_cats = [cat for cat, _ in cat_counts.most_common(3)]
if top_cats:
parts.append(
f"The most prevalent risk categories are: "
f"{', '.join(top_cats)}."
)
# Sentence 3: high-severity specific mention
if n_high > 0:
high_cats = Counter(
f.category for f in result.findings if f.severity == "High"
)
top_high = [cat for cat, _ in high_cats.most_common(2)]
parts.append(
f"Immediate attention is recommended for {n_high} High-severity "
f"finding(s), particularly in the "
f"{' and '.join(top_high)} category(ies)."
)
# Sentence 4: sensitive sheets
if result.high_sensitivity_sheets:
sheets = ", ".join(f"'{s}'" for s in result.high_sensitivity_sheets[:4])
if len(result.high_sensitivity_sheets) > 4:
sheets += f" and {len(result.high_sensitivity_sheets) - 4} more"
parts.append(
f"The following sheets were identified as actuarially sensitive "
f"and warrant heightened review: {sheets}."
)
# Sentence 5: VBA note
vba_findings = [f for f in result.findings if f.category == "VBA"]
if vba_findings:
dangerous = [f for f in vba_findings if f.severity == "High"]
if dangerous:
parts.append(
f"The workbook contains VBA macros with {len(dangerous)} "
f"High-severity finding(s) including potentially dangerous "
f"commands or error suppression. VBA code should be reviewed "
f"by a developer before the model is used in production."
)
else:
parts.append(
"The workbook contains VBA macros. While no dangerous commands "
"were detected, all macro code should be reviewed and documented."
)
return " ".join(parts)
# ---------------------------------------------------------------------------
# Table builders
# ---------------------------------------------------------------------------
def _make_summary_table(result: WorkbookAnalysisResult) -> Table:
"""
Build a 2×4 summary table showing finding counts by severity.
Args:
result: WorkbookAnalysisResult.
Returns:
ReportLab Table flowable.
"""
counts = result.count_by_severity()
data = [
[
Paragraph("Severity", _STYLES["table_header"]),
Paragraph("Count", _STYLES["table_header"]),
Paragraph("Score Contribution", _STYLES["table_header"]),
],
[
Paragraph("High", _STYLES["cell_small_bold"]),
Paragraph(str(counts["High"]), _STYLES["cell_small"]),
Paragraph(
str(counts["High"] * settings.SEVERITY_WEIGHTS["High"]),
_STYLES["cell_small"],
),
],
[
Paragraph("Medium", _STYLES["cell_small_bold"]),
Paragraph(str(counts["Medium"]), _STYLES["cell_small"]),
Paragraph(
str(counts["Medium"] * settings.SEVERITY_WEIGHTS["Medium"]),
_STYLES["cell_small"],
),
],
[
Paragraph("Low", _STYLES["cell_small_bold"]),
Paragraph(str(counts["Low"]), _STYLES["cell_small"]),
Paragraph(
str(counts["Low"] * settings.SEVERITY_WEIGHTS["Low"]),
_STYLES["cell_small"],
),
],
[
Paragraph("Total", _STYLES["cell_small_bold"]),
Paragraph(str(len(result.findings)), _STYLES["cell_small_bold"]),
Paragraph(str(result.total_score), _STYLES["cell_small_bold"]),
],
]
col_widths = [4 * cm, 3 * cm, 5 * cm]
t = Table(data, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), _COLOUR_HEADER_BG),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("BACKGROUND", (0, 1), (-1, 1), _COLOUR_HIGH),
("BACKGROUND", (0, 2), (-1, 2), _COLOUR_MEDIUM),
("BACKGROUND", (0, 3), (-1, 3), _COLOUR_LOW),
("BACKGROUND", (0, 4), (-1, 4), _COLOUR_LIGHT_GREY),
("FONTNAME", (0, 4), (-1, 4), "Helvetica-Bold"),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#BDC3C7")),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("ROWBACKGROUNDS", (0, 0), (-1, -1), [None]), # Disable auto alternation
]))
return t
def _make_findings_table(findings: list[Finding]) -> Table:
"""
Build a detailed findings table with columns:
Severity | Sheet | Cell | Finding Name | Description | Explanation
Args:
findings: List of Finding objects to include.
Returns:
ReportLab Table flowable.
"""
if not findings:
return Table([[Paragraph("No findings in this category.", _STYLES["body_italic"])]])
header = [
Paragraph("Sev.", _STYLES["table_header"]),
Paragraph("Sheet", _STYLES["table_header"]),
Paragraph("Cell", _STYLES["table_header"]),
Paragraph("Finding", _STYLES["table_header"]),
Paragraph("Description", _STYLES["table_header"]),
]
usable_width = PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN
col_widths = [
1.4 * cm, # Severity
3.2 * cm, # Sheet
1.5 * cm, # Cell
3.5 * cm, # Finding name
usable_width - (1.4 + 3.2 + 1.5 + 3.5) * cm, # Description (remainder)
]
rows = [header]
style_commands = [
("BACKGROUND", (0, 0), (-1, 0), _COLOUR_HEADER_BG),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, 0), 8),
("GRID", (0, 0), (-1, -1), 0.3, colors.HexColor("#BDC3C7")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("ROWBACKGROUNDS", (1, 1), (-1, -1), [colors.white, _COLOUR_ROW_ALT]),
]
severity_order = {"High": 0, "Medium": 1, "Low": 2}
sorted_findings = sorted(
findings,
key=lambda f: (severity_order.get(f.severity, 3), f.check_id),
)
for i, f in enumerate(sorted_findings, start=1):
sev_para = Paragraph(
f"<b>{f.severity}</b>", _STYLES["cell_small_bold"]
)
sheet_para = Paragraph(
_escape_xml(f.sheet_name[:30]), _STYLES["cell_small"]
)
cell_para = Paragraph(
_escape_xml(f.cell_ref[:12]), _STYLES["cell_mono"]
)
name_para = Paragraph(
_escape_xml(f.name), _STYLES["cell_small_bold"]
)
desc_para = Paragraph(
_escape_xml(f.description[:300]), _STYLES["cell_small"]
)
rows.append([sev_para, sheet_para, cell_para, name_para, desc_para])
bg = _severity_bg_colour(f.severity)
style_commands.append(("BACKGROUND", (0, i), (0, i), bg))
style_commands.append(
("TEXTCOLOR", (0, i), (0, i), _severity_text_colour(f.severity))
)
t = Table(rows, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle(style_commands))
return t
def _make_appendix_table(findings: list[Finding]) -> Table:
"""
Build the full appendix table with all findings sorted by severity
descending, then check_id ascending.
Args:
findings: All findings from the analysis result.
Returns:
ReportLab Table flowable.
"""
severity_order = {"High": 0, "Medium": 1, "Low": 2}
sorted_findings = sorted(
findings,
key=lambda f: (severity_order.get(f.severity, 3), f.check_id),
)
header = [
Paragraph("#", _STYLES["table_header"]),
Paragraph("Severity", _STYLES["table_header"]),
Paragraph("Category", _STYLES["table_header"]),
Paragraph("Sheet", _STYLES["table_header"]),
Paragraph("Cell", _STYLES["table_header"]),
Paragraph("Finding", _STYLES["table_header"]),
Paragraph("Description", _STYLES["table_header"]),
]
usable_width = PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN
col_widths = [
0.7 * cm, # #
1.5 * cm, # Severity
2.0 * cm, # Category
2.8 * cm, # Sheet
1.4 * cm, # Cell
3.0 * cm, # Finding name
usable_width - (0.7 + 1.5 + 2.0 + 2.8 + 1.4 + 3.0) * cm, # Description
]
rows = [header]
style_commands = [
("BACKGROUND", (0, 0), (-1, 0), _COLOUR_HEADER_BG),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("GRID", (0, 0), (-1, -1), 0.3, colors.HexColor("#BDC3C7")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("FONTSIZE", (0, 0), (-1, -1), 7),
("ROWBACKGROUNDS", (1, 1), (-1, -1), [colors.white, _COLOUR_ROW_ALT]),
]
for i, f in enumerate(sorted_findings, start=1):
rows.append([
Paragraph(str(i), _STYLES["cell_small"]),
Paragraph(f"<b>{f.severity}</b>", _STYLES["cell_small_bold"]),
Paragraph(_escape_xml(f.category), _STYLES["cell_small"]),
Paragraph(_escape_xml(f.sheet_name[:25]), _STYLES["cell_small"]),
Paragraph(_escape_xml(f.cell_ref[:10]), _STYLES["cell_mono"]),
Paragraph(_escape_xml(f.name[:40]), _STYLES["cell_small_bold"]),
Paragraph(_escape_xml(f.description[:250]), _STYLES["cell_small"]),
])
bg = _severity_bg_colour(f.severity)
style_commands.append(("BACKGROUND", (1, i), (1, i), bg))
t = Table(rows, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle(style_commands))
return t
# ---------------------------------------------------------------------------
# XML escaping helper
# ---------------------------------------------------------------------------
def _escape_xml(text: str) -> str:
"""
Escape characters that would break ReportLab's XML-like Paragraph parser.
Args:
text: Raw string.
Returns:
String safe for use in Paragraph() content.
"""
return (
str(text)
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
)
# ---------------------------------------------------------------------------
# AI disclaimer paragraph
# ---------------------------------------------------------------------------
_AI_DISCLAIMER = (
"AI commentary is generated from formula metadata and structural analysis. "
"It is interpretive and may not fully reflect model intent. Always validate "
"with the model owner."
)
def _ai_label_para() -> Paragraph:
"""Return the 'AI-Generated — Interpretive Only' italic label."""
return Paragraph(
"<i>AI-Generated — Interpretive Only</i>",
ParagraphStyle(
"ai_label",
fontName="Helvetica-Oblique",
fontSize=8,
textColor=_COLOUR_AI_LABEL,
spaceAfter=2,
),
)
def _ai_disclaimer_para() -> Paragraph:
"""Return the standard AI disclaimer paragraph."""
return Paragraph(
f"<i>{_escape_xml(_AI_DISCLAIMER)}</i>",
ParagraphStyle(
"ai_disclaimer",
fontName="Helvetica-Oblique",
fontSize=7,
textColor=_COLOUR_AI_LABEL,
spaceBefore=4,
spaceAfter=4,
),
)
def _coloured_box(text: str, bg_colour: colors.Color) -> Table:
"""Render a paragraph of text inside a coloured background box."""
inner = Paragraph(
_escape_xml(text[:1500]),
ParagraphStyle(
"ai_box_text",
fontName="Helvetica",
fontSize=9,
textColor=_COLOUR_TEXT,
leading=13,
),
)
usable = PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN
t = Table([[inner]], colWidths=[usable])
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (0, 0), bg_colour),
("BOX", (0, 0), (0, 0), 0.5, colors.HexColor("#BDC3C7")),
("LEFTPADDING", (0, 0), (0, 0), 8),
("RIGHTPADDING", (0, 0), (0, 0), 8),
("TOPPADDING", (0, 0), (0, 0), 6),
("BOTTOMPADDING", (0, 0), (0, 0), 6),
]))
return t
def _build_ai_section(result: WorkbookAnalysisResult, story: list) -> None:
"""
Append the 'AI Workbook Intelligence' section to the story.
Only called when result.ai_commentary is not None.
"""
ai = result.ai_commentary
if ai is None:
return
has_content = any([
ai.workbook_purpose,
ai.sheet_narratives,
ai.assumption_commentary,
ai.formula_explanations,
])
if not has_content:
return
story.append(PageBreak())
story.append(Paragraph("AI Workbook Intelligence", _STYLES["section_heading"]))
story.append(HRFlowable(width="100%", thickness=1, color=_COLOUR_LIGHT_GREY))
story.append(Spacer(1, 0.2 * cm))
# 1. Workbook Purpose
if ai.workbook_purpose:
story.append(Paragraph("Workbook Purpose", _STYLES["subsection_heading"]))
story.append(_ai_label_para())
story.append(_coloured_box(ai.workbook_purpose, _COLOUR_AI_BLUE))
story.append(_ai_disclaimer_para())
story.append(Spacer(1, 0.3 * cm))
# 2. Sheet Narratives — two-column table
if ai.sheet_narratives:
story.append(Paragraph("Sheet-by-Sheet Narratives", _STYLES["subsection_heading"]))
story.append(_ai_label_para())
sensitive_names = set(result.high_sensitivity_sheets)
usable = PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN
col_w_name = usable * 0.30
col_w_narr = usable * 0.70
header_row = [
Paragraph("Sheet", _STYLES["table_header"]),
Paragraph("Narrative", _STYLES["table_header"]),
]
rows = [header_row]
style_cmds = [
("BACKGROUND", (0, 0), (-1, 0), _COLOUR_HEADER_BG),
("GRID", (0, 0), (-1, -1), 0.3, colors.HexColor("#BDC3C7")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("ROWBACKGROUNDS", (1, 1), (-1, -1), [colors.white, _COLOUR_AI_BLUE]),
]
for sn in ai.sheet_narratives:
name_style = _STYLES["cell_small_bold"] if sn.sheet_name in sensitive_names else _STYLES["cell_small"]
rows.append([
Paragraph(_escape_xml(sn.sheet_name), name_style),
Paragraph(_escape_xml(sn.narrative[:800]), _STYLES["cell_small"]),
])
t = Table(rows, colWidths=[col_w_name, col_w_narr], repeatRows=1)
t.setStyle(TableStyle(style_cmds))
story.append(t)
story.append(_ai_disclaimer_para())
story.append(Spacer(1, 0.3 * cm))
# 3. Key Formula Explanations
if ai.formula_explanations:
story.append(Paragraph("Key Formula Explanations", _STYLES["subsection_heading"]))
story.append(_ai_label_para())
usable = PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN
col_widths = [
usable * 0.15, # Sheet
usable * 0.09, # Cell
usable * 0.26, # Formula
usable * 0.50, # Explanation
]
header_row = [
Paragraph("Sheet", _STYLES["table_header"]),
Paragraph("Cell", _STYLES["table_header"]),
Paragraph("Formula", _STYLES["table_header"]),
Paragraph("Explanation", _STYLES["table_header"]),
]
rows = [header_row]
style_cmds = [
("BACKGROUND", (0, 0), (-1, 0), _COLOUR_HEADER_BG),
("GRID", (0, 0), (-1, -1), 0.3, colors.HexColor("#BDC3C7")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("ROWBACKGROUNDS", (1, 1), (-1, -1), [colors.white, _COLOUR_ROW_ALT]),
]
for fe in ai.formula_explanations:
formula_display = fe.formula[:60] + "…" if len(fe.formula) > 60 else fe.formula
rows.append([
Paragraph(_escape_xml(fe.sheet_name[:25]), _STYLES["cell_small"]),
Paragraph(_escape_xml(fe.cell_address[:10]), _STYLES["cell_mono"]),
Paragraph(_escape_xml(formula_display), _STYLES["cell_mono"]),
Paragraph(_escape_xml(fe.explanation[:600]), _STYLES["cell_small"]),
])
t = Table(rows, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle(style_cmds))
story.append(t)
story.append(_ai_disclaimer_para())
story.append(Spacer(1, 0.3 * cm))
# 4. Assumption and Input Commentary
if ai.assumption_commentary:
story.append(Paragraph("Assumption and Input Commentary", _STYLES["subsection_heading"]))
story.append(_ai_label_para())
story.append(_coloured_box(ai.assumption_commentary, _COLOUR_AI_YELLOW))
story.append(_ai_disclaimer_para())
story.append(Spacer(1, 0.3 * cm))
# ---------------------------------------------------------------------------
# Cover page builder
# ---------------------------------------------------------------------------
def _build_cover_page(
result: WorkbookAnalysisResult, story: list
) -> None:
"""
Append cover page elements to the story list.
Args:
result: WorkbookAnalysisResult.
story: Mutable list of ReportLab flowables.
"""
story.append(Spacer(1, 3 * cm))
# Tool title
story.append(Paragraph(
"Excel Workbook Risk Diagnostic Report",
_STYLES["cover_title"],
))
story.append(HRFlowable(
width="80%", thickness=2, color=_COLOUR_HEADER_BG, hAlign="CENTER"
))
story.append(Spacer(1, 0.5 * cm))
# Workbook filename
story.append(Paragraph(
f"<b>{_escape_xml(result.filename)}</b>",
_STYLES["cover_subtitle"],
))
# Timestamp
ts = result.analysis_timestamp.strftime("%d %B %Y %H:%M UTC")
story.append(Paragraph(f"Analysed: {ts}", _STYLES["cover_subtitle"]))
story.append(Paragraph(
f"File size: {result.file_size_mb:.2f} MB",
_STYLES["cover_subtitle"],
))
story.append(Spacer(1, 1 * cm))
# RAG badge — centred table cell with coloured background
rag_colour = _rag_colour(result.rag_rating)
rag_table = Table(
[[Paragraph(result.rag_rating.upper(), _STYLES["cover_rag"])]],
colWidths=[6 * cm],
rowHeights=[2 * cm],
)
rag_table.setStyle(TableStyle([
("BACKGROUND", (0, 0), (0, 0), rag_colour),
("ALIGN", (0, 0), (0, 0), "CENTER"),
("VALIGN", (0, 0), (0, 0), "MIDDLE"),
("ROUNDEDCORNERS", [8]),
("BOX", (0, 0), (0, 0), 1, rag_colour),
]))
# Wrap RAG badge in a centred outer table
outer = Table([[rag_table]], colWidths=[PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN])
outer.setStyle(TableStyle([("ALIGN", (0, 0), (0, 0), "CENTER")]))
story.append(outer)
story.append(Spacer(1, 0.5 * cm))
story.append(Paragraph(
f"Overall Risk Score: <b>{result.total_score}</b>",
_STYLES["cover_subtitle"],
))
story.append(Spacer(1, 0.8 * cm))
# Summary counts table
story.append(_make_summary_table(result))
story.append(PageBreak())
# ---------------------------------------------------------------------------
# Findings-by-category section builder
# ---------------------------------------------------------------------------
_CATEGORY_ORDER = ["Formula", "Error", "Link", "Structure", "VBA", "Actuarial"]
_CATEGORY_DESCRIPTIONS: dict[str, str] = {
"Formula": (
"Formula integrity checks examine cell formulas for hardcoded literals, "
"dangerous lookup modes, volatile functions, inconsistent patterns, and "
"possible paste-over overrides."
),
"Error": (
"Cell error checks scan all computed cell values for Excel error codes "
"such as #REF!, #N/A, and #DIV/0! which indicate broken formula chains."
),
"Link": (
"Link checks verify external workbook references, named ranges, and "
"the presence of circular reference indicators in the workbook metadata."
),
"Structure": (
"Structure checks assess file size, cell population density, hidden "
"worksheets, and sheet protection settings."
),
"VBA": (
"VBA macro checks inspect embedded Visual Basic code for hardcoded "
"parameters, missing error handlers, dangerous commands, and absolute "
"file path references."
),
"Actuarial": (
"Actuarial domain checks apply heuristics specific to life insurance "
"models, flagging high-sensitivity sheets, inconsistent assumptions "
"across sheets, and isolated hardcoded values."
),
}
def _build_findings_by_category(
result: WorkbookAnalysisResult, story: list
) -> None:
"""
Append a 'Findings by Category' section to the story.
Args:
result: WorkbookAnalysisResult.
story: Mutable list of ReportLab flowables.
"""
story.append(Paragraph("Findings by Category", _STYLES["section_heading"]))
story.append(HRFlowable(width="100%", thickness=1, color=_COLOUR_LIGHT_GREY))
story.append(Spacer(1, 0.3 * cm))
# Build category → findings map
cat_map: dict[str, list[Finding]] = defaultdict(list)
for f in result.findings:
cat_map[f.category].append(f)
for category in _CATEGORY_ORDER:
cat_findings = cat_map.get(category, [])
desc = _CATEGORY_DESCRIPTIONS.get(category, "")
counts = Counter(f.severity for f in cat_findings)
story.append(Paragraph(
f"{category} Checks "
f"<font color='#C0392B'>{counts.get('High', 0)}H</font> "
f"<font color='#E67E22'>{counts.get('Medium', 0)}M</font> "
f"<font color='#27AE60'>{counts.get('Low', 0)}L</font>",
_STYLES["subsection_heading"],
))
if desc:
story.append(Paragraph(desc, _STYLES["body_italic"]))
if not cat_findings:
story.append(Paragraph(
"No findings detected in this category.",
_STYLES["body_italic"],
))
else:
story.append(_make_findings_table(cat_findings))
story.append(Spacer(1, 0.4 * cm))
# ---------------------------------------------------------------------------
# High-sensitivity sheets section
# ---------------------------------------------------------------------------
def _build_sensitive_sheets_section(
result: WorkbookAnalysisResult, story: list
) -> None:
"""
Append the High-Sensitivity Sheets summary section.
Args:
result: WorkbookAnalysisResult.
story: Mutable list of ReportLab flowables.
"""
story.append(PageBreak())
story.append(Paragraph(
"High-Sensitivity Actuarial Sheets", _STYLES["section_heading"]
))
story.append(HRFlowable(width="100%", thickness=1, color=_COLOUR_LIGHT_GREY))
story.append(Spacer(1, 0.3 * cm))
if not result.high_sensitivity_sheets:
story.append(Paragraph(
"No high-sensitivity actuarial sheets were detected in this workbook. "
"Consider reviewing the actuarial keyword list in settings if this "
"is unexpected.",
_STYLES["body"],
))
return
story.append(Paragraph(
"The following sheets were identified as actuarially sensitive based on "
"keyword matching. Findings on these sheets carry elevated significance.",
_STYLES["body"],
))
story.append(Spacer(1, 0.3 * cm))
sensitive_set = set(result.high_sensitivity_sheets)
for sheet_name in result.high_sensitivity_sheets:
sheet_findings = [
f for f in result.findings
if f.sheet_name == sheet_name and f.check_id != 21
]
counts = Counter(f.severity for f in sheet_findings)
story.append(Paragraph(
f"Sheet: <b>{_escape_xml(sheet_name)}</b> — "
f"{len(sheet_findings)} finding(s) "
f"[{counts.get('High', 0)}H / "
f"{counts.get('Medium', 0)}M / "
f"{counts.get('Low', 0)}L]",
_STYLES["subsection_heading"],
))
if sheet_findings:
story.append(_make_findings_table(sheet_findings))
else:
story.append(Paragraph(
"No specific findings on this sheet.", _STYLES["body_italic"]
))
story.append(Spacer(1, 0.3 * cm))
# ---------------------------------------------------------------------------
# Appendix builder
# ---------------------------------------------------------------------------
def _build_appendix(result: WorkbookAnalysisResult, story: list) -> None:
"""
Append the full findings appendix table, sorted by severity descending.
Args:
result: WorkbookAnalysisResult.
story: Mutable list of ReportLab flowables.
"""
story.append(PageBreak())
story.append(Paragraph("Appendix: Full Findings Listing", _STYLES["section_heading"]))
story.append(HRFlowable(width="100%", thickness=1, color=_COLOUR_LIGHT_GREY))
story.append(Paragraph(
f"All {len(result.findings)} finding(s) sorted by severity (High → Medium → Low).",
_STYLES["body_italic"],
))
story.append(Spacer(1, 0.3 * cm))
if result.findings:
story.append(_make_appendix_table(result.findings))
else:
story.append(Paragraph("No findings to list.", _STYLES["body_italic"]))
# ---------------------------------------------------------------------------
# Page header/footer callback
# ---------------------------------------------------------------------------
def _add_page_decorations(canvas, doc) -> None:
"""
Draw running header and footer on every page.
Called by ReportLab as an onPage callback.
Args:
canvas: ReportLab Canvas object.
doc: The document being built.
"""
canvas.saveState()
# Footer: page number + tool name
canvas.setFont("Helvetica", 7)
canvas.setFillColor(colors.HexColor("#95A5A6"))
page_num_text = f"Page {doc.page}"
canvas.drawRightString(
PAGE_WIDTH - RIGHT_MARGIN, 1.2 * cm, page_num_text
)