Py.Cafe

huong-li-nguyen/

enterprise-financial-insights

Enterprise Financial Insights

DocsPricing
  • assets/
  • app.py
  • requirements.txt
app.py
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
# Vizro is an open-source toolkit for creating modular data visualization applications.
# check out https://github.com/mckinsey/vizro for more info about Vizro
# and checkout https://vizro.readthedocs.io/en/stable/ for documentation.

import numpy as np
import pandas as pd
import plotly.graph_objects as go

import vizro.models as vm
from vizro import Vizro
from vizro.figures import kpi_card, kpi_card_reference
from vizro.managers import data_manager
from vizro.models.types import capture
from vizro.tables import dash_ag_grid

MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
DEPARTMENTS = ["Engineering", "Marketing", "Sales", "Operations", "Finance"]


#### DATA SETUP ####

np.random.seed(42)

# --- Financial Monthly ---
base_revenue = 10_000_000
base_expenses = 7_000_000
revenue_vals = [int(base_revenue * (1.03**i) + np.random.normal(0, 200_000)) for i in range(12)]
expenses_vals = [int(base_expenses * (1.02**i) + np.random.normal(0, 150_000)) for i in range(12)]
net_income_vals = [r - e for r, e in zip(revenue_vals, expenses_vals)]
gross_margin_vals = [round(55 + np.random.normal(0, 1.5), 1) for _ in range(12)]
operating_margin_vals = [round(30 + np.random.normal(0, 1.2), 1) for _ in range(12)]
net_margin_vals = [round((ni / r) * 100, 1) for ni, r in zip(net_income_vals, revenue_vals)]

financial_monthly_df = pd.DataFrame(
    {
        "month": MONTHS,
        "revenue": revenue_vals,
        "expenses": expenses_vals,
        "net_income": net_income_vals,
        "gross_margin_pct": gross_margin_vals,
        "operating_margin_pct": operating_margin_vals,
        "net_margin_pct": net_margin_vals,
    }
)

# --- Cost Breakdown (current month) ---
latest_expenses = expenses_vals[-1]
cost_breakdown_df = pd.DataFrame(
    {
        "category": ["Salaries", "Operations", "Marketing", "IT", "Facilities"],
        "amount": [int(latest_expenses * p + np.random.normal(0, 20_000)) for p in [0.40, 0.25, 0.15, 0.12, 0.08]],
    }
)

# --- Executive Summary KPIs (current vs previous month) ---
exec_kpi_df = pd.DataFrame(
    {
        "revenue": [revenue_vals[-1]],
        "revenue_prev": [revenue_vals[-2]],
        "net_margin_pct": [net_margin_vals[-1]],
        "net_margin_pct_prev": [net_margin_vals[-2]],
        "csat_score": [8.2],
        "csat_score_prev": [8.1],
        "ops_efficiency": [87.5],
        "ops_efficiency_prev": [88.3],
        "headcount": [548],
        "headcount_prev": [536],
    }
)

# --- Financial KPIs ---
financial_kpi_df = pd.DataFrame(
    {
        "net_income": [net_income_vals[-1]],
        "net_income_prev": [net_income_vals[-2]],
        "revenue": [revenue_vals[-1]],
        "revenue_prev": [revenue_vals[-2]],
        "expenses": [expenses_vals[-1]],
        "expenses_prev": [expenses_vals[-2]],
        "gross_margin_pct": [gross_margin_vals[-1]],
        "gross_margin_pct_prev": [gross_margin_vals[-2]],
        "operating_margin_pct": [operating_margin_vals[-1]],
        "operating_margin_pct_prev": [operating_margin_vals[-2]],
    }
)

