forked from davidcomfort/dash_sample_dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
callbacks.py
707 lines (629 loc) · 31.8 KB
/
callbacks.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
from dash.dependencies import Input, Output
from app import app
import plotly.graph_objs as go
from plotly import tools
from datetime import datetime as dt
from datetime import date, timedelta
from datetime import datetime
import numpy as np
import pandas as pd
import io
import xlsxwriter
import flask
from flask import send_file
from components import formatter_currency, formatter_currency_with_cents, formatter_percent, formatter_percent_2_digits, formatter_number
from components import update_first_datatable, update_first_download, update_second_datatable, update_graph
pd.options.mode.chained_assignment = None
# Read in Travel Report Data
df = pd.read_csv('data/performance_analytics_cost_and_ga_metrics.csv')
df.rename(columns={
'Travel Product': 'Placement type',
'Spend - This Year': 'Spend TY',
'Spend - Last Year': 'Spend LY',
'Sessions - This Year': 'Sessions - TY',
'Sessions - Last Year': 'Sessions - LY',
'Bookings - This Year': 'Bookings - TY',
'Bookings - Last Year': 'Bookings - LY',
'Revenue - This Year': 'Revenue - TY',
'Revenue - Last Year': 'Revenue - LY',
}, inplace=True)
df['Date'] = pd.to_datetime(df['Date'])
current_year = df['Year'].max()
current_week = df[df['Year'] == current_year]['Week'].max()
now = datetime.now()
datestamp = now.strftime("%Y%m%d")
columns = ['Spend TY', 'Spend LY', 'Sessions - TY', 'Sessions - LY', 'Bookings - TY', 'Bookings - LY', 'Revenue - TY', 'Revenue - LY']
columns_complete = ['Placement type', 'Spend TY', 'Spend - LP', 'Spend PoP (Abs)', 'Spend PoP (%)', 'Spend LY', 'Spend YoY (%)', \
'Sessions - TY', 'Sessions - LP', 'Sessions - LY', 'Sessions PoP (%)', 'Sessions YoY (%)', \
'Bookings - TY', 'Bookings - LP', 'Bookings PoP (%)', 'Bookings PoP (Abs)', 'Bookings - LY', 'Bookings YoY (%)', 'Bookings YoY (Abs)', \
'Revenue - TY', 'Revenue - LP', 'Revenue PoP (Abs)', 'Revenue PoP (%)', 'Revenue - LY', 'Revenue YoY (%)', 'Revenue YoY (Abs)']
columns_condensed = ['Placement type', 'Spend TY', 'Spend PoP (%)', 'Spend YoY (%)', 'Sessions - TY', 'Sessions PoP (%)', 'Sessions YoY (%)', \
'Bookings - TY', 'Bookings PoP (%)', 'Bookings YoY (%)',]
conditional_columns = ['Spend_PoP_abs_conditional', 'Spend_PoP_percent_conditional', 'Spend_YoY_percent_conditional',
'Sessions_PoP_percent_conditional', 'Sessions_YoY_percent_conditional',
'Bookings_PoP_abs_conditional', 'Bookings_YoY_abs_conditional', 'Bookings_PoP_percent_conditional', 'Bookings_YoY_percent_conditional',
'Revenue_PoP_abs_conditional', 'Revenue_YoY_abs_conditional', 'Revenue_PoP_percent_conditional', 'Revenue_YoY_percent_conditional',]
dt_columns_total = ['Placement type', 'Spend TY', 'Spend - LP', 'Spend PoP (Abs)', 'Spend PoP (%)', 'Spend LY', 'Spend YoY (%)', \
'Sessions - TY', 'Sessions - LP', 'Sessions - LY', 'Sessions PoP (%)', 'Sessions YoY (%)', \
'Bookings - TY', 'Bookings - LP', 'Bookings PoP (%)', 'Bookings PoP (Abs)', 'Bookings - LY', 'Bookings YoY (%)', 'Bookings YoY (Abs)', \
'Revenue - TY', 'Revenue - LP', 'Revenue PoP (Abs)', 'Revenue PoP (%)', 'Revenue - LY', 'Revenue YoY (%)', 'Revenue YoY (Abs)',
'Spend_PoP_abs_conditional', 'Spend_PoP_percent_conditional', 'Spend_YoY_percent_conditional',
'Sessions_PoP_percent_conditional', 'Sessions_YoY_percent_conditional',
'Bookings_PoP_abs_conditional', 'Bookings_YoY_abs_conditional', 'Bookings_PoP_percent_conditional', 'Bookings_YoY_percent_conditional',
'Revenue_PoP_abs_conditional', 'Revenue_YoY_abs_conditional', 'Revenue_PoP_percent_conditional', 'Revenue_YoY_percent_conditional',]
######################## Birst Category Callbacks ########################
#### Date Picker Callback
@app.callback(Output('output-container-date-picker-range-birst-category', 'children'),
[Input('my-date-picker-range-birst-category', 'start_date'),
Input('my-date-picker-range-birst-category', 'end_date')])
def update_output(start_date, end_date):
string_prefix = 'You have selected '
if start_date is not None:
start_date = dt.strptime(start_date, '%Y-%m-%d')
start_date_string = start_date.strftime('%B %d, %Y')
string_prefix = string_prefix + 'a Start Date of ' + start_date_string + ' | '
if end_date is not None:
end_date = dt.strptime(end_date, '%Y-%m-%d')
end_date_string = end_date.strftime('%B %d, %Y')
days_selected = (end_date - start_date).days
prior_start_date = start_date - timedelta(days_selected + 1)
prior_start_date_string = datetime.strftime(prior_start_date, '%B %d, %Y')
prior_end_date = end_date - timedelta(days_selected + 1)
prior_end_date_string = datetime.strftime(prior_end_date, '%B %d, %Y')
string_prefix = string_prefix + 'End Date of ' + end_date_string + ', for a total of ' + str(days_selected + 1) + ' Days. The prior period Start Date was ' + \
prior_start_date_string + ' | End Date: ' + prior_end_date_string + '.'
if len(string_prefix) == len('You have selected: '):
return 'Select a date to see it displayed here'
else:
return string_prefix
# Callback and update first data table
@app.callback(Output('datatable-birst-category', 'data'),
[Input('my-date-picker-range-birst-category', 'start_date'),
Input('my-date-picker-range-birst-category', 'end_date')])
def update_data_1(start_date, end_date):
data_1 = update_first_datatable(start_date, end_date, None, 'Birst Category')
return data_1
# Callback and update data table columns
@app.callback(Output('datatable-birst-category', 'columns'),
[Input('radio-button-birst-category', 'value')])
def update_columns(value):
if value == 'Complete':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_complete]
elif value == 'Condensed':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_condensed]
return column_set
# Callback for excel download
@app.callback(
Output('download-link-birst-category', 'href'),
[Input('my-date-picker-range-birst-category', 'start_date'),
Input('my-date-picker-range-birst-category', 'end_date')])
def update_link(start_date, end_date):
return '/cc-travel-report/birst-category/urlToDownload?value={}/{}'.format(dt.strptime(start_date,'%Y-%m-%d').strftime('%Y-%m-%d'),dt.strptime(end_date,'%Y-%m-%d').strftime('%Y-%m-%d'))
@app.server.route("/cc-travel-report/birst-category/urlToDownload")
def download_excel_birst_category():
value = flask.request.args.get('value')
#here is where I split the value
value = value.split('/')
start_date = value[0]
end_date = value[1]
filename = datestamp + '_birst_category_' + start_date + '_to_' + end_date + '.xlsx'
# Dummy Dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
buf = io.BytesIO()
excel_writer = pd.ExcelWriter(buf, engine="xlsxwriter")
download_1 = update_first_download(start_date, end_date, None, 'Birst Category')
download_1.to_excel(excel_writer, sheet_name="sheet1", index=False)
# df.to_excel(excel_writer, sheet_name="sheet1", index=False)
excel_writer.save()
excel_data = buf.getvalue()
buf.seek(0)
return send_file(
buf,
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename=filename,
as_attachment=True,
cache_timeout=0
)
# Callback and update second data table
@app.callback(
Output('datatable-birst-category-2', 'data'),
[Input('my-date-picker-range-birst-category', 'start_date'),
Input('my-date-picker-range-birst-category', 'end_date')])
def update_data_2(start_date, end_date):
data_2 = update_second_datatable(start_date, end_date, None, 'Birst Category')
return data_2
# Callback for the Graphs
@app.callback(
Output('birst-category', 'figure'),
[Input('datatable-birst-category', "selected_rows"),
Input('my-date-picker-range-birst-category', 'end_date')])
def update_birst_category(selected_rows, end_date):
travel_product = []
travel_product_list = sorted(df['Birst Category'].unique().tolist())
for i in selected_rows:
travel_product.append(travel_product_list[i])
# Filter by specific product
filtered_df = df[(df['Birst Category'].isin(travel_product))].groupby(['Year', 'Week']).sum()[['Spend TY', 'Spend LY', 'Sessions - TY', 'Sessions - LY', 'Bookings - TY', 'Bookings - LY', 'Revenue - TY', 'Revenue - LY']].reset_index()
fig = update_graph(filtered_df, end_date)
return fig
######################## GA Category Callbacks ########################
#### Date Picker Callback
@app.callback(Output('output-container-date-picker-range-ga-category', 'children'),
[Input('my-date-picker-range-ga-category', 'start_date'),
Input('my-date-picker-range-ga-category', 'end_date')])
def update_output(start_date, end_date):
string_prefix = 'You have selected '
if start_date is not None:
start_date = dt.strptime(start_date, '%Y-%m-%d')
start_date_string = start_date.strftime('%B %d, %Y')
string_prefix = string_prefix + 'a Start Date of ' + start_date_string + ' | '
if end_date is not None:
end_date = dt.strptime(end_date, '%Y-%m-%d')
end_date_string = end_date.strftime('%B %d, %Y')
days_selected = (end_date - start_date).days
prior_start_date = start_date - timedelta(days_selected + 1)
prior_start_date_string = datetime.strftime(prior_start_date, '%B %d, %Y')
prior_end_date = end_date - timedelta(days_selected + 1)
prior_end_date_string = datetime.strftime(prior_end_date, '%B %d, %Y')
string_prefix = string_prefix + 'End Date of ' + end_date_string + ', for a total of ' + str(days_selected + 1) + ' Days. The prior period Start Date was ' + \
prior_start_date_string + ' | End Date: ' + prior_end_date_string + '.'
if len(string_prefix) == len('You have selected: '):
return 'Select a date to see it displayed here'
else:
return string_prefix
# Callback and update first data table
@app.callback(Output('datatable-ga-category', 'data'),
[Input('my-date-picker-range-ga-category', 'start_date'),
Input('my-date-picker-range-ga-category', 'end_date')])
def update_data_1(start_date, end_date):
data_1 = update_first_datatable(start_date, end_date, None, 'GA Category')
return data_1
# Callback and update data table columns
@app.callback(Output('datatable-ga-category', 'columns'),
[Input('radio-button-ga-category', 'value')])
def update_columns(value):
if value == 'Complete':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_complete]
elif value == 'Condensed':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_condensed]
return column_set
# Callback for excel download
@app.callback(
Output('download-link-ga-category', 'href'),
[Input('my-date-picker-range-ga-category', 'start_date'),
Input('my-date-picker-range-ga-category', 'end_date')])
def update_link(start_date, end_date):
return '/cc-travel-report/ga-category/urlToDownload?value={}/{}'.format(dt.strptime(start_date,'%Y-%m-%d').strftime('%Y-%m-%d'),dt.strptime(end_date,'%Y-%m-%d').strftime('%Y-%m-%d'))
@app.server.route("/cc-travel-report/ga-category/urlToDownload")
def download_excel_ga_category():
value = flask.request.args.get('value')
#here is where I split the value
value = value.split('/')
start_date = value[0]
end_date = value[1]
filename = datestamp + '_ga_category_' + start_date + '_to_' + end_date + '.xlsx'
# Dummy Dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
buf = io.BytesIO()
excel_writer = pd.ExcelWriter(buf, engine="xlsxwriter")
download_1 = update_first_download(start_date, end_date, None, 'GA Category')
download_1.to_excel(excel_writer, sheet_name="sheet1", index=False)
# df.to_excel(excel_writer, sheet_name="sheet1", index=False)
excel_writer.save()
excel_data = buf.getvalue()
buf.seek(0)
return send_file(
buf,
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename=filename,
as_attachment=True,
cache_timeout=0
)
# Callback and update second data table
@app.callback(
Output('datatable-ga-category-2', 'data'),
[Input('my-date-picker-range-ga-category', 'start_date'),
Input('my-date-picker-range-ga-category', 'end_date')])
def update_data_2(start_date, end_date):
data_2 = update_second_datatable(start_date, end_date, None, 'GA Category')
return data_2
# Callback for the Graphs
@app.callback(
Output('ga-category', 'figure'),
[Input('datatable-ga-category', "selected_rows"),
Input('my-date-picker-range-ga-category', 'end_date')])
def update_ga_category(selected_rows, end_date):
travel_product = []
travel_product_list = sorted(df['GA Category'].unique().tolist())
for i in selected_rows:
travel_product.append(travel_product_list[i])
# Filter by specific product
filtered_df = df[(df['GA Category'].isin(travel_product))].groupby(['Year', 'Week']).sum()[['Spend TY', 'Spend LY', 'Sessions - TY', 'Sessions - LY', 'Bookings - TY', 'Bookings - LY', 'Revenue - TY', 'Revenue - LY']].reset_index()
fig = update_graph(filtered_df, end_date)
return fig
######################## Paid Search Callbacks ########################
#### Date Picker Callback
@app.callback(Output('output-container-date-picker-range-paid-search', 'children'),
[Input('my-date-picker-range-paid-search', 'start_date'),
Input('my-date-picker-range-paid-search', 'end_date')])
def update_output(start_date, end_date):
string_prefix = 'You have selected '
if start_date is not None:
start_date = dt.strptime(start_date, '%Y-%m-%d')
start_date_string = start_date.strftime('%B %d, %Y')
string_prefix = string_prefix + 'a Start Date of ' + start_date_string + ' | '
if end_date is not None:
end_date = dt.strptime(end_date, '%Y-%m-%d')
end_date_string = end_date.strftime('%B %d, %Y')
days_selected = (end_date - start_date).days
prior_start_date = start_date - timedelta(days_selected + 1)
prior_start_date_string = datetime.strftime(prior_start_date, '%B %d, %Y')
prior_end_date = end_date - timedelta(days_selected + 1)
prior_end_date_string = datetime.strftime(prior_end_date, '%B %d, %Y')
string_prefix = string_prefix + 'End Date of ' + end_date_string + ', for a total of ' + str(days_selected + 1) + ' Days. The prior period Start Date was ' + \
prior_start_date_string + ' | End Date: ' + prior_end_date_string + '.'
if len(string_prefix) == len('You have selected: '):
return 'Select a date to see it displayed here'
else:
return string_prefix
# Callback and update first data table
@app.callback(Output('datatable-paid-search', 'data'),
[Input('my-date-picker-range-paid-search', 'start_date'),
Input('my-date-picker-range-paid-search', 'end_date')])
def update_data_1(start_date, end_date):
data_1 = update_first_datatable(start_date, end_date, 'Paid Search', 'Placement type')
return data_1
# Callback and update data table columns
@app.callback(Output('datatable-paid-search', 'columns'),
[Input('radio-button-paid-search', 'value')])
def update_columns(value):
if value == 'Complete':
column_set=[{"name": i, "id": i, 'deletable': True} for i in columns_complete] + [{"name": j, "id": j, 'hidden': 'True'} for j in conditional_columns]
elif value == 'Condensed':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_condensed]
return column_set
# Callback for excel download
@app.callback(
Output('download-link-paid-search-1', 'href'),
[Input('my-date-picker-range-paid-search', 'start_date'),
Input('my-date-picker-range-paid-search', 'end_date')])
def update_link(start_date, end_date):
return '/cc-travel-report/paid-search/urlToDownload?value={}/{}'.format(dt.strptime(start_date,'%Y-%m-%d').strftime('%Y-%m-%d'),dt.strptime(end_date,'%Y-%m-%d').strftime('%Y-%m-%d'))
@app.server.route("/cc-travel-report/paid-search/urlToDownload")
def download_excel_1():
value = flask.request.args.get('value')
#here is where I split the value
value = value.split('/')
start_date = value[0]
end_date = value[1]
filename = datestamp + '_paid_search_' + start_date + '_to_' + end_date + '.xlsx'
# Dummy Dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
buf = io.BytesIO()
excel_writer = pd.ExcelWriter(buf, engine="xlsxwriter")
download_1 = update_first_download(start_date, end_date, 'Paid Search', 'Placement type')
download_1.to_excel(excel_writer, sheet_name="sheet1", index=False)
# df.to_excel(excel_writer, sheet_name="sheet1", index=False)
excel_writer.save()
excel_data = buf.getvalue()
buf.seek(0)
return send_file(
buf,
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename=filename,
as_attachment=True,
cache_timeout=0
)
# Callback and update second data table
@app.callback(
Output('datatable-paid-search-2', 'data'),
[Input('my-date-picker-range-paid-search', 'start_date'),
Input('my-date-picker-range-paid-search', 'end_date')])
def update_data_2(start_date, end_date):
data_2 = update_second_datatable(start_date, end_date, 'Paid Search', 'Placement type')
return data_2
# Callback for the Graphs
@app.callback(
Output('paid-search', 'figure'),
[Input('datatable-paid-search', "selected_rows"),
Input('my-date-picker-range-paid-search', 'end_date')])
def update_paid_search(selected_rows, end_date):
travel_product = []
travel_product_list = df[(df['Category'] == 'Paid Search')]['Placement type'].unique().tolist()
for i in selected_rows:
travel_product.append(travel_product_list[i])
# Filter by specific product
filtered_df = df[(df['Placement type'].isin(travel_product))].groupby(['Year', 'Week']).sum()[['Spend TY', 'Spend LY', 'Sessions - TY', 'Sessions - LY', 'Bookings - TY', 'Bookings - LY', 'Revenue - TY', 'Revenue - LY']].reset_index()
fig = update_graph(filtered_df, end_date)
return fig
######################## Display Callbacks ########################
#### Date Picker Callback
@app.callback(Output('output-container-date-picker-range-display', 'children'),
[Input('my-date-picker-range-display', 'start_date'),
Input('my-date-picker-range-display', 'end_date')])
def update_output_display(start_date, end_date):
string_prefix = 'You have selected '
if start_date is not None:
start_date = dt.strptime(start_date, '%Y-%m-%d')
start_date_string = start_date.strftime('%B %d, %Y')
string_prefix = string_prefix + 'a Start Date of ' + start_date_string + ' | '
if end_date is not None:
end_date = dt.strptime(end_date, '%Y-%m-%d')
end_date_string = end_date.strftime('%B %d, %Y')
days_selected = (end_date - start_date).days
prior_start_date = start_date - timedelta(days_selected + 1)
prior_start_date_string = datetime.strftime(prior_start_date, '%B %d, %Y')
prior_end_date = end_date - timedelta(days_selected + 1)
prior_end_date_string = datetime.strftime(prior_end_date, '%B %d, %Y')
string_prefix = string_prefix + 'End Date of ' + end_date_string + ', for a total of ' + str(days_selected + 1) + ' Days. The prior period Start Date was ' + \
prior_start_date_string + ' | End Date: ' + prior_end_date_string + '.'
if len(string_prefix) == len('You have selected: '):
return 'Select a date to see it displayed here'
else:
return string_prefix
# Callback and update first data table
@app.callback(Output('datatable-display', 'data'),
[Input('my-date-picker-range-display', 'start_date'),
Input('my-date-picker-range-display', 'end_date')])
def update_data_1_display(start_date, end_date):
data_1 = update_first_datatable(start_date, end_date, 'Display', 'Placement type')
return data_1
# Callback and update data table columns
@app.callback(Output('datatable-display', 'columns'),
[Input('radio-button-display', 'value')])
def update_columns(value):
if value == 'Complete':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_complete]
elif value == 'Condensed':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_condensed]
return column_set
# Callback for excel download
@app.callback(
Output('download-link-display-1', 'href'),
[Input('my-date-picker-range-display', 'start_date'),
Input('my-date-picker-range-display', 'end_date')])
def update_link(start_date, end_date):
return '/cc-travel-report/display/urlToDownload?value={}/{}'.format(dt.strptime(start_date,'%Y-%m-%d').strftime('%Y-%m-%d'),dt.strptime(end_date,'%Y-%m-%d').strftime('%Y-%m-%d'))
@app.server.route("/cc-travel-report/display/urlToDownload")
def download_excel_display_1():
value = flask.request.args.get('value')
#here is where I split the value
value = value.split('/')
start_date = value[0]
end_date = value[1]
filename = datestamp + '_display_' + start_date + '_to_' + end_date + '.xlsx'
# Dummy Dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
buf = io.BytesIO()
excel_writer = pd.ExcelWriter(buf, engine="xlsxwriter")
download_1 = update_first_download(start_date, end_date, 'Display', 'Placement type')
download_1.to_excel(excel_writer, sheet_name="sheet1", index=False)
# df.to_excel(excel_writer, sheet_name="sheet1", index=False)
excel_writer.save()
excel_data = buf.getvalue()
buf.seek(0)
return send_file(
buf,
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename=filename,
as_attachment=True,
cache_timeout=0
)
# Callback and update second data table
@app.callback(
Output('datatable-display-2', 'data'),
[Input('my-date-picker-range-display', 'start_date'),
Input('my-date-picker-range-display', 'end_date')])
def update_data_2_display(start_date, end_date):
data_2 = update_second_datatable(start_date, end_date, 'Display', 'Placement type')
return data_2
# Callback for the Graphs
@app.callback(
Output('display', 'figure'),
[Input('datatable-display', "selected_rows"),
Input('my-date-picker-range-display', 'end_date')])
def update_display(selected_rows, end_date):
travel_product = []
travel_product_list = df[(df['Category'] == 'Display')]['Placement type'].unique().tolist()
for i in selected_rows:
travel_product.append(travel_product_list[i])
# Filter by specific product
filtered_df = df[(df['Placement type'].isin(travel_product))].groupby(['Year', 'Week']).sum()[['Spend TY', 'Spend LY', 'Sessions - TY', 'Sessions - LY', 'Bookings - TY', 'Bookings - LY', 'Revenue - TY', 'Revenue - LY']].reset_index()
fig = update_graph(filtered_df, end_date)
return fig
######################## Publishing Callbacks ########################
#### Date Picker Callback
@app.callback(Output('output-container-date-picker-range-publishing', 'children'),
[Input('my-date-picker-range-publishing', 'start_date'),
Input('my-date-picker-range-publishing', 'end_date')])
def update_output_publishing(start_date, end_date):
string_prefix = 'You have selected '
if start_date is not None:
start_date = dt.strptime(start_date, '%Y-%m-%d')
start_date_string = start_date.strftime('%B %d, %Y')
string_prefix = string_prefix + 'a Start Date of ' + start_date_string + ' | '
if end_date is not None:
end_date = dt.strptime(end_date, '%Y-%m-%d')
end_date_string = end_date.strftime('%B %d, %Y')
days_selected = (end_date - start_date).days
prior_start_date = start_date - timedelta(days_selected + 1)
prior_start_date_string = datetime.strftime(prior_start_date, '%B %d, %Y')
prior_end_date = end_date - timedelta(days_selected + 1)
prior_end_date_string = datetime.strftime(prior_end_date, '%B %d, %Y')
string_prefix = string_prefix + 'End Date of ' + end_date_string + ', for a total of ' + str(days_selected + 1) + ' Days. The prior period Start Date was ' + \
prior_start_date_string + ' | End Date: ' + prior_end_date_string + '.'
if len(string_prefix) == len('You have selected: '):
return 'Select a date to see it displayed here'
else:
return string_prefix
# Callback and update first data table
@app.callback(Output('datatable-publishing', 'data'),
[Input('my-date-picker-range-publishing', 'start_date'),
Input('my-date-picker-range-publishing', 'end_date')])
def update_data_1_publishing(start_date, end_date):
data_1 = update_first_datatable(start_date, end_date, 'Publishing', 'Placement type')
return data_1
# Callback and update data table columns
@app.callback(Output('datatable-publishing', 'columns'),
[Input('radio-button-publishing', 'value')])
def update_columns(value):
if value == 'Complete':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_complete]
elif value == 'Condensed':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_condensed]
return column_set
# Callback for excel download
@app.callback(
Output('download-link-publishing-1', 'href'),
[Input('my-date-picker-range-publishing', 'start_date'),
Input('my-date-picker-range-publishing', 'end_date')])
def update_link(start_date, end_date):
return '/cc-travel-report/publishing/urlToDownload?value={}/{}'.format(dt.strptime(start_date,'%Y-%m-%d').strftime('%Y-%m-%d'),dt.strptime(end_date,'%Y-%m-%d').strftime('%Y-%m-%d'))
@app.server.route("/cc-travel-report/publishing/urlToDownload")
def download_excel_publishing_1():
value = flask.request.args.get('value')
#here is where I split the value
value = value.split('/')
start_date = value[0]
end_date = value[1]
filename = datestamp + '_publishing_' + start_date + '_to_' + end_date + '.xlsx'
# Dummy Dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
buf = io.BytesIO()
excel_writer = pd.ExcelWriter(buf, engine="xlsxwriter")
download_1 = update_first_download(start_date, end_date, 'Publishing', 'Placement type')
download_1.to_excel(excel_writer, sheet_name="sheet1", index=False)
# df.to_excel(excel_writer, sheet_name="sheet1", index=False)
excel_writer.save()
excel_data = buf.getvalue()
buf.seek(0)
return send_file(
buf,
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename=filename,
as_attachment=True,
cache_timeout=0
)
# Callback and update second data table
@app.callback(
Output('datatable-publishing-2', 'data'),
[Input('my-date-picker-range-publishing', 'start_date'),
Input('my-date-picker-range-publishing', 'end_date')])
def update_data_2_publishing(start_date, end_date):
data_2 = update_second_datatable(start_date, end_date, 'Publishing', 'Placement type')
return data_2
# Callback for the Graphs
@app.callback(
Output('publishing', 'figure'),
[Input('datatable-publishing', "selected_rows"),
Input('my-date-picker-range-publishing', 'end_date')])
def update_publishing(selected_rows, end_date):
travel_product = []
travel_product_list = df[(df['Category'] == 'Publishing')]['Placement type'].unique().tolist()
for i in selected_rows:
travel_product.append(travel_product_list[i])
# Filter by specific product
filtered_df = df[(df['Placement type'].isin(travel_product))].groupby(['Year', 'Week']).sum()[['Spend TY', 'Spend LY', 'Sessions - TY', 'Sessions - LY', 'Bookings - TY', 'Bookings - LY', 'Revenue - TY', 'Revenue - LY']].reset_index()
fig = update_graph(filtered_df, end_date)
return fig
######################## Metasearch Callbacks ########################
#### Date Picker Callback
@app.callback(Output('output-container-date-picker-range-metasearch', 'children'),
[Input('my-date-picker-range-metasearch', 'start_date'),
Input('my-date-picker-range-metasearch', 'end_date')])
def update_output_metasearch(start_date, end_date):
string_prefix = 'You have selected '
if start_date is not None:
start_date = dt.strptime(start_date, '%Y-%m-%d')
start_date_string = start_date.strftime('%B %d, %Y')
string_prefix = string_prefix + 'a Start Date of ' + start_date_string + ' | '
if end_date is not None:
end_date = dt.strptime(end_date, '%Y-%m-%d')
end_date_string = end_date.strftime('%B %d, %Y')
days_selected = (end_date - start_date).days
prior_start_date = start_date - timedelta(days_selected + 1)
prior_start_date_string = datetime.strftime(prior_start_date, '%B %d, %Y')
prior_end_date = end_date - timedelta(days_selected + 1)
prior_end_date_string = datetime.strftime(prior_end_date, '%B %d, %Y')
string_prefix = string_prefix + 'End Date of ' + end_date_string + ', for a total of ' + str(days_selected + 1) + ' Days. The prior period Start Date was ' + \
prior_start_date_string + ' | End Date: ' + prior_end_date_string + '.'
if len(string_prefix) == len('You have selected: '):
return 'Select a date to see it displayed here'
else:
return string_prefix
# Callback and update first data table
@app.callback(Output('datatable-metasearch', 'data'),
[Input('my-date-picker-range-metasearch', 'start_date'),
Input('my-date-picker-range-metasearch', 'end_date')])
def update_data_1_metasearch(start_date, end_date):
data_1 = update_first_datatable(start_date, end_date, 'Metasearch and Travel Ads', 'Placement type')
return data_1
# Callback and update data table columns
@app.callback(Output('datatable-metasearch', 'columns'),
[Input('radio-button-metasearch', 'value')])
def update_columns(value):
if value == 'Complete':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_complete]
elif value == 'Condensed':
column_set=[{"name": i, "id": i, "deletable": True} for i in columns_condensed]
return column_set
# Callback for excel download
@app.callback(
Output('download-link-metasearch-1', 'href'),
[Input('my-date-picker-range-metasearch', 'start_date'),
Input('my-date-picker-range-metasearch', 'end_date')])
def update_link(start_date, end_date):
return '/cc-travel-report/metasearch/urlToDownload?value={}/{}'.format(dt.strptime(start_date,'%Y-%m-%d').strftime('%Y-%m-%d'),dt.strptime(end_date,'%Y-%m-%d').strftime('%Y-%m-%d'))
@app.server.route("/cc-travel-report/metasearch/urlToDownload")
def download_excel_metasearch_1():
value = flask.request.args.get('value')
#here is where I split the value
value = value.split('/')
start_date = value[0]
end_date = value[1]
filename = datestamp + '_metasearch_' + start_date + '_to_' + end_date + '.xlsx'
# Dummy Dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
buf = io.BytesIO()
excel_writer = pd.ExcelWriter(buf, engine="xlsxwriter")
download_1 = update_first_download(start_date, end_date, 'Metasearch and Travel Ads', 'Placement type')
download_1.to_excel(excel_writer, sheet_name="sheet1", index=False)
# df.to_excel(excel_writer, sheet_name="sheet1", index=False)
excel_writer.save()
excel_data = buf.getvalue()
buf.seek(0)
return send_file(
buf,
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename=filename,
as_attachment=True,
cache_timeout=0
)
# Callback and update second data table
@app.callback(
Output('datatable-metasearch-2', 'data'),
[Input('my-date-picker-range-metasearch', 'start_date'),
Input('my-date-picker-range-metasearch', 'end_date')])
def update_data_2_metasearch(start_date, end_date):
data_2 = update_second_datatable(start_date, end_date, 'Metasearch and Travel Ads', 'Placement type')
return data_2
# Callback for the Graphs
@app.callback(
Output('metasearch', 'figure'),
[Input('datatable-metasearch', "selected_rows"),
Input('my-date-picker-range-metasearch', 'end_date')])
def update_metasearch(selected_rows, end_date):
travel_product = []
travel_product_list = df[(df['Category'] == 'Metasearch and Travel Ads')]['Placement type'].unique().tolist()
for i in selected_rows:
travel_product.append(travel_product_list[i])
# Filter by specific product
filtered_df = df[(df['Placement type'].isin(travel_product))].groupby(['Year', 'Week']).sum()[['Spend TY', 'Spend LY', 'Sessions - TY', 'Sessions - LY', 'Bookings - TY', 'Bookings - LY', 'Revenue - TY', 'Revenue - LY']].reset_index()
fig = update_graph(filtered_df, end_date)
return fig