Py.Cafe

ribab./

fiscal-year-donation-analytics

Fiscal Year Donation Analytics

DocsPricing
  • assets/
  • components/
  • metrics/
  • 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
#!/usr/bin/env python3
import sys
from pathlib import Path
import pandas as pd
from datetime import datetime
import vizro.models as vm
import vizro.plotly.express as px
from vizro import Vizro
from vizro.models.types import capture

# Add project root to path
project_root = Path(__file__).parent
if str(project_root) not in sys.path:
    sys.path.append(str(project_root))

# Import data source
from utils.datasource import load_pledges, load_payments, load_merged_payments_and_pledges

# Import components
from components.kpi_card import create_kpi_card
from components.ai_graph_generator import AIGraphGenerator

# Import fiscal year metrics
import metrics.fiscal_year.money_moved

# Import kpi metrics
import metrics.kpi.arr
import metrics.kpi.attrition_rate_avg
import metrics.kpi.attrition_rate_all_time
import metrics.kpi.active_donors

# Import monthly metrics
import metrics.monthly.pledges
import metrics.monthly.all_active_donors
import metrics.monthly.active_recurring_donors
import metrics.monthly.monthly_donations
import metrics.monthly.arr
import metrics.monthly.attrition

# Import bar chart metrics
import metrics.bar_charts.chapter_arr
import metrics.bar_charts.channel_arr

Vizro._reset()