# --- Operations: Project Status (by month, department, status) ---
project_rows = []
for i, month in enumerate(MONTHS):
    total = 50 + np.random.randint(-5, 6)
    delayed = np.random.randint(3, 8)
    in_progress = np.random.randint(10, 16)
    completed = total - delayed - in_progress
    for dept in DEPARTMENTS:
        project_rows.extend(
            [
                {"month": month, "department": dept, "status": "Completed", "count": max(1, int(completed / len(DEPARTMENTS) + np.random.randint(-1, 2)))},
                {"month": month, "department": dept, "status": "In Progress", "count": max(1, int(in_progress / len(DEPARTMENTS) + np.random.randint(-1, 2)))},
                {"month": month, "department": dept, "status": "Delayed", "count": max(0, int(delayed / len(DEPARTMENTS) + np.random.randint(-1, 2)))},
            ]
        )
ops_projects_df = pd.DataFrame(project_rows)

# --- Operations: Productivity Trend ---
productivity_vals = [round(8.5 + 0.05 * i + np.random.normal(0, 0.2), 2) for i in range(12)]
ops_productivity_df = pd.DataFrame({"month": MONTHS, "productivity_index": productivity_vals})

# --- Operations: Delivery by Department ---
ops_delivery_df = pd.DataFrame({"department": DEPARTMENTS, "on_time_pct": [92, 85, 88, 91, 94]})

# --- Operations KPIs ---
ops_kpi_df = pd.DataFrame(
    {
        "proj_completion_rate": [82.0],
        "proj_completion_rate_prev": [79.0],
        "on_time_delivery": [89.0],
        "on_time_delivery_prev": [87.0],
        "productivity_index": [productivity_vals[-1]],
        "productivity_index_prev": [productivity_vals[-2]],
        "capacity_utilization": [81.0],
        "capacity_utilization_prev": [78.0],
    }
)

# --- HR Monthly ---
headcount_vals = [500 + int(4 * i + np.random.randint(-2, 3)) for i in range(12)]
attrition_vals = [round(3.5 + np.random.normal(0, 0.5), 1) for _ in range(12)]
hr_monthly_df = pd.DataFrame({"month": MONTHS, "headcount": headcount_vals, "attrition_rate": attrition_vals})

# --- HR: Training by Department ---
hr_training_df = pd.DataFrame({"department": DEPARTMENTS, "training_hours": [16.2, 12.5, 14.8, 11.3, 15.1]})

# --- CSR Monthly ---
csr_actual = [int(200_000 + np.random.normal(0, 15_000)) for _ in range(12)]
csr_budget = [220_000] * 12
csr_monthly_df = pd.DataFrame({"month": MONTHS, "actual": csr_actual, "budget": csr_budget})

# --- HR KPIs ---
hr_kpi_df = pd.DataFrame(
    {
        "headcount": [headcount_vals[-1]],
        "headcount_prev": [headcount_vals[-2]],
        "attrition_rate": [attrition_vals[-1]],
        "attrition_rate_prev": [attrition_vals[-2]],
        "diversity_index": [46.2],
        "diversity_index_prev": [45.8],
        "training_hrs": [14.5],
        "training_hrs_prev": [13.8],
        "csr_spend": [csr_actual[-1]],
        "csr_spend_prev": [csr_actual[-2]],
    }
)

# --- Initiatives ---
initiatives_df = pd.DataFrame(
    {
        "initiative": [
            "Digital Transformation",
            "Market Expansion APAC",
            "Cost Optimization Program",
            "Employee Engagement",
            "Supply Chain Resilience",
            "ESG Compliance",
            "Customer Portal v2.0",
            "Data Analytics Platform",
        ],
        "owner": ["CTO", "VP Sales", "CFO", "CHRO", "COO", "CSO", "CTO", "CDO"],
        "status": ["On Track", "On Track", "On Track", "At Risk", "At Risk", "On Track", "Blocked", "On Track"],
        "due_date": ["2025-06-30", "2025-09-30", "2025-12-31", "2025-08-31", "2025-10-31", "2025-12-31", "2025-07-31", "2025-11-30"],
        "completion_pct": [85, 72, 60, 45, 38, 55, 25, 68],
    }
)

# --- Action Tracking KPIs ---
action_kpi_df = pd.DataFrame({"on_track_count": [5], "at_risk_count": [2], "blocked_count": [1]})

