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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
|
odoo.define('web.PivotModel', function (require) {
"use strict";
/**
* Pivot Model
*
* The pivot model keeps an in-memory representation of the pivot table that is
* displayed on the screen. The exact layout of this representation is not so
* simple, because a pivot table is at its core a 2-dimensional object, but
* with a 'tree' component: some rows/cols can be expanded so we zoom into the
* structure.
*
* However, we need to be able to manipulate the data in a somewhat efficient
* way, and to transform it into a list of lines to be displayed by the renderer.
*
* Basicaly the pivot table presents aggregated values for various groups of records
* in one domain. If a comparison is asked for, two domains are considered.
*
* Let us consider a simple example and let us fix the vocabulary (let us suppose we are in June 2020):
* ___________________________________________________________________________________________________________________________________________
* | | Total |
* | |_____________________________________________________________________________________________________________________|
* | | Sale Team 1 | Sale Team 2 | |
* | |_______________________________________|______________________________________|______________________________________|
* | | Sales total | Sales total | Sales total |
* | |_______________________________________|______________________________________|______________________________________|
* | | May 2020 | June 2020 | Variation | May 2020 | June 2020 | Variation | May 2020 | June 2020 | Variation |
* |____________________|______________|____________|___________|_____________|____________|___________|_____________|____________|___________|
* | Total | 85 | 110 | 29.4% | 40 | 30 | -25% | 125 | 140 | 12% |
* | Europe | 25 | 35 | 40% | 40 | 30 | -25% | 65 | 65 | 0% |
* | Brussels | 0 | 15 | 100% | 30 | 30 | 0% | 30 | 45 | 50% |
* | Paris | 25 | 20 | -20% | 10 | 0 | -100% | 35 | 20 | -42.8% |
* | North America | 60 | 75 | 25% | | | | 60 | 75 | 25% |
* | Washington | 60 | 75 | 25% | | | | 60 | 75 | 25% |
* |____________________|______________|____________|___________|_____________|____________|___________|_____________|____________|___________|
*
*
* META DATA:
*
* In the above pivot table, the records have been grouped using the fields
*
* continent_id, city_id
*
* for rows and
*
* sale_team_id
*
* for columns.
*
* The measure is the field 'sales_total'.
*
* Two domains are considered: 'May 2020' and 'June 2020'.
*
* In the model,
*
* - rowGroupBys is the list [continent_id, city_id]
* - colGroupBys is the list [sale_team_id]
* - measures is the list [sales_total]
* - domains is the list [d1, d2] with d1 and d2 domain expressions
* for say sale_date in May 2020 and June 2020, for instance
* d1 = [['sale_date', >=, 2020-05-01], ['sale_date', '<=', 2020-05-31]]
* - origins is the list ['May 2020', 'June 2020']
*
* DATA:
*
* Recall that a group is constituted by records (in a given domain)
* that have the same (raw) values for a list of fields.
* Thus the group itself is identified by this list and the domain.
* In comparison mode, the same group (forgetting the domain part or 'originIndex')
* can be eventually found in the two domains.
* This defines the way in which the groups are identified or not.
*
* In the above table, (forgetting the domain) the following groups are found:
*
* the 'row groups'
* - Total
* - Europe
* - America
* - Europe, Brussels
* - Europe, Paris
* - America, Washington
*
* the 'col groups'
*
* - Total
* - Sale Team 1
* - Sale Team 2
*
* and all non trivial combinations of row groups and col groups
*
* - Europe, Sale Team 1
* - Europe, Brussels, Sale Team 2
* - America, Washington, Sale Team 1
* - ...
*
* The list of fields is created from the concatenation of two lists of fields, the first in
*
* [], [f1], [f1, f2], ... [f1, f2, ..., fn] for [f1, f2, ..., fn] the full list of groupbys
* (called rowGroupBys) used to create row groups
*
* In the example: [], [continent_id], [continent_id, city_id].
*
* and the second in
* [], [g1], [g1, g2], ... [g1, g2, ..., gm] for [g1, g2, ..., gm] the full list of groupbys
* (called colGroupBys) used to create col groups.
*
* In the example: [], [sale_team_id].
*
* Thus there are (n+1)*(m+1) lists of fields possible.
*
* In the example: 6 lists possible, namely [],
* [continent_id], [sale_team_id],
* [continent_id, sale_team_id], [continent_id, city_id],
* [continent_id, city_id, sale_team_id]
*
* A given list is thus of the form [f1,..., fi, g1,..., gj] or better [[f1,...,fi], [g1,...,gj]]
*
* For each list of fields possible and each domain considered, one read_group is done
* and gives results of the form (an exception for list [])
*
* g = {
* f1: v1, ..., fi: vi,
* g1: w1, ..., gj: wj,
* m1: x1, ..., mk: xk,
* __count: c,
* __domain: d
* }
*
* where v1,...,vi,w1,...,Wj are 'values' for the corresponding fields and
* m1,...,mk are the fields selected as measures.
*
* For example, g = {
* continent_id: [1, 'Europe']
* sale_team_id: [1, 'Sale Team 1']
* sales_count: 25,
* __count: 4
* __domain: [
* ['sale_date', >=, 2020-05-01], ['sale_date', '<=', 2020-05-31],
* ['continent_id', '=', 1],
* ['sale_team_id', '=', 1]
* ]
* }
*
* Thus the above group g is fully determined by [[v1,...,vi], [w1,...,wj]] and the base domain
* or the corresponding 'originIndex'.
*
* When j=0, g corresponds to a row group (or also row header) and is of the form [[v1,...,vi], []] or more simply [v1,...vi]
* (not forgetting the list [v1,...vi] comes from left).
* When i=0, g corresponds to a col group (or col header) and is of the form [[], [w1,...,wj]] or more simply [w1,...,wj].
*
* A generic group g as above [[v1,...,vi], [w1,...,wj]] corresponds to the two headers [[v1,...,vi], []]
* and [[], [w1,...,wj]].
*
* Here is a description of the data structure manipulated by the pivot model.
*
* Five objects contain all the data from the read_groups
*
* - rowGroupTree: contains information on row headers
* the nodes correspond to the groups of the form [[v1,...,vi], []]
* The root is [[], []].
* A node [[v1,...,vl], []] has as direct children the nodes of the form [[v1,...,vl,v], []],
* this means that a direct child is obtained by grouping records using the single field fi+1
*
* The structure at each level is of the form
*
* {
* root: {
* values: [v1,...,vl],
* labels: [la1,...,lal]
* },
* directSubTrees: {
* v => {
* root: {
* values: [v1,...,vl,v]
* labels: [label1,...,labell,label]
* },
* directSubTrees: {...}
* },
* v' => {...},
* ...
* }
* }
*
* (directSubTrees is a Map instance)
*
* In the example, the rowGroupTree is:
*
* {
* root: {
* values: [],
* labels: []
* },
* directSubTrees: {
* 1 => {
* root: {
* values: [1],
* labels: ['Europe'],
* },
* directSubTrees: {
* 1 => {
* root: {
* values: [1, 1],
* labels: ['Europe', 'Brussels'],
* },
* directSubTrees: new Map(),
* },
* 2 => {
* root: {
* values: [1, 2],
* labels: ['Europe', 'Paris'],
* },
* directSubTrees: new Map(),
* },
* },
* },
* 2 => {
* root: {
* values: [2],
* labels: ['America'],
* },
* directSubTrees: {
* 3 => {
* root: {
* values: [2, 3],
* labels: ['America', 'Washington'],
* }
* directSubTrees: new Map(),
* },
* },
* },
* },
* }
*
* - colGroupTree: contains information on col headers
* The same as above with right instead of left
*
* - measurements: contains information on measure values for all the groups
*
* the object keys are of the form JSON.stringify([[v1,...,vi], [w1,...,wj]])
* and values are arrays of length equal to number of origins containing objects of the form
* {m1: x1,...,mk: xk}
* The structure looks like
*
* {
* JSON.stringify([[], []]): [{m1: x1,...,mk: xk}, {m1: x1',...,mk: xk'},...]
* ....
* JSON.stringify([[v1,...,vi], [w1,...,wj]]): [{m1: y1',...,mk: yk'}, {m1: y1',...,mk: yk'},...],
* ....
* JSON.stringify([[v1,...,vn], [w1,...,wm]]): [{m1: z1',...,mk: zk'}, {m1: z1',...,mk: zk'},...],
* }
* Thus the structure contains all information for all groups and all origins on measure values.
*
*
* this.measurments["[[], []]"][0]['foo'] gives the value of the measure 'foo' for the group 'Total' and the
* first domain (origin).
*
* In the example:
* {
* "[[], []]": [{'sales_total': 125}, {'sales_total': 140}] (total/total)
* ...
* "[[1, 2], [2]]": [{'sales_total': 10}, {'sales_total': 0}] (Europe/Paris/Sale Team 2)
* ...
* }
*
* - counts: contains information on the number of records in each groups
* The structure is similar to the above but the arrays contains numbers (counts)
* - groupDomains:
* The structure is similar to the above but the arrays contains domains
*
* With this light data structures, all manipulation done by the model are eased and redundancies are limited.
* Each time a rendering or an export of the data has to be done, the pivot table is generated by the _getTable function.
*/
var AbstractModel = require('web.AbstractModel');
var concurrency = require('web.concurrency');
var core = require('web.core');
var dataComparisonUtils = require('web.dataComparisonUtils');
const Domain = require('web.Domain');
var mathUtils = require('web.mathUtils');
var session = require('web.session');
var _t = core._t;
var cartesian = mathUtils.cartesian;
var computeVariation = dataComparisonUtils.computeVariation;
var sections = mathUtils.sections;
var PivotModel = AbstractModel.extend({
/**
* @override
* @param {Object} params
*/
init: function () {
this._super.apply(this, arguments);
this.numbering = {};
this.data = null;
this._loadDataDropPrevious = new concurrency.DropPrevious();
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Add a groupBy to rowGroupBys or colGroupBys according to provided type.
*
* @param {string} groupBy
* @param {'row'|'col'} type
*/
addGroupBy: function (groupBy, type) {
if (type === 'row') {
this.data.expandedRowGroupBys.push(groupBy);
} else {
this.data.expandedColGroupBys.push(groupBy);
}
},
/**
* Close the group with id given by groupId. A type must be specified
* in case groupId is [[], []] (the id of the group 'Total') because this
* group is present in both colGroupTree and rowGroupTree.
*
* @param {Array[]} groupId
* @param {'row'|'col'} type
*/
closeGroup: function (groupId, type) {
var groupBys;
var expandedGroupBys;
let keyPart;
var group;
var tree;
if (type === 'row') {
groupBys = this.data.rowGroupBys;
expandedGroupBys = this.data.expandedRowGroupBys;
tree = this.rowGroupTree;
group = this._findGroup(this.rowGroupTree, groupId[0]);
keyPart = 0;
} else {
groupBys = this.data.colGroupBys;
expandedGroupBys = this.data.expandedColGroupBys;
tree = this.colGroupTree;
group = this._findGroup(this.colGroupTree, groupId[1]);
keyPart = 1;
}
const groupIdPart = groupId[keyPart];
const range = groupIdPart.map((_, index) => index);
function keep(key) {
const idPart = JSON.parse(key)[keyPart];
return range.some(index => groupIdPart[index] !== idPart[index]) ||
idPart.length === groupIdPart.length;
}
function omitKeys(object) {
const newObject = {};
for (const key in object) {
if (keep(key)) {
newObject[key] = object[key];
}
}
return newObject;
}
this.measurements = omitKeys(this.measurements);
this.counts = omitKeys(this.counts);
this.groupDomains = omitKeys(this.groupDomains);
group.directSubTrees.clear();
delete group.sortedKeys;
var newGroupBysLength = this._getTreeHeight(tree) - 1;
if (newGroupBysLength <= groupBys.length) {
expandedGroupBys.splice(0);
groupBys.splice(newGroupBysLength);
} else {
expandedGroupBys.splice(newGroupBysLength - groupBys.length);
}
},
/**
* Reload the view with the current rowGroupBys and colGroupBys
* This is the easiest way to expand all the groups that are not expanded
*
* @returns {Promise}
*/
expandAll: function () {
return this._loadData();
},
/**
* Expand a group by using groupBy to split it.
*
* @param {Object} group
* @param {string} groupBy
* @returns {Promise}
*/
expandGroup: async function (group, groupBy) {
var leftDivisors;
var rightDivisors;
if (group.type === 'row') {
leftDivisors = [[groupBy]];
rightDivisors = sections(this._getGroupBys().colGroupBys);
} else {
leftDivisors = sections(this._getGroupBys().rowGroupBys);
rightDivisors = [[groupBy]];
}
var divisors = cartesian(leftDivisors, rightDivisors);
delete group.type;
return this._subdivideGroup(group, divisors);
},
/**
* Export model data in a form suitable for an easy encoding of the pivot
* table in excell.
*
* @returns {Object}
*/
exportData: function () {
var measureCount = this.data.measures.length;
var originCount = this.data.origins.length;
var table = this._getTable();
// process headers
var headers = table.headers;
var colGroupHeaderRows;
var measureRow = [];
var originRow = [];
function processHeader(header) {
var inTotalColumn = header.groupId[1].length === 0;
return {
title: header.title,
width: header.width,
height: header.height,
is_bold: !!header.measure && inTotalColumn
};
}
if (originCount > 1) {
colGroupHeaderRows = headers.slice(0, headers.length - 2);
measureRow = headers[headers.length - 2].map(processHeader);
originRow = headers[headers.length - 1].map(processHeader);
} else {
colGroupHeaderRows = headers.slice(0, headers.length - 1);
measureRow = headers[headers.length - 1].map(processHeader);
}
// remove the empty headers on left side
colGroupHeaderRows[0].splice(0, 1);
colGroupHeaderRows = colGroupHeaderRows.map(function (headerRow) {
return headerRow.map(processHeader);
});
// process rows
var tableRows = table.rows.map(function (row) {
return {
title: row.title,
indent: row.indent,
values: row.subGroupMeasurements.map(function (measurement) {
var value = measurement.value;
if (value === undefined) {
value = "";
} else if (measurement.originIndexes.length > 1) {
// in that case the value is a variation and a
// number between 0 and 1
value = value * 100;
}
return {
is_bold: measurement.isBold,
value: value,
};
}),
};
});
return {
col_group_headers: colGroupHeaderRows,
measure_headers: measureRow,
origin_headers: originRow,
rows: tableRows,
measure_count: measureCount,
origin_count: originCount,
};
},
/**
* Swap the pivot columns and the rows. It is a synchronous operation.
*/
flip: function () {
// swap the data: the main column and the main row
var temp = this.rowGroupTree;
this.rowGroupTree = this.colGroupTree;
this.colGroupTree = temp;
// we need to update the record metadata: (expanded) row and col groupBys
temp = this.data.rowGroupBys;
this.data.groupedBy = this.data.colGroupBys;
this.data.rowGroupBys = this.data.colGroupBys;
this.data.colGroupBys = temp;
temp = this.data.expandedColGroupBys;
this.data.expandedColGroupBys = this.data.expandedRowGroupBys;
this.data.expandedRowGroupBys = temp;
function twistKey(key) {
return JSON.stringify(JSON.parse(key).reverse());
}
function twist(object) {
var newObject = {};
Object.keys(object).forEach(function (key) {
var value = object[key];
newObject[twistKey(key)] = value;
});
return newObject;
}
this.measurements = twist(this.measurements);
this.counts = twist(this.counts);
this.groupDomains = twist(this.groupDomains);
},
/**
* @override
*
* @param {Object} [options]
* @param {boolean} [options.raw=false]
* @returns {Object}
*/
__get: function (options) {
options = options || {};
var raw = options.raw || false;
var groupBys = this._getGroupBys();
var state = {
colGroupBys: groupBys.colGroupBys,
context: this.data.context,
domain: this.data.domain,
fields: this.fields,
hasData: this._hasData(),
isSample: this.isSampleModel,
measures: this.data.measures,
origins: this.data.origins,
rowGroupBys: groupBys.rowGroupBys,
selectionGroupBys: this._getSelectionGroupBy(groupBys),
modelName: this.modelName
};
if (!raw && state.hasData) {
state.table = this._getTable();
state.tree = this.rowGroupTree;
}
return state;
},
/**
* Returns the total number of columns of the pivot table.
*
* @returns {integer}
*/
getTableWidth: function () {
var leafCounts = this._getLeafCounts(this.colGroupTree);
return leafCounts[JSON.stringify(this.colGroupTree.root.values)] + 2;
},
/**
* @override
*
* @param {Object} params
* @param {boolean} [params.compare=false]
* @param {Object} params.context
* @param {Object} params.fields
* @param {string[]} [params.groupedBy]
* @param {string[]} params.colGroupBys
* @param {Array[]} params.domain
* @param {string[]} params.measures
* @param {string[]} params.rowGroupBys
* @param {string} [params.default_order]
* @param {string} params.modelName
* @param {Object[]} params.groupableFields
* @param {Object} params.timeRanges
* @returns {Promise}
*/
__load: function (params) {
this.initialDomain = params.domain;
this.initialRowGroupBys = params.context.pivot_row_groupby || params.rowGroupBys;
this.defaultGroupedBy = params.groupedBy;
this.fields = params.fields;
this.modelName = params.modelName;
this.groupableFields = params.groupableFields;
const measures = this._processMeasures(params.context.pivot_measures) ||
params.measures.map(m => m);
this.data = {
expandedRowGroupBys: [],
expandedColGroupBys: [],
domain: this.initialDomain,
context: _.extend({}, session.user_context, params.context),
groupedBy: params.context.pivot_row_groupby || params.groupedBy,
colGroupBys: params.context.pivot_column_groupby || params.colGroupBys,
measures,
timeRanges: params.timeRanges,
};
this._computeDerivedParams();
this.data.groupedBy = this.data.groupedBy.slice();
this.data.rowGroupBys = !_.isEmpty(this.data.groupedBy) ? this.data.groupedBy : this.initialRowGroupBys.slice();
var defaultOrder = params.default_order && params.default_order.split(' ');
if (defaultOrder) {
this.data.sortedColumn = {
groupId: [[], []],
measure: defaultOrder[0],
order: defaultOrder[1] ? defaultOrder [1] : 'asc',
};
}
return this._loadData();
},
/**
* @override
*
* @param {any} handle this parameter is ignored
* @param {Object} params
* @param {boolean} [params.compare=false]
* @param {Object} params.context
* @param {string[]} [params.groupedBy]
* @param {Array[]} params.domain
* @param {string[]} params.groupBy
* @param {string[]} params.measures
* @param {Object} [params.timeRanges]
* @returns {Promise}
*/
__reload: function (handle, params) {
var self = this;
var oldColGroupBys = this.data.colGroupBys;
var oldRowGroupBys = this.data.rowGroupBys;
if ('context' in params) {
this.data.context = params.context;
this.data.colGroupBys = params.context.pivot_column_groupby || this.data.colGroupBys;
this.data.groupedBy = params.context.pivot_row_groupby || this.data.groupedBy;
this.data.measures = this._processMeasures(params.context.pivot_measures) || this.data.measures;
this.defaultGroupedBy = this.data.groupedBy.length ? this.data.groupedBy : this.defaultGroupedBy;
}
if ('domain' in params) {
this.data.domain = params.domain;
this.initialDomain = params.domain;
} else {
this.data.domain = this.initialDomain;
}
if ('groupBy' in params) {
this.data.groupedBy = params.groupBy.length ? params.groupBy : this.defaultGroupedBy;
}
if ('timeRanges' in params) {
this.data.timeRanges = params.timeRanges;
}
this._computeDerivedParams();
this.data.groupedBy = this.data.groupedBy.slice();
this.data.rowGroupBys = !_.isEmpty(this.data.groupedBy) ? this.data.groupedBy : this.initialRowGroupBys.slice();
if (!_.isEqual(oldRowGroupBys, self.data.rowGroupBys)) {
this.data.expandedRowGroupBys = [];
}
if (!_.isEqual(oldColGroupBys, self.data.colGroupBys)) {
this.data.expandedColGroupBys = [];
}
if ('measure' in params) {
return this._toggleMeasure(params.measure);
}
if (!this._hasData()) {
return this._loadData();
}
var oldRowGroupTree = this.rowGroupTree;
var oldColGroupTree = this.colGroupTree;
return this._loadData().then(function () {
if (_.isEqual(oldRowGroupBys, self.data.rowGroupBys)) {
self._pruneTree(self.rowGroupTree, oldRowGroupTree);
}
if (_.isEqual(oldColGroupBys, self.data.colGroupBys)) {
self._pruneTree(self.colGroupTree, oldColGroupTree);
}
});
},
/**
* Sort the rows, depending on the values of a given column. This is an
* in-memory sort.
*
* @param {Object} sortedColumn
* @param {number[]} sortedColumn.groupId
*/
sortRows: function (sortedColumn) {
var self = this;
var colGroupValues = sortedColumn.groupId[1];
sortedColumn.originIndexes = sortedColumn.originIndexes || [0];
this.data.sortedColumn = sortedColumn;
var sortFunction = function (tree) {
return function (subTreeKey) {
var subTree = tree.directSubTrees.get(subTreeKey);
var groupIntersectionId = [subTree.root.values, colGroupValues];
var value = self._getCellValue(
groupIntersectionId,
sortedColumn.measure,
sortedColumn.originIndexes
) || 0;
return sortedColumn.order === 'asc' ? value : -value;
};
};
this._sortTree(sortFunction, this.rowGroupTree);
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Add labels/values in the provided groupTree. A new leaf is created in
* the groupTree with a root object corresponding to the group with given
* labels/values.
*
* @private
* @param {Object} groupTree, either this.rowGroupTree or this.colGroupTree
* @param {string[]} labels
* @param {Array} values
*/
_addGroup: function (groupTree, labels, values) {
var tree = groupTree;
// we assume here that the group with value value.slice(value.length - 2) has already been added.
values.slice(0, values.length - 1).forEach(function (value) {
tree = tree.directSubTrees.get(value);
});
tree.directSubTrees.set(values[values.length - 1], {
root: {
labels: labels,
values: values,
},
directSubTrees: new Map(),
});
},
/**
* Compute what should be used as rowGroupBys by the pivot view
*
* @private
* @returns {string[]}
*/
_computeRowGroupBys: function () {
return !_.isEmpty(this.data.groupedBy) ? this.data.groupedBy : this.initialRowGroupBys;
},
/**
* Find a group with given values in the provided groupTree, either
* this.rowGrouptree or this.colGroupTree.
*
* @private
* @param {Object} groupTree
* @param {Array} values
* @returns {Object}
*/
_findGroup: function (groupTree, values) {
var tree = groupTree;
values.slice(0, values.length).forEach(function (value) {
tree = tree.directSubTrees.get(value);
});
return tree;
},
/**
* In case originIndex is an array of length 1, thus a single origin
* index, returns the given measure for a group determined by the id
* groupId and the origin index.
* If originIndexes is an array of length 2, we compute the variation
* ot the measure values for the groups determined by groupId and the
* different origin indexes.
*
* @private
* @param {Array[]} groupId
* @param {string} measure
* @param {number[]} originIndexes
* @returns {number}
*/
_getCellValue: function (groupId, measure, originIndexes) {
var self = this;
var key = JSON.stringify(groupId);
if (!self.measurements[key]) {
return;
}
var values = originIndexes.map(function (originIndex) {
return self.measurements[key][originIndex][measure];
});
if (originIndexes.length > 1) {
return computeVariation(values[1], values[0]);
} else {
return values[0];
}
},
/**
* Returns the rowGroupBys and colGroupBys arrays that
* are actually used by the pivot view internally
* (for read_group or other purpose)
*
* @private
* @returns {Object} with keys colGroupBys and rowGroupBys
*/
_getGroupBys: function () {
return {
colGroupBys: this.data.colGroupBys.concat(this.data.expandedColGroupBys),
rowGroupBys: this.data.rowGroupBys.concat(this.data.expandedRowGroupBys),
};
},
/**
* Returns a domain representation of a group
*
* @private
* @param {Object} group
* @param {Array} group.colValues
* @param {Array} group.rowValues
* @param {number} group.originIndex
* @returns {Array[]}
*/
_getGroupDomain: function (group) {
var key = JSON.stringify([group.rowValues, group.colValues]);
return this.groupDomains[key][group.originIndex];
},
/**
* Returns the group sanitized labels.
*
* @private
* @param {Object} group
* @param {string[]} groupBys
* @returns {string[]}
*/
_getGroupLabels: function (group, groupBys) {
var self = this;
return groupBys.map(function (groupBy) {
return self._sanitizeLabel(group[groupBy], groupBy);
});
},
/**
* Returns a promise that returns the annotated read_group results
* corresponding to a partition of the given group obtained using the given
* rowGroupBy and colGroupBy.
*
* @private
* @param {Object} group
* @param {string[]} rowGroupBy
* @param {string[]} colGroupBy
* @returns {Promise}
*/
_getGroupSubdivision: function (group, rowGroupBy, colGroupBy) {
var groupDomain = this._getGroupDomain(group);
var measureSpecs = this._getMeasureSpecs();
var groupBy = rowGroupBy.concat(colGroupBy);
return this._rpc({
model: this.modelName,
method: 'read_group',
context: this.data.context,
domain: groupDomain,
fields: measureSpecs,
groupBy: groupBy,
lazy: false,
}).then(function (subGroups) {
return {
group: group,
subGroups: subGroups,
rowGroupBy: rowGroupBy,
colGroupBy: colGroupBy
};
});
},
/**
* Returns the group sanitized values.
*
* @private
* @param {Object} group
* @param {string[]} groupBys
* @returns {Array}
*/
_getGroupValues: function (group, groupBys) {
var self = this;
return groupBys.map(function (groupBy) {
return self._sanitizeValue(group[groupBy]);
});
},
/**
* Returns the leaf counts of each group inside the given tree.
*
* @private
* @param {Object} tree
* @returns {Object} keys are group ids
*/
_getLeafCounts: function (tree) {
var self = this;
var leafCounts = {};
var leafCount;
if (!tree.directSubTrees.size) {
leafCount = 1;
} else {
leafCount = [...tree.directSubTrees.values()].reduce(
function (acc, subTree) {
var subLeafCounts = self._getLeafCounts(subTree);
_.extend(leafCounts, subLeafCounts);
return acc + leafCounts[JSON.stringify(subTree.root.values)];
},
0
);
}
leafCounts[JSON.stringify(tree.root.values)] = leafCount;
return leafCounts;
},
/**
* Returns the group sanitized measure values for the measures in
* this.data.measures (that migth contain '__count', not really a fieldName).
*
* @private
* @param {Object} group
* @returns {Array}
*/
_getMeasurements: function (group) {
var self = this;
return this.data.measures.reduce(
function (measurements, fieldName) {
var measurement = group[fieldName];
if (measurement instanceof Array) {
// case field is many2one and used as measure and groupBy simultaneously
measurement = 1;
}
if (self.fields[fieldName].type === 'boolean' && measurement instanceof Boolean) {
measurement = measurement ? 1 : 0;
}
if (self.data.origins.length > 1 && !measurement) {
measurement = 0;
}
measurements[fieldName] = measurement;
return measurements;
},
{}
);
},
/**
* Returns a description of the measures row of the pivot table
*
* @private
* @param {Object[]} columns for which measure cells must be generated
* @returns {Object[]}
*/
_getMeasuresRow: function (columns) {
var self = this;
var sortedColumn = this.data.sortedColumn || {};
var measureRow = [];
columns.forEach(function (column) {
self.data.measures.forEach(function (measure) {
var measureCell = {
groupId: column.groupId,
height: 1,
measure: measure,
title: self.fields[measure].string,
width: 2 * self.data.origins.length - 1,
};
if (sortedColumn.measure === measure &&
_.isEqual(sortedColumn.groupId, column.groupId)) {
measureCell.order = sortedColumn.order;
}
measureRow.push(measureCell);
});
});
return measureRow;
},
/**
* Returns the list of measure specs associated with data.measures, i.e.
* a measure 'fieldName' becomes 'fieldName:groupOperator' where
* groupOperator is the value specified on the field 'fieldName' for
* the key group_operator.
*
* @private
* @return {string[]}
*/
_getMeasureSpecs: function () {
var self = this;
return this.data.measures.reduce(
function (acc, measure) {
if (measure === '__count') {
acc.push(measure);
return acc;
}
var type = self.fields[measure].type;
var groupOperator = self.fields[measure].group_operator;
if (type === 'many2one') {
groupOperator = 'count_distinct';
}
if (groupOperator === undefined) {
throw new Error("No aggregate function has been provided for the measure '" + measure + "'");
}
acc.push(measure + ':' + groupOperator);
return acc;
},
[]
);
},
/**
* Make sure that the labels of different many2one values are distinguished
* by numbering them if necessary.
*
* @private
* @param {Array} label
* @param {string} fieldName
* @returns {string}
*/
_getNumberedLabel: function (label, fieldName) {
var id = label[0];
var name = label[1];
this.numbering[fieldName] = this.numbering[fieldName] || {};
this.numbering[fieldName][name] = this.numbering[fieldName][name] || {};
var numbers = this.numbering[fieldName][name];
numbers[id] = numbers[id] || _.size(numbers) + 1;
return name + (numbers[id] > 1 ? " (" + numbers[id] + ")" : "");
},
/**
* Returns a description of the origins row of the pivot table
*
* @private
* @param {Object[]} columns for which origin cells must be generated
* @returns {Object[]}
*/
_getOriginsRow: function (columns) {
var self = this;
var sortedColumn = this.data.sortedColumn || {};
var originRow = [];
columns.forEach(function (column) {
var groupId = column.groupId;
var measure = column.measure;
var isSorted = sortedColumn.measure === measure &&
_.isEqual(sortedColumn.groupId, groupId);
var isSortedByOrigin = isSorted && !sortedColumn.originIndexes[1];
var isSortedByVariation = isSorted && sortedColumn.originIndexes[1];
self.data.origins.forEach(function (origin, originIndex) {
var originCell = {
groupId: groupId,
height: 1,
measure: measure,
originIndexes: [originIndex],
title: origin,
width: 1,
};
if (isSortedByOrigin && sortedColumn.originIndexes[0] === originIndex) {
originCell.order = sortedColumn.order;
}
originRow.push(originCell);
if (originIndex > 0) {
var variationCell = {
groupId: groupId,
height: 1,
measure: measure,
originIndexes: [originIndex - 1, originIndex],
title: _t('Variation'),
width: 1,
};
if (isSortedByVariation && sortedColumn.originIndexes[1] === originIndex) {
variationCell.order = sortedColumn.order;
}
originRow.push(variationCell);
}
});
});
return originRow;
},
/**
* Get the selection needed to display the group by dropdown
* @returns {Object[]}
* @private
*/
_getSelectionGroupBy: function (groupBys) {
let groupedFieldNames = groupBys.rowGroupBys
.concat(groupBys.colGroupBys)
.map(function (g) {
return g.split(':')[0];
});
var fields = Object.keys(this.groupableFields)
.map((fieldName, index) => {
return {
name: fieldName,
field: this.groupableFields[fieldName],
active: groupedFieldNames.includes(fieldName)
}
})
.sort((left, right) => left.field.string < right.field.string ? -1 : 1);
return fields;
},
/**
* Returns a description of the pivot table.
*
* @private
* @returns {Object}
*/
_getTable: function () {
var headers = this._getTableHeaders();
return {
headers: headers,
rows: this._getTableRows(this.rowGroupTree, headers[headers.length - 1]),
};
},
/**
* Returns the list of header rows of the pivot table: the col group rows
* (depending on the col groupbys), the measures row and optionnaly the
* origins row (if there are more than one origins).
*
* @private
* @returns {Object[]}
*/
_getTableHeaders: function () {
var colGroupBys = this._getGroupBys().colGroupBys;
var height = colGroupBys.length + 1;
var measureCount = this.data.measures.length;
var originCount = this.data.origins.length;
var leafCounts = this._getLeafCounts(this.colGroupTree);
var headers = [];
var measureColumns = []; // used to generate the measure cells
// 1) generate col group rows (total row + one row for each col groupby)
var colGroupRows = (new Array(height)).fill(0).map(function () {
return [];
});
// blank top left cell
colGroupRows[0].push({
height: height + 1 + (originCount > 1 ? 1 : 0), // + measures rows [+ origins row]
title: "",
width: 1,
});
// col groupby cells with group values
/**
* Recursive function that generates the header cells corresponding to
* the groups of a given tree.
*
* @param {Object} tree
*/
function generateTreeHeaders(tree, fields) {
var group = tree.root;
var rowIndex = group.values.length;
var row = colGroupRows[rowIndex];
var groupId = [[], group.values];
var isLeaf = !tree.directSubTrees.size;
var leafCount = leafCounts[JSON.stringify(tree.root.values)];
var cell = {
groupId: groupId,
height: isLeaf ? (colGroupBys.length + 1 - rowIndex) : 1,
isLeaf: isLeaf,
label: rowIndex === 0 ? undefined : fields[colGroupBys[rowIndex - 1].split(':')[0]].string,
title: group.labels[group.labels.length - 1] || _t('Total'),
width: leafCount * measureCount * (2 * originCount - 1),
};
row.push(cell);
if (isLeaf) {
measureColumns.push(cell);
}
[...tree.directSubTrees.values()].forEach(function (subTree) {
generateTreeHeaders(subTree, fields);
});
}
generateTreeHeaders(this.colGroupTree, this.fields);
// blank top right cell for 'Total' group (if there is more that one leaf)
if (leafCounts[JSON.stringify(this.colGroupTree.root.values)] > 1) {
var groupId = [[], []];
var totalTopRightCell = {
groupId: groupId,
height: height,
title: "",
width: measureCount * (2 * originCount - 1),
};
colGroupRows[0].push(totalTopRightCell);
measureColumns.push(totalTopRightCell);
}
headers = headers.concat(colGroupRows);
// 2) generate measures row
var measuresRow = this._getMeasuresRow(measureColumns);
headers.push(measuresRow);
// 3) generate origins row if more than one origin
if (originCount > 1) {
headers.push(this._getOriginsRow(measuresRow));
}
return headers;
},
/**
* Returns the list of body rows of the pivot table for a given tree.
*
* @private
* @param {Object} tree
* @param {Object[]} columns
* @returns {Object[]}
*/
_getTableRows: function (tree, columns) {
var self = this;
var rows = [];
var group = tree.root;
var rowGroupId = [group.values, []];
var title = group.labels[group.labels.length - 1] || _t('Total');
var indent = group.labels.length;
var isLeaf = !tree.directSubTrees.size;
var rowGroupBys = this._getGroupBys().rowGroupBys;
var subGroupMeasurements = columns.map(function (column) {
var colGroupId = column.groupId;
var groupIntersectionId = [rowGroupId[0], colGroupId[1]];
var measure = column.measure;
var originIndexes = column.originIndexes || [0];
var value = self._getCellValue(groupIntersectionId, measure, originIndexes);
var measurement = {
groupId: groupIntersectionId,
originIndexes: originIndexes,
measure: measure,
value: value,
isBold: !groupIntersectionId[0].length || !groupIntersectionId[1].length,
};
return measurement;
});
rows.push({
title: title,
label: indent === 0 ? undefined : this.fields[rowGroupBys[indent - 1].split(':')[0]].string,
groupId: rowGroupId,
indent: indent,
isLeaf: isLeaf,
subGroupMeasurements: subGroupMeasurements
});
var subTreeKeys = tree.sortedKeys || [...tree.directSubTrees.keys()];
subTreeKeys.forEach(function (subTreeKey) {
var subTree = tree.directSubTrees.get(subTreeKey);
rows = rows.concat(self._getTableRows(subTree, columns));
});
return rows;
},
/**
* returns the height of a given groupTree
*
* @private
* @param {Object} tree, a groupTree
* @returns {number}
*/
_getTreeHeight: function (tree) {
var subTreeHeights = [...tree.directSubTrees.values()].map(this._getTreeHeight.bind(this));
return Math.max(0, Math.max.apply(null, subTreeHeights)) + 1;
},
/**
* @private
* @returns {boolean}
*/
_hasData: function () {
return (this.counts[JSON.stringify([[], []])] || []).some(function (count) {
return count > 0;
});
},
/**
* @override
*/
_isEmpty() {
return !this._hasData();
},
/**
* Initilize/Reinitialize this.rowGroupTree, colGroupTree, measurements,
* counts and subdivide the group 'Total' as many times it is necessary.
* A first subdivision with no groupBy (divisors.slice(0, 1)) is made in
* order to see if there is data in the intersection of the group 'Total'
* and the various origins. In case there is none, nonsupplementary rpc
* will be done (see the code of subdivideGroup).
* Once the promise resolves, this.rowGroupTree, colGroupTree,
* measurements, counts are correctly set.
*
* @private
* @return {Promise}
*/
_loadData: function () {
var self = this;
this.rowGroupTree = { root: { labels: [], values: [] }, directSubTrees: new Map() };
this.colGroupTree = { root: { labels: [], values: [] }, directSubTrees: new Map() };
this.measurements = {};
this.counts = {};
var key = JSON.stringify([[], []]);
this.groupDomains = {};
this.groupDomains[key] = this.data.domains.slice(0);
var group = { rowValues: [], colValues: [] };
var groupBys = this._getGroupBys();
var leftDivisors = sections(groupBys.rowGroupBys);
var rightDivisors = sections(groupBys.colGroupBys);
var divisors = cartesian(leftDivisors, rightDivisors);
return this._subdivideGroup(group, divisors.slice(0, 1)).then(function () {
return self._subdivideGroup(group, divisors.slice(1));
});
},
/**
* Extract the information in the read_group results (groupSubdivisions)
* and develop this.rowGroupTree, colGroupTree, measurements, counts, and
* groupDomains.
* If a column needs to be sorted, the rowGroupTree corresponding to the
* group is sorted.
*
* @private
* @param {Object} group
* @param {Object[]} groupSubdivisions
*/
_prepareData: function (group, groupSubdivisions) {
var self = this;
var groupRowValues = group.rowValues;
var groupRowLabels = [];
var rowSubTree = this.rowGroupTree;
var root;
if (groupRowValues.length) {
// we should have labels information on hand! regretful!
rowSubTree = this._findGroup(this.rowGroupTree, groupRowValues);
root = rowSubTree.root;
groupRowLabels = root.labels;
}
var groupColValues = group.colValues;
var groupColLabels = [];
if (groupColValues.length) {
root = this._findGroup(this.colGroupTree, groupColValues).root;
groupColLabels = root.labels;
}
groupSubdivisions.forEach(function (groupSubdivision) {
groupSubdivision.subGroups.forEach(function (subGroup) {
var rowValues = groupRowValues.concat(self._getGroupValues(subGroup, groupSubdivision.rowGroupBy));
var rowLabels = groupRowLabels.concat(self._getGroupLabels(subGroup, groupSubdivision.rowGroupBy));
var colValues = groupColValues.concat(self._getGroupValues(subGroup, groupSubdivision.colGroupBy));
var colLabels = groupColLabels.concat(self._getGroupLabels(subGroup, groupSubdivision.colGroupBy));
if (!colValues.length && rowValues.length) {
self._addGroup(self.rowGroupTree, rowLabels, rowValues);
}
if (colValues.length && !rowValues.length) {
self._addGroup(self.colGroupTree, colLabels, colValues);
}
var key = JSON.stringify([rowValues, colValues]);
var originIndex = groupSubdivision.group.originIndex;
if (!(key in self.measurements)) {
self.measurements[key] = self.data.origins.map(function () {
return self._getMeasurements({});
});
}
self.measurements[key][originIndex] = self._getMeasurements(subGroup);
if (!(key in self.counts)) {
self.counts[key] = self.data.origins.map(function () {
return 0;
});
}
self.counts[key][originIndex] = subGroup.__count;
if (!(key in self.groupDomains)) {
self.groupDomains[key] = self.data.origins.map(function () {
return Domain.FALSE_DOMAIN;
});
}
// if __domain is not defined this means that we are in the
// case where
// groupSubdivision.rowGroupBy = groupSubdivision.rowGroupBy = []
if (subGroup.__domain) {
self.groupDomains[key][originIndex] = subGroup.__domain;
}
});
});
if (this.data.sortedColumn) {
this.sortRows(this.data.sortedColumn, rowSubTree);
}
},
/**
* In the preview implementation of the pivot view (a.k.a. version 2),
* the virtual field used to display the number of records was named
* __count__, whereas __count is actually the one used in xml. So
* basically, activating a filter specifying __count as measures crashed.
* Unfortunately, as __count__ was used in the JS, all filters saved as
* favorite at that time were saved with __count__, and not __count.
* So in order the make them still work with the new implementation, we
* handle both __count__ and __count.
*
* This function replaces in the given array of measures occurences of
* '__count__' by '__count'.
*
* @private
* @param {Array[string] || undefined} measures
* @returns {Array[string] || undefined}
*/
_processMeasures: function (measures) {
if (measures) {
return _.map(measures, function (measure) {
return measure === '__count__' ? '__count' : measure;
});
}
},
/**
* Determine this.data.domains and this.data.origins from
* this.data.domain and this.data.timeRanges;
*
* @private
*/
_computeDerivedParams: function () {
const { range, rangeDescription, comparisonRange, comparisonRangeDescription } = this.data.timeRanges;
if (range) {
this.data.domains = [this.data.domain.concat(comparisonRange), this.data.domain.concat(range)];
this.data.origins = [comparisonRangeDescription, rangeDescription];
} else {
this.data.domains = [this.data.domain];
this.data.origins = [""];
}
},
/**
* Make any group in tree a leaf if it was a leaf in oldTree.
*
* @private
* @param {Object} tree
* @param {Object} oldTree
*/
_pruneTree: function (tree, oldTree) {
if (!oldTree.directSubTrees.size) {
tree.directSubTrees.clear();
delete tree.sortedKeys;
return;
}
var self = this;
[...tree.directSubTrees.keys()].forEach(function (subTreeKey) {
var subTree = tree.directSubTrees.get(subTreeKey);
if (!oldTree.directSubTrees.has(subTreeKey)) {
subTree.directSubTrees.clear();
delete subTreeKey.sortedKeys;
} else {
var oldSubTree = oldTree.directSubTrees.get(subTreeKey);
self._pruneTree(subTree, oldSubTree);
}
});
},
/**
* Toggle the active state for a given measure, then reload the data
* if this turns out to be necessary.
*
* @param {string} fieldName
* @returns {Promise}
*/
_toggleMeasure: function (fieldName) {
var index = this.data.measures.indexOf(fieldName);
if (index !== -1) {
this.data.measures.splice(index, 1);
// in this case, we already have all data in memory, no need to
// actually reload a lesser amount of information
return Promise.resolve();
} else {
this.data.measures.push(fieldName);
}
return this._loadData();
},
/**
* Extract from a groupBy value a label.
*
* @private
* @param {any} value
* @param {string} groupBy
* @returns {string}
*/
_sanitizeLabel: function (value, groupBy) {
var fieldName = groupBy.split(':')[0];
if (value === false) {
return _t("Undefined");
}
if (value instanceof Array) {
return this._getNumberedLabel(value, fieldName);
}
if (fieldName && this.fields[fieldName] && (this.fields[fieldName].type === 'selection')) {
var selected = _.where(this.fields[fieldName].selection, { 0: value })[0];
return selected ? selected[1] : value;
}
return value;
},
/**
* Extract from a groupBy value the raw value of that groupBy (discarding
* a label if any)
*
* @private
* @param {any} value
* @returns {any}
*/
_sanitizeValue: function (value) {
if (value instanceof Array) {
return value[0];
}
return value;
},
/**
* Get all partitions of a given group using the provided list of divisors
* and enrich the objects of this.rowGroupTree, colGroupTree,
* measurements, counts.
*
* @private
* @param {Object} group
* @param {Array[]} divisors
* @returns
*/
_subdivideGroup: function (group, divisors) {
var self = this;
var key = JSON.stringify([group.rowValues, group.colValues]);
var proms = this.data.origins.reduce(
function (acc, origin, originIndex) {
// if no information on group content is available, we fetch data.
// if group is known to be empty for the given origin,
// we don't need to fetch data fot that origin.
if (!self.counts[key] || self.counts[key][originIndex] > 0) {
var subGroup = {
rowValues: group.rowValues,
colValues: group.colValues,
originIndex: originIndex
};
divisors.forEach(function (divisor) {
acc.push(self._getGroupSubdivision(subGroup, divisor[0], divisor[1]));
});
}
return acc;
},
[]
);
return this._loadDataDropPrevious.add(Promise.all(proms)).then(function (groupSubdivisions) {
if (groupSubdivisions.length) {
self._prepareData(group, groupSubdivisions);
}
});
},
/**
* Sort recursively the subTrees of tree using sortFunction.
* In the end each node of the tree has its direct children sorted
* according to the criterion reprensented by sortFunction.
*
* @private
* @param {Function} sortFunction
* @param {Object} tree
*/
_sortTree: function (sortFunction, tree) {
var self = this;
tree.sortedKeys = _.sortBy([...tree.directSubTrees.keys()], sortFunction(tree));
[...tree.directSubTrees.values()].forEach(function (subTree) {
self._sortTree(sortFunction, subTree);
});
},
});
return PivotModel;
});
|