def create_home_page(payments_df, pledges_df, merged_df):
    """Create the home page with KPI cards and monthly metrics"""
    # Load data

    from vizro.managers import data_manager

    def calculate_fiscal_year(date):
        if date.month < 7:
            return f"{date.year - 1}-{date.year}"
        else:
            return f"{date.year}-{date.year + 1}"
    
    def get_payments_df(fiscal_year=None):
        df = payments_df
        if fiscal_year is None:
            fiscal_year = calculate_fiscal_year(datetime.now())
        # Fix: Use proper date string format for pd.Timestamp
        last_date_in_fiscal_year = f"{fiscal_year.split('-')[1]}-06-30"
        df = df[df['date'] <= last_date_in_fiscal_year]
        df['fiscal_year'] = fiscal_year
        return df

    def get_pledges_df(fiscal_year=None):
        df = pledges_df
        if fiscal_year is None:
            fiscal_year = calculate_fiscal_year(datetime.now())
        df['fiscal_year'] = fiscal_year
        return df

    def get_merged_df(fiscal_year=None):
        df = merged_df
        if fiscal_year is None:
            fiscal_year = calculate_fiscal_year(datetime.now())
        # Fix: Use proper date string format for pd.Timestamp
        last_date_in_fiscal_year = f"{fiscal_year.split('-')[1]}-06-30"
        df = df[df['date'] <= last_date_in_fiscal_year]
        df['fiscal_year'] = fiscal_year
        return df

    # Register the data with the data manager
    data_manager["home_page_payments"] = get_payments_df
    data_manager["home_page_pledges"] = get_pledges_df
    data_manager["home_page_merged"] = get_merged_df
    
    # Create KPI cards grid
    kpi_cards = [
        vm.Figure(
            id="money_moved_kpi",
            figure=capture('figure')(lambda data_frame: metrics.kpi.money_moved.kpi_card(data_frame))("home_page_payments")
        ),
        vm.Figure(
            id="arr_kpi",
            figure=capture('figure')(lambda data_frame: metrics.kpi.arr.create_arr_kpi_card(data_frame))("home_page_pledges")
        ),
        vm.Figure(
            id="future_arr_kpi",
            figure=capture('figure')(lambda data_frame: metrics.kpi.arr.create_future_arr_kpi_card(data_frame))("home_page_pledges")
        ),
        vm.Figure(
            id="active_arr_kpi",
            figure=capture('figure')(lambda data_frame: metrics.kpi.arr.create_active_arr_kpi_card(data_frame))("home_page_pledges")
        ),
        vm.Figure(
            id="attrition_kpi",
            figure=capture('figure')(lambda data_frame: metrics.kpi.attrition_rate_avg.create_total_attrition_kpi_card(data_frame, start_date=None, end_date=None))("home_page_pledges")
        ),
        vm.Figure(
            id="active_donors_kpi",
            figure=capture('figure')(lambda data_frame: metrics.kpi.active_donors.kpi_card(data_frame))("home_page_pledges")
        ),
        # vm.Figure(
        #     id="active_donors_kpi",
        #     figure=create_kpi_card(
        #         title="Active Donors",
        #         subtitle="Currently contributing donors",
        #         value="{:,}".format(metrics.monthly.all_active_donors.calculate_all_active_donors(pledges_df)),
        #         target_value="1,200",
        #         is_on_target=metrics.monthly.all_active_donors.calculate_all_active_donors(pledges_df) >= 1200,
        #         additional_metrics=["One-time and recurring"]
        #     )
        # )
    ]
    fiscal_year_metrics = vm.Tabs(
        tabs=[
            vm.Container(
                title="Money Moved",
                components=[
                    vm.Graph(
                        id="money_moved_fiscal_year",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_chart(data_frame, counterfactual=False))("home_page_payments")
                    ),
                ]
            ),
            vm.Container(
                title="Money Moved Counterfactual",
                components=[
                    vm.Graph(
                        id="money_moved_fiscal_year_counterfactual",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_chart(data_frame, counterfactual=True))("home_page_payments")
                    ),
                ]
            ),
            vm.Container(
                title="By Payment Platform",
                components=[
                    vm.Graph(
                        id="money_moved_platform",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="payment_platform", counterfactual=False))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Payment Platform (Counterfactual)",
                components=[
                    vm.Graph(
                        id="money_moved_platform_counterfactual",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="payment_platform", counterfactual=True))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Donor Chapter",
                components=[
                    vm.Graph(
                        id="money_moved_donor_chapter",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="donor_chapter", counterfactual=False))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Donor Chapter (Counterfactual)",
                components=[
                    vm.Graph(
                        id="money_moved_donor_chapter_counterfactual",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="donor_chapter", counterfactual=True))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Chapter Type",
                components=[
                    vm.Graph(
                        id="money_moved_chapter_type",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="chapter_type", counterfactual=False))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Chapter Type (Counterfactual)",
                components=[
                    vm.Graph(
                        id="money_moved_chapter_type_counterfactual",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="chapter_type", counterfactual=True))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Currency",
                components=[
                    vm.Graph(
                        id="money_moved_currency",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="currency", counterfactual=False))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Currency (Counterfactual)",
                components=[
                    vm.Graph(
                        id="money_moved_currency_counterfactual",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="currency", counterfactual=True))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Portfolio",
                components=[
                    vm.Graph(
                        id="money_moved_portfolio",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="portfolio", counterfactual=False))("home_page_merged")
                    ),
                ]
            ),
            vm.Container(
                title="By Portfolio (Counterfactual)",
                components=[
                    vm.Graph(
                        id="money_moved_portfolio_counterfactual",
                        figure=capture('graph')(lambda data_frame: metrics.fiscal_year.money_moved.money_moved_bar_chart(data_frame, breakdown_by="portfolio", counterfactual=True))("home_page_merged")
                    ),
                ]
            ),
        ]
    )
    
    # Create the home page
    return vm.Page(
        title="Fiscal Year Metrics",
        layout=vm.Grid(
            grid=[[0, 1, 2],
                  [3, 4, 5],  # KPI cards on top, monthly metrics below
                  [6, 6, 6],
                  [6, 6, 6]],  # KPI cards on top, monthly metrics below
            row_min_height='250px'
        ),
        components=[*kpi_cards, fiscal_year_metrics],
        controls=[
            vm.Parameter(
                targets=[
                    "money_moved_kpi.data_frame.fiscal_year",
                    "arr_kpi.data_frame.fiscal_year",
                    "future_arr_kpi.data_frame.fiscal_year",
                    "active_arr_kpi.data_frame.fiscal_year",
                    "attrition_kpi.data_frame.fiscal_year",
                    "active_donors_kpi.data_frame.fiscal_year",
                    "money_moved_fiscal_year.data_frame.fiscal_year",
                    "money_moved_fiscal_year_counterfactual.data_frame.fiscal_year",
                    "money_moved_platform.data_frame.fiscal_year",
                    "money_moved_platform_counterfactual.data_frame.fiscal_year",
                    "money_moved_donor_chapter.data_frame.fiscal_year",
                    "money_moved_donor_chapter_counterfactual.data_frame.fiscal_year",
                    "money_moved_chapter_type.data_frame.fiscal_year",
                    "money_moved_chapter_type_counterfactual.data_frame.fiscal_year",
                    "money_moved_currency.data_frame.fiscal_year",
                    "money_moved_currency_counterfactual.data_frame.fiscal_year",
                    "money_moved_portfolio.data_frame.fiscal_year",
                    "money_moved_portfolio_counterfactual.data_frame.fiscal_year",
                ],
                # value=calculate_fiscal_year(datetime.now()),
                selector=vm.Dropdown(
                    options=[
                        calculate_fiscal_year(datetime(year, 7, 1))
                        for year in reversed(range(
                            min(pd.to_datetime(payments_df['date']).dt.year),
                            max(pd.to_datetime(payments_df['date']).dt.year)
                        ))
                    ],
                    multi=False
                )
            )
        ]

        # controls=[
        #     vm.Filter(
        #         column="date",
        #         targets=["monthly_donations", "monthly_donations_breakdown", "monthly_pledges", "chapter_arr", "active_recurring_donors"],
        #         selector=vm.DatePicker(
        #             title="Select Month",
        #             value=datetime.now().strftime("%Y-%m")
        #         )
        #     ),
        #     vm.Filter(
        #         column="chapter_type",
        #         targets=["chapter_arr"],
        #         selector=vm.Dropdown(
        #             title="Chapter Type",
        #             multi=True
        #         )
        #     ),
        #     vm.Filter(
        #         column="payment_platform",
        #         targets=["monthly_donations", "monthly_donations_breakdown"],
        #         selector=vm.Dropdown(
        #             title="Payment Platform",
        #             multi=True
        #         )
        #     )
        # ]
    )