# --- RAG Summary (for executive summary chart) ---
rag_summary_df = pd.DataFrame({"status": ["On Track", "At Risk", "Blocked"], "count": [5, 2, 1]})

# Register all data
data_manager["exec_kpi"] = exec_kpi_df
data_manager["financial_monthly"] = financial_monthly_df
data_manager["financial_kpi"] = financial_kpi_df
data_manager["cost_breakdown"] = cost_breakdown_df
data_manager["ops_projects"] = ops_projects_df
data_manager["ops_productivity"] = ops_productivity_df
data_manager["ops_delivery"] = ops_delivery_df
data_manager["ops_kpi"] = ops_kpi_df
data_manager["hr_monthly"] = hr_monthly_df
data_manager["hr_training"] = hr_training_df
data_manager["csr_monthly"] = csr_monthly_df
data_manager["hr_kpi"] = hr_kpi_df
data_manager["initiatives"] = initiatives_df
data_manager["action_kpi"] = action_kpi_df
data_manager["rag_summary"] = rag_summary_df


#### CUSTOM CHART SETUP ####


@capture("graph")
def revenue_trend(data_frame: pd.DataFrame) -> go.Figure:
    fig = go.Figure(
        go.Scatter(x=data_frame["month"], y=data_frame["revenue"], mode="lines+markers", name="Revenue")
    )
    fig.update_layout(title="Revenue Trend", xaxis_title="", yaxis_title="Revenue ($)", showlegend=False)
    return fig


@capture("graph")
def net_margin_trend(data_frame: pd.DataFrame) -> go.Figure:
    fig = go.Figure(
        go.Scatter(x=data_frame["month"], y=data_frame["net_margin_pct"], mode="lines+markers", name="Net Margin")
    )
    fig.update_layout(title="Net Margin Trend", xaxis_title="", yaxis_title="Margin (%)", showlegend=False)
    return fig


@capture("graph")
def expense_breakdown_chart(data_frame: pd.DataFrame) -> go.Figure:
    df_sorted = data_frame.sort_values("amount", ascending=True)
    fig = go.Figure(
        go.Bar(
            x=df_sorted["amount"],
            y=df_sorted["category"],
            orientation="h",
            text=[f"${v / 1e6:.2f}M" for v in df_sorted["amount"]],
            textposition="auto",
        )
    )
    fig.update_layout(title="Expense Breakdown (Current Month)", xaxis_title="", yaxis_title="")
    return fig


@capture("graph")
def rag_summary_chart(data_frame: pd.DataFrame) -> go.Figure:
    status_order = ["Blocked", "At Risk", "On Track"]
    df = data_frame.set_index("status").reindex(status_order).reset_index()
    color_map = {"On Track": "#00B5A9", "At Risk": "#EA5748", "Blocked": "#FFC107"}
    fig = go.Figure(
        go.Bar(
            x=df["count"],
            y=df["status"],
            orientation="h",
            marker_color=[color_map[s] for s in df["status"]],
            text=df["count"],
            textposition="auto",
        )
    )
    fig.update_layout(title="Strategic Initiatives Status", xaxis_title="Count", yaxis_title="", showlegend=False)
    return fig


@capture("graph")
def revenue_vs_expenses_trend(data_frame: pd.DataFrame) -> go.Figure:
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=data_frame["month"], y=data_frame["revenue"], mode="lines+markers", name="Revenue"))
    fig.add_trace(go.Scatter(x=data_frame["month"], y=data_frame["expenses"], mode="lines+markers", name="Expenses"))
    fig.update_layout(title="Revenue vs Expenses", xaxis_title="", yaxis_title="Amount ($)", legend_title="")
    return fig


@capture("graph")
def cost_breakdown_by_category(data_frame: pd.DataFrame) -> go.Figure:
    df_sorted = data_frame.sort_values("amount", ascending=True)
    fig = go.Figure(
        go.Bar(
            x=df_sorted["amount"],
            y=df_sorted["category"],
            orientation="h",
            text=[f"${v / 1e6:.2f}M" for v in df_sorted["amount"]],
            textposition="auto",
        )
    )
    fig.update_layout(title="Cost Breakdown by Category", xaxis_title="", yaxis_title="")
    return fig


