-
Notifications
You must be signed in to change notification settings - Fork 0
/
training-report.html
1287 lines (1179 loc) · 38.9 KB
/
training-report.html
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
<!-- Check out the documentation at https://github.com/KaiVandivier/ascend-mda-report -->
<!-- Bootstrap stylesheet and scripts -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"
></script>
<!-- Font awesome icons -->
<script
src="https://kit.fontawesome.com/8483276227.js"
crossorigin="anonymous"
></script>
<style type="text/css" media="screen">
/* Put your CSS styling here */
/* Vars */
:root {
--colShade: rgba(0, 0, 0, 0.02);
--pink: hsl(348, 100%, 97.5%);
--yellow: hsl(60, 100%, 97.5%);
--green: hsl(132, 100%, 97.5%);
--blue: hsl(204, 100%, 97.5%);
--lilac: hsl(276, 100%, 97.5%);
}
/* Button styles */
.btn.disabled,
.btn:disabled {
pointer-events: none;
}
/* Table styles */
table {
border-collapse: separate;
border-spacing: 0;
}
/* Constrain column size */
thead th:first-child {
width: 60%;
}
/* Table header color & stripe */
thead th {
background: white;
}
thead th:nth-child(even) {
background: #f7f7f7;
}
/* Table header styles */
#header-row > th {
position: sticky;
top: 0;
}
th.container {
width: auto;
}
.bottom-row {
font-weight: normal;
font-size: 0.9rem;
height: calc(0.9rem * 1.5);
}
/**
* Table body color & stripe:
* THIS IS HARD-CODED AND NEEDS CHANGING IF COLUMNS CHANGE
*/
tbody tr *:nth-child(even) {
background-color: var(--colShade);
}
/* Row headers that are not category labels: normal font-weight */
th[scope="row"]:not([colspan]) {
font-weight: normal;
}
/* Colors (used for rows) */
.pink {
background: var(--pink);
}
.yellow {
background: var(--yellow);
}
.green {
background: var(--green);
}
.blue {
background: var(--blue);
}
.lilac {
background: var(--lilac);
}
</style>
<script type="text/javascript">
// Put your javascript functions here
// Enums for table
const colSubcats = Object.freeze({
ROUND_1: { name: "Round 1", shortName: "R1" },
ROUND_2: { name: "Round 2", shortName: "R2" },
TOTAL: { name: "Total", shortName: "Tot." },
});
const rowTypes = Object.freeze({
CATEGORY: "category",
DATA: "data",
});
const rowColors = Object.freeze({
ENDEMICITY: "yellow",
TARGETS: "blue",
COVERAGE: "pink",
COVERAGE_EVALUATION: "green",
LNOB: "lilac",
});
const tooltipTypes = Object.freeze({
INFO: { name: "info", icon: "fa-info-circle", color: "text-secondary" },
ERROR: {
name: "error",
icon: "fa-exclamation-circle",
color: "text-danger",
},
WARNING: {
name: "warning",
icon: "fa-exclamation-triangle",
color: "text-warning",
},
});
/**
* Row and column definitions: Edit these to define the table.
* See the documentation at https://github.com/KaiVandivier/ascend-mda-report
* for a guide.
*/
const columns = [
{
name: "Female",
shortName: "Female",
subcategories: null,
},
{
name: "Male",
shortName: "Male",
subcategories: null,
},
{
name: "Total",
shortName: "Total",
subcategories: null,
},
];
const rows = [
{
name: "People trained to support morbidity mapping for LF",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - People trained to support morbidity mapping for LF_Female",
},
{
dn:
"Training - People trained to support morbidity mapping for LF_Male",
},
{
dn:
"Training - People trained to support morbidity mapping for LF_Total",
},
],
},
{
name: "People trained to support morbidity mapping for Trachoma",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - People trained to support morbidity mapping for Trachoma_Female",
},
{
dn:
"Training - People trained to support morbidity mapping for Trachoma_Male",
},
{
dn:
"Training - People trained to support morbidity mapping for Trachoma_Total",
},
],
},
{
name: "Staff trained on transmission assessment and data collection",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - Staff trained on transmission assessment and data collection_Female",
},
{
dn:
"Training - Staff trained on transmission assessment and data collection_Male",
},
{
dn:
"Training - Staff trained on transmission assessment and data collection_Total",
},
],
},
{
name: "People trained in budgeting",
type: rowTypes.DATA,
cells: [
{ dn: "Training - People trained in budgeting_Female" },
{ dn: "Training - People trained in budgeting_Male" },
{ dn: "Training - People trained in budgeting_Total" },
],
},
{
name: "Total people trained (disaggregated to roles and geographic area)",
type: rowTypes.DATA,
cells: [null, null, null],
},
{
name:
"Health care providers providing morbidity management who received raining on morbidity management (LF: Lymphoedema, Hydrocele; Trachoma: Trichiasis)",
type: rowTypes.DATA,
cells: [null, null, null],
},
{
name: "People trained on data management systems",
type: rowTypes.DATA,
cells: [
{ dn: "Training - People trained on data management systems_Female" },
{ dn: "Training - People trained on data management systems_Male" },
{ dn: "Training - People trained on data management systems_Total" },
],
},
{
name: "Surveillance trainings conducted",
type: rowTypes.DATA,
cells: [
null,
null,
{ dn: "Training - Surveillance trainings conducted" },
],
},
{
name: "People trained on supply chain management systems",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - People trained on supply chain management systems_Female",
},
{
dn:
"Training - People trained on supply chain management systems_Male",
},
{
dn:
"Training - People trained on supply chain management systems_Total",
},
],
},
{
name: "NTD trainings including IEC/BCC components",
type: rowTypes.DATA,
cells: [
null,
null,
{ dn: "Training - NTD trainings including IEC/BCC components_Total" },
],
},
{
name:
"Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: CDDs",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: CDDs_Female",
},
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: CDDs_Male",
},
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: CDDs_Total",
},
],
},
{
name:
"Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: FLHW",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: FLHW_Female",
},
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: FLHW_Male",
},
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: FLHW_Total",
},
],
},
{
name:
"Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: Supervisor/Trainers",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: Supervisor/Trainers_Female",
},
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: Supervisor/Trainers_Male",
},
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: Supervisor/Trainers_Total",
},
],
},
{
name:
"Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: Teachers",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: Teachers_Female",
},
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: Teachers_Male",
},
{
dn:
"Training - Health care providers and community drug distributors trained and working on MDA planning, social mobilization, implementation and monitoring: Teachers_Total",
},
],
},
{
name:
"VL treatment facilities which are functional with adequate trained human resources, diagnostic equipment and supplies and medicines",
type: rowTypes.DATA,
cells: [null, null, null],
},
{
name: "VL treatment facilities receiving training",
type: rowTypes.DATA,
cells: [
null,
null,
{ dn: "Training - VL treatment facilities receiving training" },
],
},
{
name: "People trained in mmdp care: Lymphoedema management",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - People trained in mmdp care: Lymphoedema management_Female",
},
{
dn:
"Training - People trained in mmdp care: Lymphoedema management_Male",
},
{
dn:
"Training - People trained in mmdp care: Lymphoedema management_Total",
},
],
},
{
name: "People trained in mmdp care: Hydrocelectomy",
type: rowTypes.DATA,
cells: [
{ dn: "Training - People trained in mmdp care: Hydrocelectomy_Female" },
{ dn: "Training - People trained in mmdp care: Hydrocelectomy_Male" },
{ dn: "Training - People trained in mmdp care: Hydrocelectomy_Total" },
],
},
{
name: "People trained in mmdp care: TT surgery",
type: rowTypes.DATA,
cells: [
{ dn: "Training - People trained in mmdp care: TT surgery_Female" },
{ dn: "Training - People trained in mmdp care: TT surgery_Male" },
{ dn: "Training - People trained in mmdp care: TT surgery_Total" },
],
},
{
name: "People trained in mmdp care: VL treatment",
type: rowTypes.DATA,
cells: [
{ dn: "Training - People trained in mmdp care: VL treatment_Female" },
{ dn: "Training - People trained in mmdp care: VL treatment_Male" },
{ dn: "Training - People trained in mmdp care: VL treatment_Total" },
],
},
{
name: "People trained in active case finding for VL",
type: rowTypes.DATA,
cells: [
{
dn: "Training - People trained in active case finding for VL_Female",
},
{ dn: "Training - People trained in active case finding for VL_Male" },
{ dn: "Training - People trained in active case finding for VL_Total" },
],
},
{
name: "People trained in active case finding for trachoma",
type: rowTypes.DATA,
cells: [
{
dn:
"Training - People trained in active case finding for trachoma_Female",
},
{
dn:
"Training - People trained in active case finding for trachoma_Male",
},
{
dn:
"Training - People trained in active case finding for trachoma_Total",
},
],
},
{
name: "People trained in active case finding for LF",
type: rowTypes.DATA,
cells: [
{
dn: "Training - People trained in active case finding for LF_Female",
},
{ dn: "Training - People trained in active case finding for LF_Male" },
{ dn: "Training - People trained in active case finding for LF_Total" },
],
},
{
name: "Total people trained: all training types",
type: rowTypes.DATA,
cells: [
{ dn: "Training - People trained: all training types_Female" },
{ dn: "Training - People trained: all training types_Male" },
{ dn: "Training - People trained: all training types_Total" },
],
},
{
name: "Total people trained: by training type",
type: rowTypes.DATA,
cells: [null, { value: "todo" }, null],
},
];
// End row & cell definitions
/**
*
* App state
*
*/
// (Ideally, initial values would be set by the reports app parameters)
// Initial period should get overwritten by `setUpPeriodSelect()`;
const currentYear = new Date().getFullYear();
const initialPeriod = currentYear;
const initialOrgUnit = Object.keys(dhis2.report.organisationUnit).length
? dhis2.report.organisationUnit.id
: "GdH306UQ8L8"; // This is the global org-unit
// Number format to be used in cells
const numberFormat = new Intl.NumberFormat(undefined, {
maximumFractionDigits: 2,
});
// Cell-width of table
const totalColumns =
1 +
columns.reduce(
(sum, column) => sum + (column.subcategories?.length || 1),
0
);
let state = {
currentYear: currentYear,
period: initialPeriod,
orgUnit: initialOrgUnit,
numberFormat,
totalColumns,
// Dim. IDs, found by dimension-name lookup:
dimensionsToQuery: [],
// Warnings and errors to be displayed in tooltips:
alerts: [],
};
/**
*
* Custom logic helper functions
*
*/
function greatestOf(...args) {
const nums = args.filter((n) => !isNaN(n));
if (!nums.length) return 0;
return Math.max(...nums);
}
function sumOf(...args) {
const nums = args.filter((n) => !isNaN(n));
if (!nums.length) return 0;
return nums.reduce((sum, n) => sum + Number(n), 0);
}
function uniqueRespondingIUs(cells) {
// This function counts all unique IUs with at least one value in this row
// 1. Build dimensions list for query url
const dimensions = cells
.filter((cell) => cell && cell.dxId)
.map((cell) => cell.dxId)
.join(";");
// 2. Query analytics:
return $.get("../api/34/analytics", {
// Second orgunit dimension is hardcoded to IU level
dimension: `dx:${dimensions},ou:${state.orgUnit};LEVEL-iGO9aN3ZSSi`,
filter: `pe:${state.period}`,
skipMeta: true,
})
.then((json) => {
// 3. Get unique org units (IUs) with response > 0
const uniqueOrgUnits = new Map();
json.rows.forEach(([dimensionId, orgUnitId, value]) => {
if (!value) return;
// If this org unit is a duplicate in the list, set value to be the greater
const existingValue = uniqueOrgUnits.get(orgUnitId);
if (existingValue) {
const greaterValue = greatestOf(value, existingValue);
uniqueOrgUnits.set(orgUnitId, greaterValue);
return;
}
// Otherwise, set value
uniqueOrgUnits.set(orgUnitId, value);
});
// Sum response values of unique IUs
let sumOfValues = 0;
uniqueOrgUnits.forEach((value) => {
if (isNaN(value)) return;
sumOfValues += Number(value);
});
const numUniqueIUs = uniqueOrgUnits.size;
return { numUniqueIUs, sumOfValues };
})
.catch((err) => {
// Format error for later handling
return Promise.reject({ ...err, message: "Unique IUs error" });
});
}
/**
*
* Table logic
*
*/
function getAllDimensions() {
// Gets a list of all indicators' and program indicators' names and IDs
const filter = "Training";
// TODO: Refactor for easier manipulation
return Promise.all([
$.get(
`../api/34/programIndicators.json?filter=displayName:like:${filter}&paging=false`
),
$.get(
`../api/34/indicators.json?filter=displayName:like:${filter}&paging=false`
),
]).then((values) => {
const [{ programIndicators }, { indicators }] = values;
const allDimensions = [...programIndicators, ...indicators];
const dimensionMap = new Map();
allDimensions.forEach((dimension) => {
// Check for duplicated dimensions
const dimensionWithSameName = dimensionMap.get(dimension.displayName);
if (dimensionWithSameName) {
const alert = {
identifier: "dimension-name",
identifierValue: dimension.displayName,
tooltipType: tooltipTypes.WARNING,
message: `Duplicate dimension name found: '${dimension.displayName}'. You may not get the data you're looking for if this cell is queried by name.`,
};
state.alerts.push(alert);
console.warn(
"Duplicate dimension name found: ",
dimension.displayName
);
}
// As of right now, overwrite to give last-queried group precedence (i.e., indicators)
dimensionMap.set(dimension.displayName, dimension.id);
});
return dimensionMap;
});
}
function populateCellDimensionIds(allDimensions) {
// Populates dimensionId (`dxId`) on cells based on dimensionName
// Also populates `state.dimensionsToQuery` for analytics query
const dimensionsToQuery = [];
// Look up dimension ids by name and add ids to cells
rows.forEach(({ cells }) => {
if (!cells) return;
cells.forEach((cell) => {
if (!cell) return;
if (cell.dxId) {
// cell already has `dimensionId`; skip ID lookup
dimensionsToQuery.push(cell.dxId);
return;
}
if (!cell.dn) return;
const { dn: dimensionName } = cell;
// Find dimension in map:
const dimensionId = allDimensions.get(dimensionName);
if (!dimensionId) {
if (!cell.tooltips) cell.tooltips = [];
cell.tooltips.push({
type: tooltipTypes.ERROR,
message: `Dimension not found: ${dimensionName}`,
});
return;
}
// Dimension found - add it to list to query and populate cell
dimensionsToQuery.push(dimensionId);
cell.dxId = dimensionId;
});
});
state = { ...state, dimensionsToQuery };
return dimensionsToQuery;
}
function getAnalyticsData() {
// Query analytics API for data (with one monolithic query)
const { dimensionsToQuery, period, orgUnit } = state;
return $.get("../api/34/analytics", {
dimension: `dx:${dimensionsToQuery.join(";")}`,
filter: `ou:${orgUnit},pe:${period}`,
skipMeta: true,
})
.then((json) => {
// convert to a map for easy lookup by ID:
const keyValuePairs = json.rows.map((row) => [row[0], row[1]]);
const resultsMap = new Map(keyValuePairs);
return resultsMap;
})
.catch((err) => {
// There was an error with the monolothic query. Fall back to individual queries
// Log error and notify user
console.warn(
"There was an error with the monolithic query. Falling back to individual queries.",
err
);
const errMsgExists = $("#errMsg").length;
if (!errMsgExists) {
$("#loading").prepend(`
<div id="errMsg">
<p>Oops! There was an error with the database query. This report will fall back to a less efficient method to identify the error, which will take a bit longer to load than usual.</p>
<p class="text-warning"><i class="fa fa-exclamation-triangle"></i> Warning: Please be aware that refreshing the table multiple times while the error exists can crash the server, due to a large volume of network requests.</p>
</div>
`);
}
// Query dimensions individually to sort out errors
return getAnalyticsDataIndividually();
});
}
function getAnalyticsDataIndividually() {
// Query each cell individually to sort out errors
// (This is much slower and should only be used if there is a db error in the monolothic query)
const { dimensionsToQuery, period, orgUnit } = state;
return Promise.all(
dimensionsToQuery.map((dimensionId) => {
// Query individual cell contents
return $.get("../api/34/analytics", {
dimension: `dx:${dimensionId},pe:${period}`,
filter: `ou:${orgUnit}`,
skipMeta: true,
}).then(
// If successful, return key-value pair of data
(json) => {
if (!json.rows.length) return;
return [dimensionId, json.rows[0][2]];
},
// If unsuccessful, log error and make key-value pair of id and error message
(err) => {
console.error(
`Analytics query error found for dimension ID ${dimensionId}: `,
err
);
const { status, statusText, responseJSON } = err;
const errorMessage = `Query error, status ${status}: ${
responseJSON ? responseJSON.message : statusText
}`;
state.alerts.push({
identifier: "dimension-id",
identifierValue: dimensionId,
tooltipType: tooltipTypes.ERROR,
message: errorMessage,
});
}
);
})
).then((kvPairs) => {
// Turn key-value pairs into a map for lookup during table population
const filteredPairs = kvPairs.filter((pair) => pair);
const resultsMap = new Map(filteredPairs);
return resultsMap;
});
}
function populateCellValues(analyticsResults) {
// Use `dimensionId` or `customLogic` to populate `value`
// Execute in parallel across rows
return Promise.all(
rows.map(async ({ cells }, rowIdx) => {
if (!cells) return; // Empty row; return
// Execute (possibly async) cell logic in _series_
return cells
.reduce((prevTask, cell, idx, arr) => {
return prevTask.then(async () => {
if (!cell) return;
const { dxId: dimensionId, customLogic } = cell;
// Handle cell defined by dimension ID
if (dimensionId) {
const data = analyticsResults.get(dimensionId);
cell.value = data ?? "-";
return;
}
// Handle cell defined by custom logic
if (customLogic) {
try {
cell.value = await customLogic(arr, idx);
} catch (err) {
// If error in custom logic, create alert
const message = `
${err.message || "Custom logic error"}:
${err.status || ""} ${err.statusText || ""}.
See console.
`;
state.alerts.push({
identifier: "custom-logic",
identifierValue: `row-${rowIdx}-idx-${idx}`,
tooltipType: tooltipTypes.ERROR,
message,
});
console.error(message, err);
}
return;
}
});
}, Promise.resolve())
.catch(console.error.bind(console, "Cell population error: "));
})
);
}
/**
*
* HTML Table building
*
*/
function populateHtmlTableHeader() {
// Empty cell over row names (Maybe "indicator?")
$("#header-row").append(`<th scope="col"></th>`);
columns.forEach((col) => {
const colspan = col.subcategories ? col.subcategories.length : 1;
const subheadings = col.subcategories
? col.subcategories.map((sc) => sc.shortName)
: null;
const newHeader = $(`
<th scope="col" class="container" colspan="${colspan}">
<div class="row mb-2">
<span class="col">${subheadings ? col.name : col.shortName}</span>
</div>
</th>
`);
$("#header-row").append(newHeader);
const bottomRow = $(`<div class="row no-gutters bottom-row"></div>`);
newHeader.append(bottomRow);
if (subheadings) {
subheadings.forEach((subheading) =>
bottomRow.append(`<span class="col">${subheading}</span>`)
);
return;
}
});
}
function populateHtmlTableBodyWithValues() {
// Clear tbody for fresh rows & remove "loading"
const tbody = $("#tbody").empty();
$("#loading").hide();
// Set up table body
rows.forEach((row, rowIdx) => {
// Make new row element
const newRow = $(
`<tr
data-name="${row.name}"
data-type="${row.type}"
class="${row.color || ""}"
></tr>`
);
// Add new row to DOM
tbody.append(newRow);
if (row.type === rowTypes.CATEGORY) {
// Row is just a category label (like "Coverage Evaluation"): make one wide cell and return
newRow.append(
`<th scope="row" colspan="${state.totalColumns}">${row.name}</th>`
);
return;
}
// Add row header with name
newRow.append(`<th scope="row">${row.name}</th>`);
addCellsToHtmlRow(newRow, row, rowIdx);
});
}
function addCellsToHtmlRow(htmlRow, row, rowIdx) {
const { cells } = row;
if (!cells || !cells.length) {
htmlRow.append(
`<td colspan="${state.totalColumns - 1}">No dimensions specified</td>`
);
return;
}
cells.forEach((cell, idx) => {
if (!cell) return htmlRow.append("<td></td>");
const { dn, dxId, customLogic, value } = cell;
const newCell = $(`
<td
${dn ? `data-dimension-name="${dn}"` : ""}
${dxId ? `data-dimension-id="${dxId}"` : ""}
${customLogic ? `data-custom-logic="row-${rowIdx}-idx-${idx}"` : ""}
></td>
`);
// Add value and format number
if (typeof value !== "undefined") {
const formattedValue = isNaN(value)
? value
: state.numberFormat.format(Number(value));
newCell.append(formattedValue);
}
// Add tooltips, if defined
if (cell.tooltips)
cell.tooltips.forEach((tooltip) => addTooltipToCell(newCell, tooltip));
htmlRow.append(newCell);
});
}
function addTooltipToCell(htmlCell, { type, message }) {
// Check if cell is valid:
if (!htmlCell.length)
return console.warn("Invalid html cell when adding tooltip");
const htmlTooltip = $(
`<i class="fa ${type.icon} ${type.color}" data-toggle="tooltip" data-title="${message}"></i>`
);
htmlCell.append(" ", htmlTooltip);
htmlTooltip.tooltip();
}
function addAlertTooltips() {
state.alerts.forEach((alert) => {
const { identifier, identifierValue, tooltipType, message } = alert;
const targetCell = $(`[data-${identifier}="${identifierValue}"`);
if (!targetCell.length) return;
addTooltipToCell(targetCell, { type: tooltipType, message });
});
}
/**
*
* Load the Table, populate it with data
*
*/
function loadTableData() {
// Prepare for new table data & show loading
$("#tbody").empty();
$("#loading").show();
$("#downloadCSV").attr("disabled", true);
$("#downloadCSV").addClass("disabled");
// Query new data and populate table
// TODO: update period and org unit display
return getAnalyticsData()
.then(populateCellValues)
.then(populateHtmlTableBodyWithValues)
.then(addAlertTooltips)
.then(() => {
$("#downloadCSV").attr("disabled", false);
$("#downloadCSV").removeClass("disabled");
});
}
/**
*
* CSV Export
*
*/
function exportToCSV() {
const csvPrefix = "data:text/csv;charset=utf-8,";
// 0. Include Org unit and period
const {
period,
allYears,
orgUnit,
allOrgUnits,
orgUnitPrettyString,
periodPrettyString,
} = state;
const csvOrgUnit = `Organisation Unit(s):,${
orgUnitPrettyString || allOrgUnits.get(orgUnit)
}\n`;
const csvPeriod = `Period(s):,${
period === allYears ? "All Years" : period
}\n\n`;
// 1. Make two header rows for column title
const colHeadersTop = [null];
const colHeadersBot = [null];
const columnHeaders = columns.forEach((column) => {
// TODO: Short names?
// If no subcategories, enter column name on top and null on bottom.
if (!column.subcategories) {
colHeadersTop.push(column.name);
colHeadersBot.push(null);
return;
}
// If column has subcategories, enter col name and n-1 spaces on top,
// and all subcategories in bottom.
column.subcategories.forEach((subcategory, idx) => {
colHeadersTop.push(idx === 0 ? column.name : null);
colHeadersBot.push(subcategory.name);
});
});
const csvHeaders =
colHeadersTop.join(",") + "\n" + colHeadersBot.join(",") + "\n";
// 2. Map each row; join with newlines