-
Notifications
You must be signed in to change notification settings - Fork 1
/
backend.js
executable file
·1993 lines (1835 loc) · 75.3 KB
/
backend.js
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
// This file defines the database object, which stores the data sets and allows to query them.
"use strict";
var db = {
totalSeriesName: "Total",
singleSeriesName: "Value",
countries: {},
// Code => ID
countriesCodes: {},
// ID => Code
countryNames: {},
// ID => Name
countryNamesReverse: {},
// Name => ID
countriesWithData: [],
// List of IDs
dsTypes:
{ "AllCarsByBrand": 1
, "AllCarsTotal": 2
, "ElectricCarsByModel": 3
, "ElectricCarsByBrand": 4
, "ElectricCarsTotal": 5
},
datasets: [],
// All datasets of the database.
// Format of entries:
// - country: country enum value
// - countryName: country display name
// - monthString: month in the form "2020-01"
// - perQuarter: boolean
// - year: integer
// - month: integer 1..12
// - dsType: dataset dsType enum value
// - source: source URL
// - data: object of brand -> number of sales or
// object of model -> number of sales
companyGroupNames: [],
// List of company group names.
// Sorted alphabetical.
companiesByBrand: {},
// Brand -> company.
companies: [],
// List of company groups and brands which do not belong to a company group.
// Sorted alphabetical.
brands: [],
// List of brands used in the datasets.
// Sorted alphabetical.
models: [],
// List of electric car models used in the datasets.
// Format: e.g. "Tesla|Model 3".
// Sorted alphabetical.
initialize: function() {
// fill country variables
let id = 0;
for (const code in countryNamesByCode) {
const name = countryNamesByCode[code];
this.countries[code] = id;
this.countriesCodes[id] = code;
this.countryNames[id] = name;
this.countryNamesReverse[name] = id;
id++;
}
},
insert: function(country, dateString, dsType, source, data) {
// Adds the data for one counry and one month or one quarter and one dataset type.
// - country: country enum value
// - dateString: month in the form "2020-01" or quarter in the form "2020-Q1"
// - dsType: dataset dsType enum value
// - source: source URL
// - data: number of sales or
// object of brand -> number of sales or
// object of model -> number of sales
if (!this.countriesWithData.includes(country))
this.countriesWithData.push(country);
let dataset =
{ country: country
, countryName: this.countryNames[country]
, dsType: dsType
, isEvs: dsType > this.dsTypes.AllCarsTotal
, source: source
};
if (dateString.substr(5, 1) == 'Q') {
dataset.perQuarter = true;
dataset.data = {};
for (const key in data) {
const val = Math.round(data[key] / 3);
if (val > 0)
dataset.data[key] = val;
}
dataset.year = parseInt(dateString.substr(0, 4));
dataset.month = this.quarterToMonth(parseInt(dateString.substr(6, 1)));
for (let i = 0; i < 3; i++) {
dataset.monthString = this.formatMonth(dataset.year, dataset.month);
this.datasets.push(this.cloneObject(dataset));
dataset.month++;
}
} else {
dataset.monthString = dateString;
dataset.year = parseInt(dateString.substr(0, 4));
dataset.month = parseInt(dateString.substr(5, 2));
dataset.data = data;
this.datasets.push(dataset);
}
if (dsType == this.dsTypes.ElectricCarsByModel) {
for (const model in data) {
const parts = model.split("|", 2);
const brand = parts[0];
if (!this.brands.includes(brand))
this.brands.push(brand);
if (!this.models.includes(model))
this.models.push(model);
}
} else {
for (const brand in data) {
if (!this.brands.includes(brand))
this.brands.push(brand);
}
}
},
finalizeDataLoading: function() {
// This should be called once after all country data files are loaded.
// Process company groups
let brandsInAGroup = [];
for (const groupName in companyGroups) {
this.companyGroupNames.push(groupName);
this.companies.push(groupName);
const brands = companyGroups[groupName];
for (const i in brands) {
const brand = brands[i];
this.companiesByBrand[brand] = groupName;
brandsInAGroup.push(brand);
}
}
for (const i in this.brands) {
const brand = this.brands[i];
if (!brandsInAGroup.includes(brand)) {
this.companies.push(brand);
this.companiesByBrand[brand] = brand;
}
}
// Sort lists, which are used in UI
this.models.sort(function(a, b) {
return a.localeCompare(b);
});
this.brands.sort(function(a, b) {
return a.localeCompare(b);
});
this.companies.sort(function(a, b) {
return a.localeCompare(b);
});
this.companyGroupNames.sort(function(a, b) {
return a.localeCompare(b);
});
},
getValueOrDefault: function(value, defaultValue) {
if (value === undefined)
return defaultValue;
return value;
},
cloneObject: function(obj) {
return JSON.parse(JSON.stringify(obj));
},
formatMonth: function(year, month) {
return year + "-" + ("0" + month).substr(-2);
},
formatQuarter: function(year, quarter) {
return year + " Q" + quarter;
},
unformatQuarter: function(text) {
// Converts "2024 Q1" to "q2024-1"
const parts = text.split(" ");
return "q" + parts[0] + "-" + parts[1].substr(1);
},
monthToQuarter: function(month) {
return Math.ceil(month / 3);
},
quarterToMonth: function(quarter) {
return 1 + (quarter - 1) * 3;
},
formatSeriesNameAndCategory: function(text) {
if (Number.isInteger(text))
return text;
else
return text.replace("|", " ");
},
metrics:
{ "all": "all-metrics"
, "salesAll": "all-sales"
, "salesElectric": "electric-sales"
, "ratioElectric": "electric-ratio"
, "ratioElectricWithinCompanyOrBrand": "brand-electric-ratio"
, "shareElectric": "electric-share"
, "shareAll": "all-share"
},
xProperties:
{ "month": "month"
, "monthAvg3": "3-month-avg"
, "monthAvg12": "12-month-avg"
, "quarter": "quarter"
, "year": "year"
, "country": "country"
, "company": "company"
, "brand": "brand"
, "model": "model"
},
timeSpanOptions:
{ "auto": "auto"
, "all": "all-time"
, "last3m": "3m"
, "last6m": "6m"
, "last1y": "1y"
, "last2y": "2y"
, "last3y": "3y"
, "last4y": "4y"
, "last5y": "5y"
, "last6y": "6y"
},
countryOptions:
{ "all": "all-countries"
, "combine": "combine-countries"
},
detailLevels:
{ "total": "total"
, "company": "split-companies"
, "brand": "split-brands"
, "model": "split-models"
},
companyOptions:
{ "all": "all-companies"
},
brandOptions:
{ "all": "all-brands"
},
modelOptions:
{ "all": "all-models"
},
views:
{ "barChart": "bar-chart"
, "lineChart": "line-chart"
, "table": "table"
, "sources": "sources"
},
maxSeriesOptions:
{ "limit5": {mostRelevant: true, count: 5}
, "limit10": {mostRelevant: true, count: 10}
, "limit15": {mostRelevant: true, count: 15}
, "limit20": {mostRelevant: true, count: 20}
, "limit30": {mostRelevant: true, count: 30}
, "top5": {mostRelevant: false, count: 5}
, "top10": {mostRelevant: false, count: 10}
, "top15": {mostRelevant: false, count: 15}
, "top20": {mostRelevant: false, count: 20}
, "top30": {mostRelevant: false, count: 30}
},
urlEncode: function(str) {
if (str)
return str.replace(/ /g, "-");
},
isByMonth: function(chartConfig) {
return [this.xProperties.month, this.xProperties.monthAvg3, this.xProperties.monthAvg12].includes(chartConfig.xProperty);
},
isByQuarter: function(chartConfig) {
return chartConfig.xProperty == this.xProperties.quarter;
},
isByYear: function(chartConfig) {
return chartConfig.xProperty == this.xProperties.year;
},
isTimeXProperty: function(chartConfig) {
return this.isByMonth(chartConfig) || this.isByQuarter(chartConfig) || this.isByYear(chartConfig);
},
isCompanyBrandModelXProperty: function(chartConfig) {
return [this.xProperties.company, this.xProperties.brand, this.xProperties.model].includes(chartConfig.xProperty);
},
isMultiCountry: function(chartConfig) {
return chartConfig.country == this.countryOptions.all || chartConfig.country.includes(",");
},
isCombinedCountry: function(chartConfig) {
return this.getCountries(chartConfig).includes(this.countryOptions.combine);
},
isSingleOrCombinedCountry: function(chartConfig) {
return !this.isMultiCountry(chartConfig) || this.isCombinedCountry(chartConfig);
},
getCountries: function(chartConfig) {
if (chartConfig.country == null)
return [];
return chartConfig.country.split(",");
},
getCompanies: function(chartConfig) {
if (chartConfig.company == null)
return [];
return chartConfig.company.split(",");
},
getBrands: function(chartConfig) {
if (chartConfig.brand == null)
return [];
return chartConfig.brand.split(",");
},
getModels: function(chartConfig) {
if (chartConfig.model == null)
return [];
return chartConfig.model.split(",");
},
getChartParams: function(chartConfig = null) {
let result = {};
// country
{
let param = {};
param.name = "country";
param.title = "Country";
param.allOptions = {};
param.allOptions[this.countryOptions.all] = "All Countries";
param.allOptions[this.countryOptions.combine] = "Combine Countries";
for (const i in this.countriesWithData) {
const id = this.countriesWithData[i];
param.allOptions[db.countriesCodes[id]] = this.countryNames[id];
}
param.options = this.cloneObject(param.allOptions);
if (chartConfig != null && !((chartConfig.country == null || this.isMultiCountry(chartConfig)) && (chartConfig.metric != this.metrics.shareAll || chartConfig.xProperty != this.xProperties.brand)))
delete param.options[this.countryOptions.combine];
param.unfoldKey = this.countryOptions.all;
param.excludeOnUnfoldAndTitle = [this.countryOptions.all, this.countryOptions.combine];
param.noMultiSelectOptions = [this.countryOptions.all];
param.disableUnfoldOption = this.countryOptions.combine;
param.additiveOptions = [this.countryOptions.combine];
param.defaultOption = this.countryOptions.all;
param.showInTitle = true;
param.showAsFilter = chartConfig == null || chartConfig.xProperty != this.xProperties.country;
param.allowMultiSelection = true;
result[param.name] = param;
}
// metric
{
let param = {};
param.name = "metric";
param.title = "Metric";
param.options = {};
param.options[this.metrics.salesElectric] = "Absolute EV Sales";
param.options[this.metrics.ratioElectric] = "Relative EV Sales";
param.options[this.metrics.shareElectric] = "EV Market Split";
param.options[this.metrics.salesAll] = "All Cars Sales";
param.options[this.metrics.ratioElectricWithinCompanyOrBrand] = "EV Ratio within Company/Brand";
param.options[this.metrics.shareAll] = "All Cars Market Split";
param.options[this.metrics.all] = "All Metrics";
param.allOptions = param.options;
param.unfoldKey = this.metrics.all;
param.noMultiSelectOptions = [this.metrics.all];
param.defaultOption = this.metrics.ratioElectric;
param.alwaysAddToUrl = true;
param.showInTitle = true;
param.showAsFilter = true;
param.allowMultiSelection = true;
param.showAlwaysAsActive = true;
result[param.name] = param;
}
// x-axis property
{
let param = {};
param.name = "xProperty";
param.title = "X-property";
param.options = {};
param.options[this.xProperties.month] = "By Month";
param.options[this.xProperties.monthAvg3] = "3-month Average";
param.options[this.xProperties.monthAvg12] = "12-month Average";
param.options[this.xProperties.quarter] = "By Quarter";
param.options[this.xProperties.year] = "By Year";
if (chartConfig == null || [this.metrics.salesAll, this.metrics.salesElectric, this.metrics.ratioElectric].includes(chartConfig.metric))
param.options[this.xProperties.country] = "By Country";
if (chartConfig == null || ![this.metrics.ratioElectric].includes(chartConfig.metric))
param.options[this.xProperties.company] = "By Company";
if (chartConfig == null || chartConfig.metric != this.metrics.ratioElectric)
param.options[this.xProperties.brand] = "By Brand";
if (chartConfig == null || [this.metrics.salesElectric, this.metrics.shareElectric].includes(chartConfig.metric))
param.options[this.xProperties.model] = "By Model";
param.allOptions = param.options;
param.defaultOption = this.xProperties.quarter;
param.showAsFilter = true;
param.showInTitle = chartConfig == null || [this.xProperties.monthAvg3, this.xProperties.monthAvg12].includes(chartConfig.xProperty);
param.showAlwaysAsActive = true;
param.breakLineAfterFilter = true;
result[param.name] = param;
}
// time span
{
let param = {};
param.name = "timeSpan";
param.title = "Time span";
param.showAsFilter = chartConfig == null || !this.isByYear(chartConfig);
param.options = {};
param.options[this.timeSpanOptions.auto] = "Auto Time Span";
param.options[this.timeSpanOptions.all] = "All Time";
param.allOptions = param.options;
this.setTimeSpanParamOptions(param, chartConfig);
param.defaultOption = this.timeSpanOptions.auto;
param.showInTitle = chartConfig == null || !this.isTimeXProperty(chartConfig);
result[param.name] = param;
}
// company/brand/model detail level
{
let param = {};
param.name = "detailLevel";
param.title = "Detail level";
param.showAsFilter = chartConfig == null || !this.isCompanyBrandModelXProperty(chartConfig);
param.options = {};
if (chartConfig == null || ![this.metrics.shareElectric, this.metrics.shareAll, this.metrics.ratioElectricWithinCompanyOrBrand].includes(chartConfig.metric))
param.options[this.detailLevels.total] = "Total";
if (chartConfig == null || !this.isCompanyBrandModelXProperty(chartConfig)) {
param.options[this.detailLevels.company] = "Split Companies";
param.options[this.detailLevels.brand] = "Split Brands";
if (chartConfig == null || ![this.metrics.salesAll, this.metrics.shareAll, this.metrics.ratioElectricWithinCompanyOrBrand].includes(chartConfig.metric))
param.options[this.detailLevels.model] = "Split Models";
}
param.allOptions = param.options;
param.defaultOption = this.detailLevels.company;
param.showAlwaysAsActive = true;
result[param.name] = param;
}
// company
{
let param = {};
param.name = "company";
param.title = "Company";
param.options = {};
param.options[this.companyOptions.all] = "All Companies";
param.showAsFilter = chartConfig == null || (chartConfig.xProperty != this.xProperties.company && chartConfig.detailLevel != this.detailLevels.total);
if (chartConfig != null && param.showAsFilter) {
if (chartConfig.xProperty == this.xProperties.brand || chartConfig.detailLevel == this.detailLevels.brand) {
for (const i in this.companyGroupNames) {
const company = this.companyGroupNames[i];
param.options[company] = company;
}
} else {
for (const i in this.companies) {
const company = this.companies[i];
if (company != "other")
param.options[company] = company;
}
}
}
param.allOptions = param.options;
param.defaultOption = this.companyOptions.all;
param.excludeOnUnfoldAndTitle = [this.companyOptions.all];
param.noMultiSelectOptions = [this.companyOptions.all];
param.showInTitle = chartConfig == null || ((chartConfig.brand == this.brandOptions.all || chartConfig.company == chartConfig.brand) && !this.combineMetricAndCompanyOrBrandInTitle(chartConfig));
param.allowMultiSelection = true;
result[param.name] = param;
}
const filterContainsMultipleBrands = chartConfig == null || chartConfig.company == this.companyOptions.all || this.getCompanies(chartConfig).length > 1 || this.getBrands(chartConfig).length > 1 || this.companyGroupNames.includes(chartConfig.company);
// brand
{
let param = {};
param.name = "brand";
param.title = "Brand";
param.showAsFilter = chartConfig == null || (([this.detailLevels.brand, this.detailLevels.model].includes(chartConfig.detailLevel) || chartConfig.xProperty == this.xProperties.model) && filterContainsMultipleBrands);
param.options = {};
param.options[this.brandOptions.all] = "All Brands";
if (chartConfig != null && chartConfig.brand != null && (param.showAsFilter || !filterContainsMultipleBrands)) {
for (const i in this.brands) {
const brand = this.brands[i];
if (brand == "other")
continue;
if (chartConfig == null || chartConfig.company == this.companyOptions.all || this.getCompanies(chartConfig).includes(this.companiesByBrand[brand]))
param.options[brand] = brand;
}
} else {
for (const i in this.brands) {
const brand = this.brands[i];
if (brand == "other")
continue;
param.options[brand] = brand;
}
}
param.allOptions = param.options;
param.defaultOption = this.brandOptions.all;
param.excludeOnUnfoldAndTitle = [this.brandOptions.all];
param.noMultiSelectOptions = [this.brandOptions.all];
param.showInTitle = chartConfig == null || (chartConfig.brand != chartConfig.company && !this.combineMetricAndCompanyOrBrandInTitle(chartConfig));
param.allowMultiSelection = true;
result[param.name] = param;
}
// model
{
let param = {};
param.name = "model";
param.title = "Model";
param.showAsFilter = chartConfig == null || (chartConfig.detailLevel == this.detailLevels.model && (chartConfig.company != this.companyOptions.all || chartConfig.brand != this.brandOptions.all));
param.options = {};
param.options[this.modelOptions.all] = "All Models";
if (chartConfig != null && chartConfig.model != null && param.showAsFilter) {
let models = [];
let brands = [];
if (chartConfig.brand != this.brandOptions.all) {
brands = this.getBrands(chartConfig);
} else {
const companies = this.getCompanies(chartConfig);
const companyGroupsKeys = Object.keys(companyGroups);
for (const i in companies) {
const company = companies[i];
const j = companyGroupsKeys.indexOf(company);
if (j != -1)
brands = brands.concat(companyGroups[companyGroupsKeys[j]]);
else
brands.push(company);
}
}
let hasOther = false;
for (const i in this.models) {
const parts = this.models[i].split("|", 2);
const brand = parts[0];
const model = parts[1];
if (brands.includes(brand)) {
if (model == "other")
hasOther = true;
else
models.push(model);
}
}
models.sort(function(a, b) {
return a.localeCompare(b);
});
for (const i in models) {
param.options[models[i]] = models[i];
}
if (hasOther)
param.options["other"] = "Other";
} else {
for (const i in this.models) {
const parts = this.models[i].split("|", 2);
const model = parts[1];
param.options[model] = model;
}
}
param.allOptions = param.options;
param.defaultOption = this.modelOptions.all;
param.excludeOnUnfoldAndTitle = [this.modelOptions.all];
param.noMultiSelectOptions = [this.modelOptions.all];
param.allowMultiSelection = true;
result[param.name] = param;
}
// max series
{
let param = {};
param.name = "maxSeries";
param.title = "Max. series/categories";
param.options = {};
for (const i in this.maxSeriesOptions) {
const option = this.maxSeriesOptions[i];
if (option.mostRelevant)
param.options[i] = "Most Relevant " + option.count;
else
param.options[i] = "Top " + option.count;
}
param.allOptions = param.options;
param.defaultOption = "limit10";
param.showAsFilter = chartConfig == null || this.getNumberOfSeries(chartConfig) > 5 || !this.isTimeXProperty(chartConfig);
result[param.name] = param;
}
// view
{
let param = {};
param.name = "view";
param.title = "View";
param.options = {};
const allowLineChart = chartConfig == null || this.isTimeXProperty(chartConfig);
if (this.isBarChartAllowed(chartConfig) || !allowLineChart)
param.options[this.views.barChart] = "Bar Chart";
if (allowLineChart)
param.options[this.views.lineChart] = "Line Chart";
param.options[this.views.table] = "Table";
param.options[this.views.sources] = "Sources";
param.allOptions = param.options;
param.defaultOption = Object.keys(param.options)[0];
result[param.name] = param;
}
return result;
},
setTimeSpanParamOptions: function(param, chartConfig) {
if (chartConfig == null || !param.showAsFilter)
return;
if (!this.isByQuarter(chartConfig)) {
param.options[this.timeSpanOptions.last3m] = "Last 3 Months";
param.options[this.timeSpanOptions.last6m] = "Last 6 Months";
}
param.options[this.timeSpanOptions.last1y] = "Last Year";
param.options[this.timeSpanOptions.last2y] = "Last 2 Years";
param.options[this.timeSpanOptions.last3y] = "Last 3 Years";
param.options[this.timeSpanOptions.last4y] = "Last 4 Years";
param.options[this.timeSpanOptions.last5y] = "Last 5 Years";
param.options[this.timeSpanOptions.last6y] = "Last 6 Years";
let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = 1 + currentDate.getMonth();
currentMonth--;
if (currentMonth < 1) {
currentMonth = 12;
currentYear--;
}
// single month
if (!this.isByQuarter(chartConfig) && !this.isByMonth(chartConfig)) {
let year = currentYear;
let month = currentMonth;
for (let i = 0; i < 4; i++) {
param.options["m" + this.formatMonth(year, month)] = this.formatMonth(year, month);
month--;
if (month < 1) {
month = 12;
year--;
}
}
}
// single quarter
if (![this.xProperties.monthAvg3, this.xProperties.quarter].includes(chartConfig.xProperty)) {
let year = currentYear;
let quarter = this.monthToQuarter(currentMonth);
for (let i = 0; i < 4; i++) {
param.options["q" + year + "-" + quarter] = this.formatQuarter(year, quarter);
quarter--;
if (quarter < 1) {
quarter = 4;
year--;
}
}
}
// single year
let year = currentYear;
for (let i = 0; i <= 4; i++) {
param.options["y" + year] = year;
year--;
}
// Allow to select a time spans which is not included in the suggested options
if (chartConfig.timeSpan != null && param.options[chartConfig.timeSpan] == null) {
let text = chartConfig.timeSpan.substr(1);
if (chartConfig.timeSpan.startsWith("q")) {
const year = chartConfig.timeSpan.substr(1, 4);
const quarter = chartConfig.timeSpan.substr(6, 1);
text = this.formatQuarter(year, quarter);
}
param.options[chartConfig.timeSpan] = text;
}
},
getRealTimeSpan: function(chartConfig) {
if (chartConfig.timeSpan == this.timeSpanOptions.auto) {
if (this.isByYear(chartConfig))
return this.timeSpanOptions.all;
else if ([this.xProperties.quarter, this.xProperties.monthAvg12].includes(chartConfig.xProperty))
return this.timeSpanOptions.last3y;
else
return this.timeSpanOptions.last2y;
}
return chartConfig.timeSpan;
},
encodeChartConfig: function(chartConfig, changedParamName = null) {
chartConfig = this.makeChartConfigValid(chartConfig, changedParamName);
let parts = [];
const params = this.getChartParams(chartConfig);
for (const i in params) {
const param = params[i];
if (chartConfig[param.name] == param.defaultOption && !param.alwaysAddToUrl)
continue;
if (!(param.name in chartConfig))
continue;
const values = chartConfig[param.name].split(",");
for (const i in values) {
if (values[i] != "") {
const encoded = this.urlEncode(values[i]);
if (!parts.includes(encoded))
parts.push(encoded);
}
}
}
return parts.join(":");
},
normalizeSearchString: function(s) {
s = s.replace(/-/g, "");
s = s.replace(/\./g, "");
s = s.replace(/ä/g, "ae");
s = s.replace(/ö/g, "oe");
s = s.replace(/ü/g, "ue");
s = s.replace(/ß/g, "ss");
s = s.replace(/é/g, "e");
s = s.replace(/ë/g, "e");
s = s.replace(/Š/g, "s");
s = s.toLowerCase();
return s;
},
decodeChartConfigString: function(chartConfigString) {
let parts = [];
if (chartConfigString != "") {
const partsRaw = chartConfigString.split(":");
// process strings for backward compatibility
for (const i in partsRaw) {
let part = partsRaw[i];
if (part == "combine-brands")
part = this.detailLevels.total;
else if (part == "all-models")
part = this.detailLevels.model;
parts.push(part);
}
}
let result = {};
let params = this.getChartParams();
for (const i in params) {
if (!params[i])
continue;
const param = params[i];
let selectedValues = [];
for (const j in parts) {
const part = parts[j];
const partNormalized = this.normalizeSearchString(part);
let optionsKeyMatched = null;
for (const key in param.options) {
if (this.normalizeSearchString(db.urlEncode(key)) == partNormalized) {
optionsKeyMatched = key;
delete parts[j]; // avoid using a part twice
break;
}
}
if (optionsKeyMatched != null) {
if (!selectedValues.includes(optionsKeyMatched))
selectedValues.push(optionsKeyMatched);
if (!param.allowMultiSelection)
break;
} else if (param.name == "timeSpan" && Number.isInteger(parseInt(part[1])) && (part.startsWith("m") || part.startsWith("q") || part.startsWith("y"))) {
// Allow to select a time spans which is not included in the suggested options
selectedValues.push(part);
}
}
if (selectedValues.length == 0)
selectedValues.push(param.defaultOption);
result[param.name] = selectedValues.join(",");
params = this.getChartParams(result);
}
result.unfoldedByParams = [];
return this.makeChartConfigValid(result);
},
makeChartConfigValid: function(chartConfig, changedParamName = null) {
let params = this.getChartParams(chartConfig);
let countryValues = this.getCountries(chartConfig);
if (!countryValues.includes(this.countryOptions.all)) {
let singleCountryCount = 0;
for (const i in countryValues) {
if (countryValues[i] != this.countryOptions.combine)
singleCountryCount++;
}
if (singleCountryCount == 0) {
countryValues.push(this.countryOptions.all);
chartConfig.country = countryValues.join(",");
} else if (singleCountryCount == 1 && countryValues.length > 0) {
for (const i in countryValues) {
if (countryValues[i] != this.countryOptions.combine) {
chartConfig.country = countryValues[i];
break;
}
}
}
}
if (chartConfig.metric.includes(",")) {
const values = chartConfig.metric.split(",");
if (values.includes(this.metrics.all))
chartConfig.metric = this.metrics.all;
}
if (chartConfig.xProperty == this.xProperties.country)
chartConfig.country = this.countryOptions.all;
if (chartConfig.xProperty == this.xProperties.company)
chartConfig.company = this.companyOptions.all;
if (chartConfig.xProperty == this.xProperties.brand)
chartConfig.brand = this.brandOptions.all;
if (chartConfig.xProperty == this.xProperties.model && ![this.metrics.salesElectric, this.metrics.shareElectric].includes(chartConfig.metric))
chartConfig.xProperty = this.xProperties.brand;
if (chartConfig.country == this.countryOptions.all && !Object.keys(params.country.options).includes(this.countryOptions.all))
chartConfig.country = db.countriesCodes[this.countriesWithData[0]];
if (!Object.keys(params.xProperty.options).includes(chartConfig.xProperty))
chartConfig.xProperty = params.xProperty.defaultOption;
if( this.isCompanyBrandModelXProperty(chartConfig))
chartConfig.detailLevel = "";
else if (!Object.keys(params.detailLevel.options).includes(chartConfig.detailLevel))
chartConfig.detailLevel = params.detailLevel.defaultOption;
if (chartConfig.company == null)
chartConfig.company = params.company.defaultOption;
if (chartConfig.brand == null)
chartConfig.brand = params.brand.defaultOption;
if (chartConfig.model == null)
chartConfig.model = params.model.defaultOption;
// replace company groups by their brands when switching from detailLevel.company to detailLevel.brand
const companies = this.getCompanies(chartConfig);
if (chartConfig.detailLevel == this.detailLevels.brand && companies.length > 1) {
let brands = [];
const companyGroupsKeys = Object.keys(companyGroups);
for (const i in companies) {
const company = companies[i];
const j = companyGroupsKeys.indexOf(company);
if (j != -1)
brands = brands.concat(companyGroups[companyGroupsKeys[j]]);
else
brands.push(company);
}
chartConfig.brand = brands.join(",");
chartConfig.company = this.companyOptions.all;
}
// move brands from 'company' to 'brand' property when multiple non-related companies/brands are selected
if (chartConfig.company != this.companyOptions.all && chartConfig.brand != this.brandOptions.all) {
const brands = this.getBrands(chartConfig);
var apply = false;
let newCompanies = companies;
for (const i in brands) {
const brand = brands[i];
const company = this.companiesByBrand[brand];
if (company != null && chartConfig.company != company) {
newCompanies.push(brand);
apply = true;
}
}
if (apply) {
chartConfig.brand = newCompanies.join(",");
chartConfig.company = this.companyOptions.all;
}
}
if (this.isTimeXProperty(chartConfig) && chartConfig.timeSpan != null) {
if (chartConfig.timeSpan.startsWith("m")
|| (chartConfig.timeSpan.startsWith("q") && !this.isByMonth(chartConfig))
|| (chartConfig.timeSpan.startsWith("y") && this.isByYear(chartConfig))) {
chartConfig.timeSpan = params.timeSpan.defaultOption;
}
}
params = this.getChartParams(chartConfig); // update
if (!Object.keys(params.view.options).includes(chartConfig.view))
chartConfig.view = params.view.defaultOption;
// reset brand filter, when company filter is reset
if (changedParamName == "company" && chartConfig.company == this.companyOptions.all)
chartConfig.brand = this.brandOptions.all;
return chartConfig;
},
applyNewDefaultOptions: function(newChartConfig, curChartConfig) {
// reset parameters, which are set to the current default option, to the new default option
const newParams = this.getChartParams(newChartConfig);
const curParams = this.getChartParams(curChartConfig);
for (const i in curParams) {
const param = curParams[i];
if (newChartConfig[param.name] == param.defaultOption)
newChartConfig[param.name] = newParams[i].defaultOption;
}
},
needsUnfold: function(chartConfig) {
if (chartConfig.metric == this.metrics.all || chartConfig.metric.includes(","))
return true;
if (!this.isTimeXProperty(chartConfig))
return false;
let count = 0;
if (this.isMultiCountry(chartConfig) && !this.isCombinedCountry(chartConfig))
count++;
if (chartConfig.detailLevel == this.detailLevels.company && (chartConfig.company == this.companyOptions.all || this.getCompanies(chartConfig).length > 1))
count++;
if (chartConfig.detailLevel == this.detailLevels.brand && (chartConfig.brand == this.brandOptions.all || this.getBrands(chartConfig).length > 1))
count++;
if (chartConfig.detailLevel == this.detailLevels.model && (chartConfig.model == this.modelOptions.all || this.getModels(chartConfig).length > 1))
count++;
return count > 1;
},
unfoldChartConfig: function(chartConfig) {
let result = [];
let unfoldedByParams = [];
result.push(chartConfig);
const params = this.getChartParams();
for (const i in params) {
if (!this.needsUnfold(result[0]))
break;
const param = params[i];
let values = [];
if (param.unfoldKey && chartConfig[param.name] == param.unfoldKey)
values = Object.keys(param.options);
else if (param.allowMultiSelection && chartConfig[param.name] != null) {
values = chartConfig[param.name].split(",");
if (param.disableUnfoldOption != null && values.includes(param.disableUnfoldOption))
continue;
}
if (values.length <= 1)
continue;
let newResult = [];
for (const j in result) {
for (const k in values) {
if (param.excludeOnUnfoldAndTitle && param.excludeOnUnfoldAndTitle.includes(values[k]))
continue;
if (!unfoldedByParams.includes(param.name))
unfoldedByParams.push(param.name);
let newConfig = this.cloneObject(result[j]);
newConfig[param.name] = values[k];
newConfig = this.makeChartConfigValid(newConfig);
newConfig.unfoldedByParams = unfoldedByParams;
newResult.push(newConfig);
}
}
result = newResult;
}
return result;
},
getChartTitle: function(chartConfig, isSingleChart) {
let parts = [];
const params = this.getChartParams(chartConfig);
for (const i in params) {
const param = params[i];
if (!param.showInTitle)
continue;
const value = chartConfig[param.name];
if (param.allowMultiSelection && value.includes(","))
continue;
if (param.excludeOnUnfoldAndTitle && param.excludeOnUnfoldAndTitle.includes(value))
continue;
if (!isSingleChart && !chartConfig.unfoldedByParams.includes(param.name))
continue;