@capture("graph")
def gross_operating_margin_trend(data_frame: pd.DataFrame) -> go.Figure:
    fig = go.Figure()
    fig.add_trace(
        go.Scatter(x=data_frame["month"], y=data_frame["gross_margin_pct"], mode="lines+markers", name="Gross Margin")
    )
    fig.add_trace(
        go.Scatter(
            x=data_frame["month"], y=data_frame["operating_margin_pct"], mode="lines+markers", name="Operating Margin"
        )
    )
    fig.update_layout(title="Margin Trend", xaxis_title="", yaxis_title="Margin (%)", legend_title="")
    return fig


@capture("graph")
def project_status_chart(data_frame: pd.DataFrame) -> go.Figure:
    agg = data_frame.groupby(["month", "status"])["count"].sum().reset_index()
    agg["month"] = pd.Categorical(agg["month"], categories=MONTHS, ordered=True)
    agg = agg.sort_values("month")
    fig = go.Figure()
    for status in ["Completed", "In Progress", "Delayed"]:
        s_data = agg[agg["status"] == status]
        fig.add_trace(go.Bar(x=s_data["month"], y=s_data["count"], name=status))
    fig.update_layout(
        barmode="stack", title="Project Status by Month", xaxis_title="", yaxis_title="Count", legend_title=""
    )
    return fig


@capture("graph")
def productivity_trend_chart(data_frame: pd.DataFrame) -> go.Figure:
    fig = go.Figure(
        go.Scatter(
            x=data_frame["month"], y=data_frame["productivity_index"], mode="lines+markers", name="Productivity"
        )
    )
    fig.update_layout(title="Productivity Trend", xaxis_title="", yaxis_title="Index", showlegend=False)
    return fig


@capture("graph")
def delivery_performance_chart(data_frame: pd.DataFrame) -> go.Figure:
    df_sorted = data_frame.sort_values("on_time_pct", ascending=True)
    fig = go.Figure(
        go.Bar(
            x=df_sorted["on_time_pct"],
            y=df_sorted["department"],
            orientation="h",
            text=[f"{v}%" for v in df_sorted["on_time_pct"]],
            textposition="auto",
        )
    )
    fig.update_layout(title="On-Time Delivery by Department", xaxis_title="", yaxis_title="")
    return fig


@capture("graph")
def headcount_trend_chart(data_frame: pd.DataFrame) -> go.Figure:
    fig = go.Figure(
        go.Scatter(x=data_frame["month"], y=data_frame["headcount"], mode="lines+markers", name="Headcount")
    )
    fig.update_layout(title="Headcount Trend", xaxis_title="", yaxis_title="Employees", showlegend=False)
    return fig


@capture("graph")
def attrition_trend_chart(data_frame: pd.DataFrame) -> go.Figure:
    fig = go.Figure(
        go.Scatter(x=data_frame["month"], y=data_frame["attrition_rate"], mode="lines+markers", name="Attrition")
    )
    fig.update_layout(title="Attrition Rate Trend", xaxis_title="", yaxis_title="Rate (%)", showlegend=False)
    return fig


@capture("graph")
def training_by_dept_chart(data_frame: pd.DataFrame) -> go.Figure:
    df_sorted = data_frame.sort_values("training_hours", ascending=True)
    fig = go.Figure(
        go.Bar(
            x=df_sorted["training_hours"],
            y=df_sorted["department"],
            orientation="h",
            text=[f"{v:.1f}h" for v in df_sorted["training_hours"]],
            textposition="auto",
        )
    )
    fig.update_layout(title="Training Hours per Employee", xaxis_title="", yaxis_title="")
    return fig


