forked from alpha-canada-ca/cra-arc.performance
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoverview_calldrivers.php
1259 lines (1007 loc) · 57.4 KB
/
overview_calldrivers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php include "./includes/upd_header.php"; ?>
<?php include "./includes/upd_sidebar.php"; ?>
<?php include "./includes/date-ranges.php"; ?>
<?php include "./includes/functions.php"; ?>
<?php ini_set('display_errors', 0);
?>
<!--Translation Code start-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="./assets/i18n/js/CLDRPluralRuleParser.js"></script>
<script src="./assets/i18n/js/jquery.i18n.js"></script>
<script src="./assets/i18n/js/jquery.i18n.messagestore.js"></script>
<script src="./assets/i18n/js/jquery.i18n.fallbacks.js"></script>
<script src="./assets/i18n/js/jquery.i18n.language.js"></script>
<script src="./assets/i18n/js/jquery.i18n.parser.js"></script>
<script src="./assets/i18n/js/jquery.i18n.emitter.js"></script>
<script src="./assets/i18n/js/jquery.i18n.emitter.bidi.js"></script>
<script src="./assets/i18n/js/global.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-legend/2.25.6/d3-legend.min.js"></script>
<!--Main content start-->
<h1 class="visually-hidden">Usability Performance Dashboard</h1>
<h2 class="h3 pt-2 pb-2" data-i18n="overview-title">Overview of CRA website</h2>
<!-- Tabs menu -->
<div class="tabs sticky">
<ul>
<li <?php if ($tab=="summary") {echo "class='is-active'";} ?>><a href="./overview_summary.php" data-i18n="tab-summary">Summary</a></li>
<li <?php if ($tab=="webtraffic") {echo "class='is-active'";} ?>><a href="./overview_webtraffic.php" data-i18n="tab-webtraffic">Web traffic</a></li>
<li <?php if ($tab=="searchanalytics") {echo "class='is-active'";} ?>><a href="./overview_searchanalytics.php" data-i18n="tab-searchanalytics">Search analytics</a></li>
<li <?php if ($tab=="pagefeedback") {echo "class='is-active'";} ?>><a href="./overview_pagefeedback.php" data-i18n="tab-pagefeedback">Page feedback</a></li>
<li <?php if ($tab=="calldrivers") {echo "class='is-active'";} ?>><a href="#" data-i18n="tab-calldrivers">Call drivers</a></li>
<li <?php if ($tab=="uxtests") {echo "class='is-active'";} ?>><a href="./overview_uxtests.php" data-i18n="tab-uxtests">UX tests</a></li>
</ul>
</div>
<?php
ini_set('display_errors', 1);
require 'vendor/autoload.php';
use TANIOS\Airtable\Airtable;
// Adobe Analytics
// $time = microtime(true);
// $succ = 0;
//
// if (!isset($_SESSION['CREATED']))
// {
// $_SESSION['CREATED'] = time();
// require_once ('./php/getToken.php');
// $succ = 1;
// }
// else if (time() - $_SESSION['CREATED'] > 86400)
// {
// session_regenerate_id(true);
// $_SESSION['CREATED'] = time();
// require_once ('./php/getToken.php');
// $succ = 1;
// }
// if (isset($_SESSION["token"]))
// {
// $succ = 1;
// }
//
// if ($succ === 1)
// {
// require_once ('./php/api_post.php');
// $config = include ('./php/config-aa.php');
// $data = include ('./php/data-aa.php');
// Get Date for AA
$iso = 'Y-m-d\TH:i:s.v';
$previousWeekStart = strtotime("last sunday midnight", strtotime("-2 week +1 day"));
$previousWeekEnd = strtotime("next sunday", $previousWeekStart);
$previousWeekStart = date($iso, $previousWeekStart);
$previousWeekEnd = date($iso, $previousWeekEnd);
$weekStart = strtotime("last sunday midnight", strtotime("-1 week +1 day"));
$weekEnd = strtotime("next sunday", $weekStart);
$weekStart = date($iso, $weekStart);
$weekEnd = date($iso, $weekEnd);
$monthStart = (new DateTime("first day of last month midnight"))->format($iso);
$monthEnd = (new DateTime("first day of this month midnight"))->format($iso);
$previousMonthStart = (new DateTime("first day of -2 month midnight"))->format($iso);
$previousMonthEnd = $monthStart;
// echo $monthStart."<br>";
// echo $monthEnd."<br>";
// echo $previousMonthStart."<br>";
// echo $previousMonthEnd."<br>";
// Get date for GSC
$iso = 'Y-m-d';
$startLastGSC = (new DateTime($previousWeekStart))->format($iso);
$endLastGSC = (new DateTime($previousWeekEnd))->modify('-1 days')
->format($iso);
$startGSC = (new DateTime($weekStart))->format($iso);
$endGSC = (new DateTime($weekEnd))->modify('-1 days')
->format($iso);
$dates = [[$startLastGSC, $endLastGSC], [$startGSC, $endGSC]];
// echo "<pre>";
// print_r($dates);
// echo "</pre>";
// Get date for header
$iso = 'M d';
$startLastHeader = (new DateTime($previousWeekStart))->format($iso);
$endLastHeader = (new DateTime($previousWeekEnd))->modify('-1 days')
->format($iso);
$startHeader = (new DateTime($weekStart))->format($iso);
$endHeader = (new DateTime($weekEnd))->modify('-1 days')
->format($iso);
// Weekly date ranges for the Header
$datesHeader = [[$startLastHeader, $endLastHeader], [$startHeader, $endHeader]];
$monthStartHeader = (new DateTime("first day of last month midnight"))->format($iso);
$monthEndHeader = (new DateTime("last day of last month midnight"))->format($iso);
$previousMonthStartHeader = (new DateTime("first day of -2 month midnight"))->format($iso);
$previousMonthEndHeader = (new DateTime("last day of -2 month midnight"))->format($iso);
// Monthly date ranges for the Header
$datesHeaderMonth = [[$previousMonthStartHeader, $previousMonthEndHeader], [$monthStartHeader, $monthEndHeader]];
// echo "<pre>";
// print_r($datesHeaderMonth);
// echo "</pre>";
//
// echo "<pre>";
// print_r($datesHeaderMonth);
// echo "</pre>";
// }
?>
<!-- Dropdown - date range -->
<div class="row mb-4 mt-1">
<div class="dropdown">
<button type="button" class="btn bg-white border border-1 dropdown-toggle" id="range-button" data-bs-toggle="dropdown" aria-expanded="false"><span class="material-icons align-top">calendar_today</span> <span data-i18n="dr-lastweek">Last week</span></button>
<span class="text-secondary ps-3 text-nowrap dates-header-week"><strong><?=$datesHeader[1][0] ?> - <?=$datesHeader[1][1] ?></strong></span>
<span class="text-secondary ps-1 text-nowrap dates-header-week" data-i18n="compared_to">compared to</span>
<span class="text-secondary ps-1 text-nowrap dates-header-week"><strong><?=$datesHeader[0][0] ?> - <?=$datesHeader[0][1] ?></strong></span>
<?php /*<span class="text-secondary ps-2 text-nowrap dates-header-month d-none"><?=$datesHeaderMonth[1][0] ?> to <?=$datesHeaderMonth[1][1] ?> compared to <?=$datesHeaderMonth[0][0] ?> to <?=$datesHeaderMonth[0][1] ?></span>*/?>
<ul class="dropdown-menu" aria-labelledby="range-button" style="">
<li id="dr_week"><a class="dropdown-item active" aria-current="true" href="#" data-i18n="dr-lastweek">Last week</a></li>
<li id="dr_month"><a class="dropdown-item" href="#" data-i18n="dr-lastmonth">Last month</a></li>
</ul>
</div>
</div>
<script>
// Update Date range dropdown button with selected value
$(".dropdown-menu li a").click(function(){
$(".btn").text($(this).text());
$(".btn").val($(this).text());
//prepend the calendar icon
$(".btn").prepend( "<span class='material-icons align-top' data-i18n='icon-calendar'>calendar_today</span> ");
$(".dropdown-menu li a").removeClass("active").removeAttr("aria-current");
$(this).addClass("active").attr("aria-current","true");
//$(".dates-header-month, .dates-header-week").toggleClass("d-none");
//add proper translation data-attribute for selected value
if ($(".btn").text() == "Last week") {
$(".btn").attr("data-i18n", "dr-lastweek");
//$(".dates-header-week").removeClass("d-none");
//$("#dr_week a.dropdown-item").addClass("active").attr("aria-current","true");
//$("#dr_month a.dropdown-item").removeClass("active").removeAttr("aria-current");
}
else {
$(".btn").attr("data-i18n", "dr-lastmonth");
//$(".dates-header-month").removeClass("d-none");
//$(".dates-header-week").addClass("d-none");
//$("#dr_month a.dropdown-item").addClass("active").attr("aria-current","true");;
//$("#dr_week a.dropdown-item").removeClass("active").removeAttr("aria-current");
}
});
</script>
<?php
function differ($old, $new)
{
if ($old == 0) {
return 0;
}
else {
return (($new - $old) / $old);
}
}
function numDiffer($old, $new)
{
return ($new - $old);
}
function posOrNeg($num)
{
if ($num > 0) return 'text-success:arrow_upward';
else if ($num == 0) return 'text-warning:';
else return 'text-danger:arrow_downward';
}
function posOrNeg2($num)
{
if ($num > 0) return 'text-success:+';
else if ($num == 0) return 'text-warning:';
else return 'text-danger:-';
}
function percent($num)
{
return round($num * 100, 0) . '%';
}
?>
<?php
$lastMonthAndYear = date('F Y', strtotime($monthStartHeader));
$twoMonthsAgoAndYear = date('F Y', strtotime($previousMonthStartHeader));
// echo $currentMonthAndYear;
// echo "<br/>";
// echo $lastMonthAndYear;
// echo "<br/>";
// echo $twoMonthsAgoAndYear;
// $s = '27-06-2021';
// $e = '03-07-2021';
// $s1 = '04-07-2021';
// $e1 = '10-07-2021';
// $s = '29-08-2021';
// $e = '04-09-2021';
// $s1 = '05-09-2021';
// $e1 = '11-09-2021';
//$dates = [[$startLastGSC, $endLastGSC], [$startGSC, $endGSC]];
$s = $startLastGSC;
$e = $endLastGSC;
$s1 = $startGSC;
$e1 = $endGSC;
//$result1 = getMonthRanges('29-05-2021', '16-08-2021');
//$weeklyMonthRanges = getMonthRanges('22-08-2021', '04-09-2021');
// NOTE: you can use any kind of date format in the function
// NOTE: but the output date format of the function is always "2021-06-30"
//$weeklyMonthRanges = getMonthRanges('22-08-2021', '04-09-2021');
//$weeklyMonthRanges = getMonthRanges('2021-08-16', '2021-09-14');
$weeklyMonthRanges = getMonthRanges($s, $e1);
// //we use GSC - '2 weeks ago' start date and 'last week' end date for this range
// //$weeklyMonthRanges = getMonthRanges($startLastGSC, $endGSC);
// echo "<br><br><pre>";
// print_r($weeklyMonthRanges); //Prev WEEK
// echo "</pre><br></br>";
//echo count($result1);
/* **************************************************************************************************** */
// Set up config file and credentials for the Airtable API
/* **************************************************************************************************** */
//$config = include ('./php/config-at_cd.php');
$config = include ('./php/config-at.php');
//time the page load
$start2 = microtime(true);
if (count($weeklyMonthRanges) > 1) {
//echo "data ranges spread in two months";
$curMonth1 = date('F Y', strtotime($weeklyMonthRanges[0]['start']));
$curMonth2 = date('F Y', strtotime($weeklyMonthRanges[1]['start']));
//echo $curMonth1;
//echo $curMonth2;
$curQuarter1 = ceil(date("n", strtotime($weeklyMonthRanges[0]['start'])) / 3);
$curQuarter2 = ceil(date("n", strtotime($weeklyMonthRanges[1]['start'])) / 3);
//echo "<br>";
//echo $curQuarter1;
//echo $curQuarter2;
$curYear1 = date('Y', strtotime($weeklyMonthRanges[0]['start']));
$curYear2 = date('Y', strtotime($weeklyMonthRanges[1]['start']));
//echo "<br>";
//echo $curYear1;
//echo $curYear2;
$base1 = "DCD-".$curYear1."-Q".$curQuarter1;
$base2 = "DCD-".$curYear2."-Q".$curQuarter2;
//$airtable = new Airtable($config);
$airtable1 = new Airtable(array(
'api_key' => $config['call_data']['api_key'],
'base' => $config['call_data']['base'][$base1],
));
$airtable2 = new Airtable(array(
'api_key' => $config['call_data']['api_key'],
'base' => $config['call_data']['base'][$base2],
));
// $currentMonthAndYear = date('F Y');
// //BASE - current quarter
// $month = date("n", );
//$currentQuarter =
//get first month range ($result[0])
//get second month range ($result[1])
//get the current month for ech array
// echo $weeklyMonthRanges[0]['start']; echo $weeklyMonthRanges[0]['end'];
// echo "<br/>";
// echo $weeklyMonthRanges[1]['start']; echo $weeklyMonthRanges[1]['end'];
// echo "<br/>";
// echo gettype($weeklyMonthRanges[0]['start']);
$wMrS1 = $weeklyMonthRanges[0]['start'];
$wMrE1 = $weeklyMonthRanges[0]['end'];
$wMrS2 = $weeklyMonthRanges[1]['start'];
$wMrE2 = $weeklyMonthRanges[1]['end'];
//echo $wMrS1;
//echo $wMrE1;
//echo $wMrS2;
//echo $wMrE2;
// **************************************************************************************************************************
// I M P O R T A N T
// IS_AFTER() and IS_BEFORE() functions don't count the border dates when filtering.
// that's why we do DATEADD (one day) for is_BEFORE() ...
// for IS_AFTER() we don't substract a day for $params1, cause that start day is always Saturday and on Sundays there's no call centre data.
// As a correct coding practice, we need to subtact a day from $params1 (TO BE DONE)
// for $params2, instead of subtract a day, we use the $params1 end date (that is a one day less the the $params2 start date).
// **************************************************************************************************************************
$params1 = array("filterByFormula" => "AND(IS_AFTER({CALL_DATE}, '$wMrS1'), IS_BEFORE({CALL_DATE}, DATEADD('$wMrE1',1,'days')))"); // array( "filterByFormula" => 'SEARCH(Task, "'.implode($taskArray, ',').'") != ""');
$params2 = array("filterByFormula" => "AND(IS_AFTER({CALL_DATE}, '$wMrE1'), IS_BEFORE({CALL_DATE}, DATEADD('$wMrE2',1,'days')))"); // array( "filterByFormula" => 'SEARCH(Task, "'.implode($taskArray, ',').'") != ""');
$table1 = $curMonth1;
$table2 = $curMonth2;
//API REQUST 1
$fullArray1 = [];
$request1 = $airtable1->getContent($table1, $params1);
do
{
$response1 = $request1->getResponse();
$fullArray1 = array_merge($fullArray1, ($response1->records));
}
while ($request1 = $response1->next());
$weeklyRe1 = ( json_decode(json_encode($fullArray1), true));//['records'];
// if there's data (record exist)
if ( count( $weeklyRe1 ) > 0 ) {
// do things here
// echo "first monthly range array <br>";
// echo count($weeklyRe1);
// echo "<br>";
}
// ***************** //
//API REQUST 2
$fullArray2 = [];
$request2 = $airtable2->getContent($table2, $params2);
do
{
$response2 = $request2->getResponse();
$fullArray2 = array_merge($fullArray2, ($response2->records));
}
while ($request2 = $response2->next());
$weeklyRe2 = ( json_decode(json_encode($fullArray2), true));//['records'];
// if there's data (record exist)
if ( count( $weeklyRe2 ) > 0 ) {
// do things here
// echo "second monthly range array <br>";
// echo count($weeklyRe2);
// echo "<br>";
}
// WE NEED TO MERGE $weeklyRe1 and $weeklyRe2
$fullArray = array_merge($fullArray1, $fullArray2);
// echo "full_array_merged<br>";
// echo count($fullArray);
// echo "<br>";
}
if (count($weeklyMonthRanges) == 1) {
//echo "data ranges in one month";
//$month = date("n", );
//$currentQuarter = ceil($month / 3);
// $curMonth = date('F Y', strtotime($endGSC));
// $curQuarter = ceil(date("n", strtotime($endGSC)) / 3);
// $curYear = date('Y', strtotime($endGSC));
$curMonth = date('F Y', strtotime($e1));
$curQuarter = ceil(date("n", strtotime($e1)) / 3);
$curYear = date('Y', strtotime($e1));
//echo $curMonth;
//echo $curQuarter;
//echo $curYear;
//echo "<br>";
$base = "DCD-".$curYear."-Q".$curQuarter;
//echo "base: ". $base;
$airtable = new Airtable(array(
'api_key' => $config['call_data']['api_key'],
'base' => $config['call_data']['base'][$base],
));
// echo $curMonth;
// echo "<br/>";
// echo $startLastGSC;
// echo "<br/>";
// echo $endGSC;
// echo "<br/>";
// echo gettype($startLastGSC); //returns string
// $test_date1 = '2021-07-04';
// $test_date2 = '2021-07-10';
//NEED to get the BEFORE day for + 1 (it doesnt take the recoreds for july 10, only to the day before) - use DATEADD("07/10/19", 10, "days")
//$iso = 'Y-m-d';
$s = date("Y-m-d", strtotime($s));
$e1 = date("Y-m-d", strtotime($e1));
// echo $s;
// echo "<br/>";
// echo "$e1";
// echo "<br/>";
// $e1 = date("Y-m-d", strtotime("2020-06-01"));
//$s = (new DateTime($previousWeekStart))->format($iso);
$params = array("filterByFormula" => "AND(IS_AFTER({CALL_DATE}, '$s'), IS_BEFORE({CALL_DATE}, DATEADD('$e1',1,'days')))");
//$params = array("filterByFormula" => "AND(IS_AFTER({CALL_DATE}, '$startLastGSC'), IS_BEFORE({CALL_DATE}, DATEADD('$endGSC',1,'days')))"); // array( "filterByFormula" => 'SEARCH(Task, "'.implode($taskArray, ',').'") != ""');
// echo $s;
// echo "<br/>";
// echo "$e1";
// echo "<br/>";
//parameters are empty when getting the whole table (one month)
//$params_monthly = array();
//print_r($params);
$table = $curMonth;
$fullArray = [];
$request = $airtable->getContent($table, $params);
do
{
$response = $request->getResponse();
$fullArray = array_merge($fullArray, ($response->records));
}
while ($request = $response->next());
$weeklyRe = ( json_decode(json_encode($fullArray), true));//['records'];
// if there's data (record exist)
if ( count( $weeklyRe ) > 0 ) {
//do things here
//echo "we got data from the table";
}
//we can use the $dates array with GSC date ranges for '2 weeks ago' and 'last week'.
//get the current month
//get data with API
$fullArray = $weeklyRe;
}
//in a loop
//get data for the date range in the first month range ($result[0])
//get data for the date range in the second month range ($result[1])
//merge them in one array (total for weekly data we need)
//get the last month
//get data for this month
//get the 2 month ago month
////get data for this month
//we'll end up having 3 or 4 array (depends if count($result1) > 1) with data for the weekly and monthly date ranges we need.
//monthly data will be arranged in separate arrays for each month
//weekly data will be spread into one or two arrays -
//if one array, we know that is for '2 weeks ago' and for 'last week' together (we'll have to filer by date to get each week)
//alternatively, we can create separate arrays for each week
//if two arrays (i.e 3 days from last month, 11 days from this month), we'll have to merge these arrays and than use it as mentioned in the line above
//we can use these arrays to display the data on the page and calculate the changes
/* **************************************************************************************************** */
// Set up config file and credentials for the Airtable API
/* **************************************************************************************************** */
// //$config = include ('./php/config-at_cd.php');
// $config = include ('./php/config-at-new.php');
//
//
// //time the page load
// $start2 = microtime(true);
//
// //$airtable = new Airtable($config);
// $airtable = new Airtable(array(
// 'api_key' => $config['api_key'],
// 'base' => $config['base']['DCD-2021-Q3'],
// ));
//var_dump($taskArray);
// Tasks in AirTable
// $params = array(
//
// //print_r($params);
// $table = 'User testing';
// $request = getContentRecursive($airtable, $table, $params);
// $lo = ['fields', ['Task', 'Tasks']];
//
// $con = parseJSON2($request, $lo);
//echo "<br /><br /> Connection Main: ";
//var_dump ( $con );
// Enquiry Lines in AirTable
//echo date('F Y');
/* **************************************************************************************************** */
// Set up Parameters and Table for the Data we want to get with the Airtable API
/* **************************************************************************************************** */
// $test_date1 = '2021-07-04';
// $test_date2 = '2021-07-10';
// //NEED to get the BEFORE day for + 1 (it doesnt take the recoreds for july 10, only to the day before) - use DATEADD("07/10/19", 10, "days")
// $params = array("filterByFormula" => "AND(IS_AFTER({CALL_DATE}, '2021-07-04'), IS_BEFORE({CALL_DATE}, DATEADD('2021-07-10',1,'days')))"); // array( "filterByFormula" => 'SEARCH(Task, "'.implode($taskArray, ',').'") != ""');
//
// //parameters are empty when getting the whole table (one month)
// $params_monthly = array();
// //print_r($params);
// $table = 'July 2021';
//
// $fullArray = [];
// $request = $airtable->getContent($table, $params);
// $response = $request->getResponse();
// //$re = json_decode(json_encode($response), true);
// $re = ( json_decode( $response, true ) )['records'];
// //['records'];
// echo count($re);
// echo "<br><br><pre>";
// print_r($re); //Prev WEEK
// echo "</pre><br></br>";
// $request = $airtable->getContent($table, $params);
// do
// {
// $response = $request->getResponse();
// $fullArray = array_merge($fullArray, ($response->records));
// }
// while ($request = $response->next());
$re = ( json_decode(json_encode($fullArray), true));//['records'];
// echo "<br><br><pre>";
// print_r($re); //Prev WEEK
// echo "</pre><br></br>";
// $s = '06-06-2021';
// $e = '12-06-2021';
// $s1 = '13-06-2021';
// $e1 = '19-06-2021';
//weekly data
$rangeStartW = strtotime($s1);
$rangeEndW = strtotime($e1);
//previous week
$rangeStartPW = strtotime($s);
$rangeEndPW = strtotime($e);
//filter array by date ranges
$WeeklyData = array_filter( $re, function($var) use ($rangeStartW, $rangeEndW) {
$utime = strtotime($var['fields']['CALL_DATE']);
return $utime <= $rangeEndW && $utime >= $rangeStartW;
});
$PWeeklyData = array_filter( $re, function($var) use ($rangeStartPW, $rangeEndPW) {
$utime = strtotime($var['fields']['CALL_DATE']);
return $utime <= $rangeEndPW && $utime >= $rangeStartPW;
});
//echo count($WeeklyData);
//echo "<br>";
//echo count($PWeeklyData);
// $re = array_filter( $re, function($var) use ($rangeStartW, $rangeEndW) {
// $utime = strtotime($var['fields']['CALL_DATE']);
// return $utime <= $rangeEndW && $utime >= $rangeStartW;
// });
//echo count($re);
//echo gettype($re[0]['fields']["CALL_DATE"]);
// echo "<br><br><pre>";
// print_r($re); //Prev WEEK
// echo "</pre><br></br>";
// if there's data (record exist)
//if ( count( $re ) > 0 ) {
//if ( count( $re ) > 0 ) {
if (( count( $WeeklyData ) > 0 ) && ( count( $PWeeklyData ) > 0 )) {
//var_dump($re);
// Get just the ['fields'] array of each record - as a separate array - $all_fields
$all_fields = array_column_recursive($WeeklyData, 'fields');
$all_fieldsPW = array_column_recursive($PWeeklyData, 'fields');
// echo "<br><br><pre>";
// print_r($all_fieldsPW); //Prev WEEK
// echo "</pre><br></br>";
//Sort all_fields array by Call_Date key in descending order
// if we need an ascernding order, swap the $a and $b variable as function arguments
usort($all_fields, function($a, $b) {
return new DateTime($a['CALL_DATE']) <=> new DateTime($b['CALL_DATE']);
});
usort($all_fieldsPW, function($a, $b) {
return new DateTime($a['CALL_DATE']) <=> new DateTime($b['CALL_DATE']);
});
$fieldsByGroup = group_by('Topic', $all_fields);
$fieldsByGroupPW = group_by('Topic', $all_fieldsPW);
//
// echo count($fieldsByGroup);
// echo "<br><br><pre>";
// print_r($fieldsByGroup); //Prev WEEK
// echo "</pre><br></br>";
foreach ( $fieldsByGroupPW as &$item ) {
$item["Total topic calls"] = array_sum(array_column_recursive($item, "Calls"));
}
//
$i=1;
foreach ( $fieldsByGroup as &$item1 ) {
// Add Total Topic Calls and Change (in teh number of calls from previous week) keys
$item1["Total topic calls"] = array_sum(array_column_recursive($item1, "Calls"));
//echo "--------------------------------------<br><br><pre>";
//if $item[0]['Topic']
//Prev WEEK
//echo "</pre><br></br>";
//echo array_key_exists($item[0]['Topic'], $fieldsByGroupPW);
//if (array_key_exists($item[0]['Topic'], $fieldsByGroupPW)){
if (array_key_exists("Topic", $item1[0])) {
if (array_key_exists($item1[0]['Topic'], $fieldsByGroupPW)){
$item1["Change"] = differ( $fieldsByGroupPW[$item1[0]['Topic']]['Total topic calls'], $item1['Total topic calls'] );
}
else {
$item1["Change"] = 0;
}
}
else {
$item1["Change"] = 0;
}
}
// echo count($fieldsByGroupPW);
// echo "--------------------------------------<br><br><pre>";
// print_r($fieldsByGroup); //Prev WEEK
// echo "</pre><br></br>";
//uasort -keeps the key associations
uasort($fieldsByGroup, function($b, $a) {
if ($a["Total topic calls"] == $b["Total topic calls"]) {
return 0;
}
return ($a["Total topic calls"] < $b["Total topic calls"]) ? -1 : 1;
});
$top5Topics = array_slice($fieldsByGroup, 0, 5);
//usort -does not keep the key associations - it becomes an array (no keys)
// usort($fieldsByGroup, function($b, $a) {
// if ($a == $b) {
// return 0;
// }
// return ($a < $b) ? -1 : 1;
// });
// usort($fieldsByGroup, function($a, $b) {
// return new DateTime($a['Total topic calls']) <=> new DateTime($b['Total topic calls']);
// });
// echo "***************************************************************************";
// echo "<pre>";
// print_r( $fieldsByGroup );
// echo "</pre>";
} //if ( count( $re ) > 0 )
?>
<!-- D3 - TOTAL CALLS BY INQUIRY LINE -->
<div class="row mb-4">
<div class="col-lg-12 col-md-12">
<div class="card">
<div class="card-body pt-2">
<h3 class="card-title"><span class="card-tooltip h6" data-bs-toggle="popover" data-bs-trigger="hover focus" data-bs-placement="right" data-bs-content="Total number of calls per enquiry line: ITE (Individual Tax Enquiries), e-services, Child and Family Benefits, Buiness Enquiries, etc." data-bs-original-title="" title="" data-i18n="d3-tcbil">Total calls by inqury line</span></h3>
<div class="card-body pt-2" id="d3_tcbil"></div>
<div id="d3_www_legend"></div>
<!-- Total calls by Enquiry_line D3 bar chart -->
<?php
$fieldsByGroupEL = group_by('Enquiry_line', $all_fields);
$fieldsByGroupELPW = group_by('Enquiry_line', $all_fieldsPW);
foreach ( $fieldsByGroupEL as &$item ) {
$item["Total EL calls"] = array_sum(array_column_recursive($item, "Calls"));
}
foreach ( $fieldsByGroupELPW as &$item ) {
$item["Total EL calls"] = array_sum(array_column_recursive($item, "Calls"));
}
// echo "--------------------------------------<br><br><pre>";
// print_r($fieldsByGroupELPW); //Prev WEEK
// echo "</pre><br></br>";
// echo "--------------------------------------<br><br><pre>";
// print_r($el); //Prev WEEK
// echo "</pre><br></br>";
//USE THIS - THESE ARE WELL DEFINED DATE RANGES
//-------------------------------------------------------
//$d3DateRanges = array($datesHeaderMonth[0][0].'-'.$datesHeaderMonth[0][1],$datesHeaderMonth[1][0].'-'.$datesHeaderMonth[1][1],$datesHeader[0][0].'-'.$datesHeader[0][1],$datesHeader[1][0].'-'.$datesHeader[1][1]); // previous $a1
//$groups = json_encode(array($d3DateRanges[2],$d3DateRanges[3]));
//----------------------------------------------------
//$d3DateRanges = array($s.'-'.$e,$s1.'-'.$e1); // previous $a1
//$d3DateRanges = array("June 06-12", "June 13-19");
// $s = $startLastGSC;
// $e = $endLastGSC;
// $s1 = $startGSC;
// $e1 = $endGSC;
$s = date("M d", strtotime($s));
$e = date("M d", strtotime($e));
$s1 = date("M d", strtotime($s1));
$e1 = date("M d", strtotime($e1));
$d3DateRanges = array($s.'-'.$e,$s1.'-'.$e1); // previous $a1
$groups = json_encode($d3DateRanges);
//echo count($d3DateRanges);
//echo count($groups[0]);
//$d3Subgroups = array("Yes","Yes","Yes","Yes","No","No","No","No"); // previous $b1
//$d3Data = array_slice($metrics, 0, 8); // previous $c1
// echo "--------------------------------------<br><br><pre>";
// print_r($groups); //Prev WEEK
// echo "</pre><br></br>";
$el = array_values(array_unique(array_column_recursive($fieldsByGroup, "Enquiry_line")));
$subgroups = json_encode($el);
// echo "--------------------------------------<br><br><pre>";
// print_r($el); //Prev WEEK
// echo count($el);
// echo "</pre><br></br>";
/// ---------------------
/// MAKE SURE WE ADD THE DATA IN THE RIGHT DATE RANGE - AND TRIPLE CHECK THE RESULTS WITH THE ACTUAL DATA IN THE WEKLY AND PWEEKLY VARIABLES
/// -----------------------
for ($i = 0; $i < 2; ++$i) {
$final_array["dateRange"] = $d3DateRanges[$i];
if ($i==0) {
for ($k = 0; $k < count($el); ++$k) {
$final_array[$el[$k]] = $fieldsByGroupELPW[$el[$k]]["Total EL calls"];
}
}
else {
for ($k = 0; $k < count($el); ++$k) {
$final_array[$el[$k]] = $fieldsByGroupEL[$el[$k]]["Total EL calls"];
}
}
// $final_array["No"] = $d3Data[$i+4];
$d3_data_w[]=$final_array;
}
//$mydata = json_encode($new_array);
//just present the Weekly date range data - index 2 and 3 from new_array
// echo "--------------------------------------<br><br><pre>";
// print_r($d3_data_w); //Prev WEEK
// echo "</pre><br></br>";
//$mydata = json_encode(array_slice($new_array, 2));
$mydata = json_encode($d3_data_w);
//$groups = json_encode(array_unique($d3Data_DYFWYWLF_DateRanges));
//just present the Weekly date ranges
?>
<script>
// set the dimensions and margins of the graph
width = parseInt(d3.select('#d3_tcbil').style('width'), 10)
height = width / 3;
//alert("hellp");
var margin = {top: 10, right: 30, bottom: 30, left: 100},
width = width - margin.left - margin.right,
height = height - margin.top - margin.bottom,
legendHeight = 0;
// append the svg object to the body of the page
var svg_new = d3.select("#d3_tcbil")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom + legendHeight)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Parse the Data
var data = <?=$mydata?>;
//console.log(data)
//console.log(typeof data)
// List of subgroups = header of the csv files = soil condition here
//var subgroups = data.columns.slice(1)
var subgroups = <?=$subgroups?>;
//console.log(subgroups)
//console.log(typeof subgroups)
// List of groups = species here = value of the first column called group -> I show them on the X axis
//var groups = d3.map(data, function(d){return(d.group)}).keys()
var groups = <?=$groups?>;
//console.log(groups)
//console.log(typeof groups)
// Add X axis
var x = d3.scaleBand()
.domain(groups)
.range([0, width])
.padding([0.3]);
svg_new.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).tickSizeOuter(0));
// get the max value from the data json object for the y axis domain
var max = d3.max(data, function(d){ return d3.max(d3.values(d).filter(function(d1){ return !isNaN(d1)}))});
console.log(max);
var num_digits = Math.floor(Math.log10(max)) + 1;
console.log(num_digits);
console.log(Math.ceil(max/Math.pow(10,num_digits-1))*Math.pow(10,num_digits-1));
// Add Y axis
var y = d3.scaleLinear()
.domain([0, Math.ceil(max/Math.pow(10,num_digits-1))*Math.pow(10,num_digits-1)])
.range([ height, 0 ]);
// grid lines on Y axis
var yGrid = d3.axisLeft(y).tickSize(-width).tickFormat('').ticks(5);
// Another scale for subgroup position?
var xSubgroup = d3.scaleBand()
.domain(subgroups)
.range([0, x.bandwidth()])
.padding([0.1]);
//create yGrid
svg_new.append('g')
.attr('class', 'axis-grid')
.call(yGrid);
//create Y axis
svg_new.append("g")
.call(d3.axisLeft(y).ticks(5));
// color palette = one color per subgroup
var color = d3.scaleOrdinal()
.domain(subgroups)
.range(['#345EA5','#6CB5F3','#36A69A','#F8C040','#3EE9B7','#F17F2B']);
// Show the bars
svg_new.append("g")
.selectAll("g")
// Enter in data = loop group per group
.data(data)
.enter()
.append("g")
.attr("transform", function(d) { return "translate(" + x(d.dateRange) + ",0)"; })
.selectAll("rect")
.data(function(d) { return subgroups.map(function(key) { return {key: key, value: d[key]}; }); })
.enter().append("rect")
.attr("x", function(d) { return xSubgroup(d.key); })
.attr("y", function(d) { return y(d.value); })
.attr("width", xSubgroup.bandwidth())
.attr("height", function(d) { return height - y(d.value); })
.attr("fill", function(d) { return color(d.key); });
svg_new.selectAll(".tick text")
.style("font-size","14px")
.style("fill","#666");
// D3 legend
//color.domain(d3.keys(data[0]).filter(function(key) { return key !== "dateRange"; }));
// svg_new.append("g")
// .attr("class", "legendOrdinal")
// .attr("transform", "translate(0,"+(height+45)+")");
//
// var legendOrdinal = d3.legendColor()
// .shape("rect")
// .shapePadding(150)
// .orient('horizontal')
// .labelAlign("start")
// .scale(color);
//
// svg_new.select(".legendOrdinal")
// .call(legendOrdinal);
var legend = d3.select('#d3_www_legend').selectAll("legend")
.data(subgroups);
var legend_cells = legend.enter().append("div")
.attr("class","legend");