def create_channel_chapter_page(pledges_df):
    """Both channel and chapter are the same thing according to metadata.md"""
    from vizro.managers import data_manager
    
    def get_pledges_df():
        return pledges_df

    # Register the pledges data with the data manager
    data_manager["channel_chapter_pledges"] = get_pledges_df

    @capture('graph')
    def active_and_pledged_donors_chart(data_frame):
        return metrics.bar_charts.chapter_arr.custom_chart(data_frame, start_column='pledge_created_at', end_column='pledge_ended_at')
    
    @capture('graph')
    def active_donors_chart(data_frame):
        return metrics.bar_charts.chapter_arr.custom_chart(data_frame, start_column='pledge_starts_at', end_column='pledge_ended_at')
    
    @capture('graph')
    def pledged_donors_chart(data_frame):
        return metrics.bar_charts.chapter_arr.custom_chart(data_frame, start_column='pledge_created_at', end_column='pledge_starts_at')
    
    # Create the page components using the registered data
    
    return vm.Page(
        title="Annual Recurring Revenue by Chapter",
        layout=vm.Grid(
            grid=[
                [0], [1], [1], [1], [1], [1], [1], [1],
            ],
            row_gap='0px'
        ),
        components=[
            vm.Text(text="""
                Both channel and chapter are the same thing according to the [project metadata](https://docs.google.com/spreadsheets/d/1XSlvYfBxqAPvdXLCG7hnVzjCCjAtQ5CpGUebhU-8sPg/edit?usp=sharing).
                    
                Hold left-click and drag the mouse on the graph to zoom-in.
            """),
            vm.Tabs(tabs=[
                vm.Container(
                    title="Active + Pledged Donors",
                    components=[
                        vm.Graph(
                            id="active_and_pledged_donors_chart",
                            figure=active_and_pledged_donors_chart("channel_chapter_pledges"),
                        ),
                    ]
                ),
                vm.Container(
                    title="Active Donors",
                    components=[
                        vm.Graph(
                            id="active_donors_chart",
                            figure=active_donors_chart("channel_chapter_pledges"),
                        ),
                    ]
                ),
                vm.Container(
                    title="Pledged Donors",
                    components=[
                        vm.Graph(
                            id="pledged_donors_chart",
                            figure=pledged_donors_chart("channel_chapter_pledges"),
                        ),
                    ]
                ),
            ])
        ],
        controls=[
            vm.Filter(
                column="chapter_type",
                targets=["active_and_pledged_donors_chart", "active_donors_chart", "pledged_donors_chart"],
                selector=vm.Dropdown(
                    title="Chapter Type",
                    options=sorted(pledges_df['chapter_type'].unique()),
                    multi=True,
                    value=['ALL']
                )
            ),
        ]
    )