@capture("graph")
def csr_spend_vs_budget_chart(data_frame: pd.DataFrame) -> go.Figure:
    fig = go.Figure()
    fig.add_trace(go.Bar(x=data_frame["month"], y=data_frame["actual"], name="Actual"))
    fig.add_trace(go.Bar(x=data_frame["month"], y=data_frame["budget"], name="Budget"))
    fig.update_layout(
        barmode="group", title="CSR Spend vs Budget", xaxis_title="", yaxis_title="Amount ($)", legend_title=""
    )
    return fig


@capture("graph")
def completion_chart(data_frame: pd.DataFrame) -> go.Figure:
    df_sorted = data_frame.sort_values("completion_pct", ascending=True)
    color_map = {"On Track": "#00B5A9", "At Risk": "#EA5748", "Blocked": "#FFC107"}
    fig = go.Figure(
        go.Bar(
            x=df_sorted["completion_pct"],
            y=df_sorted["initiative"],
            orientation="h",
            marker_color=[color_map.get(s, "#888") for s in df_sorted["status"]],
            text=[f"{v}%" for v in df_sorted["completion_pct"]],
            textposition="auto",
        )
    )
    fig.update_layout(title="Initiative Completion", xaxis_title="Completion %", yaxis_title="")
    return fig


#### DASHBOARD SETUP ####

exec_summary = vm.Page(
    title="Executive Summary",
    components=[
        vm.Container(
            id="exec_kpi_container",
            layout=vm.Flex(direction="row", gap="12px", wrap=True),
            components=[
                vm.Figure(
                    figure=kpi_card_reference(
                        "exec_kpi",
                        value_column="revenue",
                        reference_column="revenue_prev",
                        value_format="${value:,.0f}",
                        reference_format="{delta_relative:+.1%} vs prev month",
                        agg_func="mean",
                        title="Total Revenue",
                        icon="payments",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "exec_kpi",
                        value_column="net_margin_pct",
                        reference_column="net_margin_pct_prev",
                        value_format="{value:.1f}%",
                        reference_format="{delta:+.1f}pp vs prev month",
                        agg_func="mean",
                        title="Net Margin",
                        icon="trending_up",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "exec_kpi",
                        value_column="csat_score",
                        reference_column="csat_score_prev",
                        value_format="{value:.1f}",
                        reference_format="{delta:+.1f} vs prev month",
                        agg_func="mean",
                        title="Customer Satisfaction",
                        icon="sentiment_satisfied",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "exec_kpi",
                        value_column="ops_efficiency",
                        reference_column="ops_efficiency_prev",
                        value_format="{value:.1f}%",
                        reference_format="{delta:+.1f}pp vs prev month",
                        agg_func="mean",
                        title="Ops Efficiency",
                        icon="speed",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "exec_kpi",
                        value_column="headcount",
                        reference_column="headcount_prev",
                        value_format="{value:,.0f}",
                        reference_format="{delta:+.0f} vs prev month",
                        agg_func="mean",
                        title="Headcount",
                        icon="groups",
                    )
                ),
            ],
        ),
        vm.Graph(figure=revenue_trend("financial_monthly")),
        vm.Graph(figure=net_margin_trend("financial_monthly")),
        vm.Graph(figure=expense_breakdown_chart("cost_breakdown")),
        vm.Graph(figure=rag_summary_chart("rag_summary")),
    ],
    layout=vm.Grid(
        grid=[
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
            [3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
            [3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
        ],
        row_min_height="140px",
    ),
)

financial = vm.Page(
    title="Financial Performance",
    components=[
        vm.Container(
            id="financial_kpi_container",
            layout=vm.Flex(direction="row", gap="12px", wrap=True),
            components=[
                vm.Figure(
                    figure=kpi_card_reference(
                        "financial_kpi",
                        value_column="net_income",
                        reference_column="net_income_prev",
                        value_format="${value:,.0f}",
                        reference_format="{delta_relative:+.1%} vs prev month",
                        agg_func="mean",
                        title="Net Income",
                        icon="account_balance",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "financial_kpi",
                        value_column="revenue",
                        reference_column="revenue_prev",
                        value_format="${value:,.0f}",
                        reference_format="{delta_relative:+.1%} vs prev month",
                        agg_func="mean",
                        title="Total Revenue",
                        icon="payments",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "financial_kpi",
                        value_column="expenses",
                        reference_column="expenses_prev",
                        value_format="${value:,.0f}",
                        reference_format="{delta_relative:+.1%} vs prev month",
                        agg_func="mean",
                        title="Total Expenses",
                        icon="receipt_long",
                        reverse_color=True,
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "financial_kpi",
                        value_column="gross_margin_pct",
                        reference_column="gross_margin_pct_prev",
                        value_format="{value:.1f}%",
                        reference_format="{delta:+.1f}pp vs prev month",
                        agg_func="mean",
                        title="Gross Margin",
                        icon="show_chart",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "financial_kpi",
                        value_column="operating_margin_pct",
                        reference_column="operating_margin_pct_prev",
                        value_format="{value:.1f}%",
                        reference_format="{delta:+.1f}pp vs prev month",
                        agg_func="mean",
                        title="Operating Margin",
                        icon="analytics",
                    )
                ),
            ],
        ),
        vm.Graph(figure=revenue_vs_expenses_trend("financial_monthly")),
        vm.Graph(figure=cost_breakdown_by_category("cost_breakdown")),
        vm.Graph(figure=gross_operating_margin_trend("financial_monthly")),
    ],
    layout=vm.Grid(
        grid=[
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3],
            [2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3],
            [2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3],
        ],
        row_min_height="140px",
    ),
)

operations = vm.Page(
    title="Operational Performance",
    components=[
        vm.Container(
            id="ops_kpi_container",
            layout=vm.Flex(direction="row", gap="12px", wrap=True),
            components=[
                vm.Figure(
                    figure=kpi_card_reference(
                        "ops_kpi",
                        value_column="proj_completion_rate",
                        reference_column="proj_completion_rate_prev",
                        value_format="{value:.0f}%",
                        reference_format="{delta:+.0f}pp vs prev month",
                        agg_func="mean",
                        title="Project Completion",
                        icon="task_alt",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "ops_kpi",
                        value_column="on_time_delivery",
                        reference_column="on_time_delivery_prev",
                        value_format="{value:.0f}%",
                        reference_format="{delta:+.0f}pp vs prev month",
                        agg_func="mean",
                        title="On-Time Delivery",
                        icon="schedule",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "ops_kpi",
                        value_column="productivity_index",
                        reference_column="productivity_index_prev",
                        value_format="{value:.1f}",
                        reference_format="{delta:+.2f} vs prev month",
                        agg_func="mean",
                        title="Productivity Index",
                        icon="bar_chart",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "ops_kpi",
                        value_column="capacity_utilization",
                        reference_column="capacity_utilization_prev",
                        value_format="{value:.0f}%",
                        reference_format="{delta:+.0f}pp vs prev month",
                        agg_func="mean",
                        title="Capacity Utilization",
                        icon="battery_charging_full",
                    )
                ),
            ],
        ),
        vm.Graph(figure=project_status_chart("ops_projects")),
        vm.Graph(figure=productivity_trend_chart("ops_productivity")),
        vm.Graph(figure=delivery_performance_chart("ops_delivery")),
    ],
    layout=vm.Grid(
        grid=[
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
            [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
            [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
        ],
        row_min_height="140px",
    ),
    controls=[vm.Filter(column="department")],
)

hr_csr = vm.Page(
    title="HR & CSR",
    components=[
        vm.Container(
            id="hr_kpi_container",
            layout=vm.Flex(direction="row", gap="12px", wrap=True),
            components=[
                vm.Figure(
                    figure=kpi_card_reference(
                        "hr_kpi",
                        value_column="headcount",
                        reference_column="headcount_prev",
                        value_format="{value:,.0f}",
                        reference_format="{delta:+.0f} vs prev month",
                        agg_func="mean",
                        title="Headcount",
                        icon="groups",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "hr_kpi",
                        value_column="attrition_rate",
                        reference_column="attrition_rate_prev",
                        value_format="{value:.1f}%",
                        reference_format="{delta:+.1f}pp vs prev month",
                        agg_func="mean",
                        title="Attrition Rate",
                        icon="person_remove",
                        reverse_color=True,
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "hr_kpi",
                        value_column="diversity_index",
                        reference_column="diversity_index_prev",
                        value_format="{value:.1f}%",
                        reference_format="{delta:+.1f}pp vs prev month",
                        agg_func="mean",
                        title="Diversity Index",
                        icon="diversity_3",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "hr_kpi",
                        value_column="training_hrs",
                        reference_column="training_hrs_prev",
                        value_format="{value:.1f}h",
                        reference_format="{delta:+.1f}h vs prev month",
                        agg_func="mean",
                        title="Training Hrs/Employee",
                        icon="school",
                    )
                ),
                vm.Figure(
                    figure=kpi_card_reference(
                        "hr_kpi",
                        value_column="csr_spend",
                        reference_column="csr_spend_prev",
                        value_format="${value:,.0f}",
                        reference_format="{delta_relative:+.1%} vs prev month",
                        agg_func="mean",
                        title="CSR Spend",
                        icon="eco",
                    )
                ),
            ],
        ),
        vm.Graph(figure=headcount_trend_chart("hr_monthly")),
        vm.Graph(figure=attrition_trend_chart("hr_monthly")),
        vm.Graph(figure=training_by_dept_chart("hr_training")),
        vm.Graph(figure=csr_spend_vs_budget_chart("csr_monthly")),
    ],
    layout=vm.Grid(
        grid=[
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
            [3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
            [3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
            [3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
        ],
        row_min_height="140px",
    ),
)

action_tracking = vm.Page(
    title="Action Tracking",
    components=[
        vm.Container(
            id="action_kpi_container",
            layout=vm.Flex(direction="row", gap="12px", wrap=True),
            components=[
                vm.Figure(
                    figure=kpi_card(
                        "action_kpi",
                        value_column="on_track_count",
                        value_format="{value:.0f}",
                        agg_func="mean",
                        title="On Track",
                        icon="check_circle",
                    )
                ),
                vm.Figure(
                    figure=kpi_card(
                        "action_kpi",
                        value_column="at_risk_count",
                        value_format="{value:.0f}",
                        agg_func="mean",
                        title="At Risk",
                        icon="warning",
                    )
                ),
                vm.Figure(
                    figure=kpi_card(
                        "action_kpi",
                        value_column="blocked_count",
                        value_format="{value:.0f}",
                        agg_func="mean",
                        title="Blocked",
                        icon="block",
                    )
                ),
            ],
        ),
        vm.Graph(figure=completion_chart("initiatives")),
        vm.AgGrid(figure=dash_ag_grid("initiatives")),
    ],
    layout=vm.Grid(
        grid=[
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
            [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
            [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
            [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
        ],
        row_min_height="140px",
    ),
    controls=[vm.Filter(column="status")],
)

dashboard = vm.Dashboard(
    pages=[exec_summary, financial, operations, hr_csr, action_tracking],
    navigation=vm.Navigation(
        nav_selector=vm.NavBar(
            items=[
                vm.NavLink(
                    label="Executive Summary",
                    icon="Analytics",
                    pages=["Executive Summary"],
                ),
                vm.NavLink(
                    label="Financial Performance",
                    icon="Finance",
                    pages=["Financial Performance"],
                ),
                vm.NavLink(
                    label="Operational Performance",
                    icon="Assignment",
                    pages=["Operational Performance"],
                ),
                vm.NavLink(
                    label="HR & CSR",
                    icon="Group",
                    pages=["HR & CSR"],
                ),
                vm.NavLink(
                    label="Action Tracking",
                    icon="Track Changes",
                    pages=["Action Tracking"],
                )
            ]
        )
    ),
    )

app = Vizro().build(dashboard).run()