def create_monthly_metrics_page(payments_df, pledges_df, merged_df):
    """Create the monthly metrics page"""
    import metrics.monthly.active_recurring_donors
    import metrics.monthly.all_active_donors
    import metrics.monthly.arr
    import metrics.monthly.attrition
    import metrics.monthly.monthly_donations
    import metrics.monthly.pledges

    from vizro.managers import data_manager

    def calculate_fiscal_year(date):
        if date.month < 7:
            return f"{date.year - 1}-{date.year}"
        else:
            return f"{date.year}-{date.year + 1}"
    
    def get_payments_df():
        df = payments_df
        return df

    def get_pledges_df():
        df = pledges_df
        return df

    def get_merged_df():
        df = merged_df
        return df

    # Register the data with the data manager
    data_manager["monthly_metrics_payments"] = get_payments_df
    data_manager["monthly_metrics_pledges"] = get_pledges_df
    data_manager["monthly_metrics_merged"] = get_merged_df
    
    return vm.Page(
        title="Monthly Metrics",
        layout=vm.Grid(
            grid=[
                [0], [1], [1], [2], [2], [3], [3], [4], [4], [5], [5], [5], [5]
            ],
            # row_gap='',
            row_min_height='200px'
        ),
        components=[
            vm.Text(text="""
                Table of contents:
                - [Donors with Active Pledges Per Month](#active_recurring_donors_chart)
                - [All Active Donors at Month End](#all_active_donors_chart)
                - [Attrition Rate](#attrition_rate_chart)
                - [Monthly Donations](#monthly_donations_chart)
                - [Active + Pledged Donors](#pledges_chart)
                - [Active Donors](#active_pledges_chart)
                - [Pledged Donors](#future_pledges_chart)
                - [Annual Recurring Revenue](#arr_chart)
            """),
            # active recurring donors
            vm.Graph(
                id="active_recurring_donors_chart",
                figure=capture('graph')(lambda data_frame: metrics.monthly.active_recurring_donors.custom_chart(data_frame))("monthly_metrics_pledges")
            ),
            # all active donors
            vm.Graph(
                id="all_active_donors_chart",
                figure=capture('graph')(lambda data_frame: metrics.monthly.all_active_donors.custom_chart(data_frame))("monthly_metrics_pledges")
            ),
            # attrition rate
            vm.Graph(
                id="attrition_rate_chart",
                figure=capture('graph')(lambda data_frame: metrics.monthly.attrition.attrition_chart(data_frame))("monthly_metrics_pledges")
            ),
            # monthly donations
            vm.Graph(
                id="monthly_donations_chart",
                figure=capture('graph')(lambda data_frame: metrics.monthly.monthly_donations.custom_chart(data_frame))("monthly_metrics_payments")
            ),
            # arr and pledges
            vm.Tabs(tabs=[
                vm.Container(
                    title="Active + Pledged Donors",
                    components=[
                        vm.Graph(
                            id="pledges_chart",
                            figure=capture('graph')(lambda data_frame: metrics.monthly.pledges.pledges_chart(data_frame))("monthly_metrics_pledges")
                        ),
                        vm.Graph(
                            id="arr_chart",
                            figure=capture('graph')(lambda data_frame: metrics.monthly.arr.custom_chart(data_frame, start_column='pledge_created_at', end_column='pledge_ended_at'))("monthly_metrics_pledges")
                        )
                    ]
                ),
                vm.Container(
                    title="Active Donors",
                    components=[
                        vm.Graph(
                            id="active_pledges_chart",
                            figure=capture('graph')(lambda data_frame: metrics.monthly.pledges.active_pledges_chart(data_frame))("monthly_metrics_pledges")
                        ),
                        vm.Graph(
                            id="active_arr_chart",
                            figure=capture('graph')(lambda data_frame: metrics.monthly.arr.custom_chart(data_frame, start_column='pledge_starts_at', end_column='pledge_ended_at'))("monthly_metrics_pledges")
                        )
                    ]
                ),
                vm.Container(
                    title="Pledged Donors",
                    components=[
                        vm.Graph(
                            id="future_pledges_chart",
                            figure=capture('graph')(lambda data_frame: metrics.monthly.pledges.future_pledges_chart(data_frame))("monthly_metrics_pledges")
                        ),
                        vm.Graph(
                            id="future_arr_chart",
                            figure=capture('graph')(lambda data_frame: metrics.monthly.arr.custom_chart(data_frame, start_column='pledge_created_at', end_column='pledge_starts_at'))("monthly_metrics_pledges")
                        )
                    ]
                )
            ])
        ]
    )

def create_ai_page(payments_df, pledges_df, merged_df):
    """Create the AI graph generator page"""
    return vm.Page(
        title="AI Graph Generator - use for quick insights (May be inaccurate)",
        components=[
            AIGraphGenerator(
                id="graph_container",
                data_frames={
                    "Pledges": pledges_df,
                    "Payments": payments_df,
                    "Merged": merged_df
                }
            )
        ]
    )

if __name__ == "__main__":
    payments_df = load_payments()
    pledges_df = load_pledges()
    merged_df = load_merged_payments_and_pledges()

    # Create the dashboard
    dashboard = vm.Dashboard(
        pages=[
            create_home_page(payments_df, pledges_df, merged_df),
            create_monthly_metrics_page(payments_df, pledges_df, merged_df),
            create_channel_chapter_page(pledges_df),
            create_ai_page(payments_df, pledges_df, merged_df),
        ],
        title="One for the World Analytics"
    )
    
    # Build and run the dashboard
    app = Vizro().build(dashboard)
    
    # Find an available port
    from utils.developer_tools import find_available_port
    port = find_available_port()
    
    # Run the app
    app.run(debug=True, port=port)