Passed
Push — master ( 0b1a33...6372a5 )
by Marcel
06:49
created

js/filter.js   F

Complexity

Total Complexity 64
Complexity/F 3.37

Size

Lines of Code 518
Function Count 19

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 369
c 0
b 0
f 0
dl 0
loc 518
rs 3.28
wmc 64
mnd 45
bc 45
fnc 19
bpm 2.3684
cpm 3.3684
noi 9

How to fix   Complexity   

Complexity

Complex classes like js/filter.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/**
2
 * Analytics
3
 *
4
 * This file is licensed under the Affero General Public License version 3 or
5
 * later. See the LICENSE.md file.
6
 *
7
 * @author Marcel Scherello <[email protected]>
8
 * @copyright 2021 Marcel Scherello
9
 */
10
/** global: OCA */
11
/** global: OCP */
12
/** global: OC */
13
/** global: table */
14
/** global: Chart */
15
/** global: cloner */
16
17
'use strict';
18
/**
19
 * @namespace OCA.Analytics.Filter
20
 */
21
OCA.Analytics.Filter = {
22
    optionTextsArray: {
23
        'EQ': t('analytics', 'equal to'),
24
        'GT': t('analytics', 'greater than'),
25
        'LT': t('analytics', 'less than'),
26
        'LIKE': t('analytics', 'contains'),
27
        'IN': t('analytics', 'list of values'),
28
    },
29
30
    openDrilldownDialog: function () {
31
        OCA.Analytics.UI.hideReportMenu();
32
        let drilldownRows = '';
33
        let availableDimensions = OCA.Analytics.currentReportData.dimensions;
34
        let filterOptions = OCA.Analytics.currentReportData.options.filteroptions;
35
36
        for (let i = 0; i < Object.keys(availableDimensions).length; i++) {
37
            let checkboxStatus = 'checked';
38
            if (filterOptions['drilldown'] !== undefined && filterOptions['drilldown'][Object.keys(availableDimensions)[i]] !== undefined) {
39
                checkboxStatus = '';
40
            }
41
            drilldownRows = drilldownRows + '<div style="display: table-row;">'
42
                + '<div style="display: table-cell;">'
43
                + Object.values(availableDimensions)[i]
44
                + '</div>'
45
                + '<div style="display: table-cell;">'
46
                + '<input type="checkbox" id="drilldownColumn' + [i] + '" class="checkbox" name="drilldownColumn" value="' + Object.keys(availableDimensions)[i] + '" ' + checkboxStatus + '>'
47
                + '<label for="drilldownColumn' + [i] + '"> </label>'
48
                + '</div>'
49
                + '</div>';
50
        }
51
52
        document.body.insertAdjacentHTML('beforeend',
53
            '<div id="analytics_dialog_overlay" class="oc-dialog-dim"></div>'
54
            + '<div id="analytics_dialog_container" class="oc-dialog" style="position: fixed;">'
55
            + '<div id="analytics_dialog">'
56
            + '<a class="oc-dialog-close" id="btnClose"></a>'
57
            + '<h2 class="oc-dialog-title" style="display:flex;margin-right:30px;">'
58
            + t('analytics', 'Drilldown')
59
            + '</h2>'
60
            + '<div class="table" style="display: table;">'
61
62
            + '<div style="display: table-row;">'
63
            + '<div style="display: table-cell; width: 150px;">'
64
            + '</div>'
65
            + '<div style="display: table-cell; width: 50px;">'
66
            + '<img src="' + OC.imagePath('analytics', 'column') + '" style="height: 20px;" alt="column">'
67
            + '</div>'
68
            + '</div>'
69
            + drilldownRows
70
            + '</div>'
71
            + '<div class="oc-dialog-buttonrow boutons" id="buttons">'
72
            + '<a class="button primary" id="drilldownDialogGo">' + t('analytics', 'OK') + '</a>'
73
            + '<a class="button primary" id="drilldownDialogCancel">' + t('analytics', 'Cancel') + '</a>'
74
            + '</div>'
75
        );
76
77
        document.getElementById("btnClose").addEventListener("click", OCA.Analytics.Filter.close);
78
        document.getElementById("drilldownDialogCancel").addEventListener("click", OCA.Analytics.Filter.close);
79
        document.getElementById("drilldownDialogGo").addEventListener("click", OCA.Analytics.Filter.processDrilldownDialog);
80
    },
81
82
    processDrilldownDialog: function () {
83
        let filterOptions = OCA.Analytics.currentReportData.options.filteroptions;
84
        let drilldownColumns = document.getElementsByName('drilldownColumn');
85
86
        for (let i = 0; i < drilldownColumns.length; i++) {
87
            let dimension = drilldownColumns[i].value;
88
            if (drilldownColumns[i].checked === false) {
89
                if (filterOptions['drilldown'] === undefined) {
90
                    filterOptions['drilldown'] = {};
91
                }
92
                filterOptions['drilldown'][dimension] = false;
93
            } else {
94
                if (filterOptions['drilldown'] !== undefined && filterOptions['drilldown'][dimension] !== undefined) {
95
                    delete filterOptions['drilldown'][dimension];
96
                }
97
                if (filterOptions['drilldown'] !== undefined && Object.keys(filterOptions['drilldown']).length === 0) {
98
                    delete filterOptions['drilldown'];
99
                }
100
            }
101
        }
102
103
        OCA.Analytics.currentReportData.options.filteroptions = filterOptions;
104
        OCA.Analytics.unsavedFilters = true;
105
        OCA.Analytics.Backend.getData();
106
        OCA.Analytics.Filter.close();
107
    },
108
109
    openFilterDialog: function () {
110
        OCA.Analytics.UI.hideReportMenu();
111
        document.body.insertAdjacentHTML('beforeend',
112
            '<div id="analytics_dialog_overlay" class="oc-dialog-dim"></div>'
113
            + '<div id="analytics_dialog_container" class="oc-dialog" style="position: fixed;">'
114
            + '<div id="analytics_dialog">'
115
            + '<a class="oc-dialog-close" id="btnClose"></a>'
116
            + '<h2 class="oc-dialog-title" style="display:flex;margin-right:30px;">'
117
            + t('analytics', 'Filter')
118
            + '</h2>'
119
            + '<div class="table" style="display: table;">'
120
            + '<div style="display: table-row;">'
121
            + '<div style="display: table-cell; width: 50px;"></div>'
122
            + '<div style="display: table-cell; width: 80px;"></div>'
123
            + '<div style="display: table-cell; width: 150px;">'
124
            + '<label for="filterDialogDimension">' + t('analytics', 'Filter by') + '</label>'
125
            + '</div>'
126
            + '<div style="display: table-cell; width: 150px;">'
127
            + '<label for="filterDialogOption">' + t('analytics', 'Operator') + '</label>'
128
            + '</div>'
129
            + '<div style="display: table-cell; width: 150px;">'
130
            + '<label for="filterDialogValue">' + t('analytics', 'Value') + '</label>'
131
            + '</div>'
132
            + '</div>'
133
            + '<div style="display: table-row;">'
134
            + '<div style="display: table-cell;">'
135
            + '<img src="' + OC.imagePath('analytics', 'filteradd') + '" alt="filter">'
136
            + '</div>'
137
            + '<div style="display: table-cell;">'
138
            + '<select id="filterDialogType" class="checkbox" disabled>'
139
            + '<option value="and">' + t('analytics', 'and') + '</option>'
140
            + '</select>'
141
            + '</div>'
142
            + '<div style="display: table-cell;">'
143
            + '<select id="filterDialogDimension" class="checkbox optionsInput">'
144
            + '</select>'
145
            + '</div>'
146
            + '<div style="display: table-cell;">'
147
            + '<select id="filterDialogOption" class="checkbox optionsInput">'
148
            + '</select>'
149
            + '</div>'
150
            + '<div style="display: table-cell;">'
151
            + '<input type="text" id="filterDialogValue" class="optionsInput">'
152
            + '</div></div></div>'
153
            + '<div class="oc-dialog-buttonrow boutons" id="buttons">'
154
            + '<a class="button primary" id="filterDialogGo">' + t('analytics', 'Add') + '</a>'
155
            + '<a class="button primary" id="filterDialogCancel">' + t('analytics', 'Cancel') + '</a>'
156
            + '</div>'
157
        );
158
159
        // fill Dimension dropdown
160
        let dimensionSelectOptions;
161
        let availableDimensions = OCA.Analytics.currentReportData.dimensions;
162
        for (let i = 0; i < Object.keys(availableDimensions).length; i++) {
163
            dimensionSelectOptions = dimensionSelectOptions + '<option value="' + Object.keys(availableDimensions)[i] + '">' + Object.values(availableDimensions)[i] + '</option>';
0 ignored issues
show
Bug introduced by
The variable dimensionSelectOptions seems to not be initialized for all possible execution paths.
Loading history...
164
        }
165
        document.getElementById('filterDialogDimension').innerHTML = dimensionSelectOptions;
166
167
        // fill Options dropdown
168
        let optionSelectOptions;
169
        for (let i = 0; i < Object.keys(OCA.Analytics.Filter.optionTextsArray).length; i++) {
170
            optionSelectOptions = optionSelectOptions + '<option value="' + Object.keys(OCA.Analytics.Filter.optionTextsArray)[i] + '">' + Object.values(OCA.Analytics.Filter.optionTextsArray)[i] + '</option>';
0 ignored issues
show
Bug introduced by
The variable optionSelectOptions seems to not be initialized for all possible execution paths.
Loading history...
171
        }
172
        document.getElementById('filterDialogOption').innerHTML = optionSelectOptions;
173
174
        // preselect existing filter
175
        // TODO: currently only one filter preset
176
        let filterOptions = OCA.Analytics.currentReportData.options.filteroptions;
177
        if (filterOptions !== null && filterOptions['filter'] !== undefined) {
178
            for (let filterDimension of Object.keys(filterOptions['filter'])) {
179
                let filterOption = filterOptions['filter'][filterDimension]['option'];
180
                let filterValue = filterOptions['filter'][filterDimension]['value']
181
                document.getElementById('filterDialogValue').value = filterValue;
182
                document.getElementById('filterDialogOption').value = filterOption;
183
                document.getElementById('filterDialogDimension').value = filterDimension;
184
            }
185
        }
186
187
        document.getElementById("btnClose").addEventListener("click", OCA.Analytics.Filter.close);
188
        document.getElementById("filterDialogCancel").addEventListener("click", OCA.Analytics.Filter.close);
189
        document.getElementById("filterDialogGo").addEventListener("click", OCA.Analytics.Filter.processFilterDialog);
190
        document.getElementById('filterDialogValue').addEventListener('keydown', function (event) {
191
            if (event.key === 'Enter') {
192
                OCA.Analytics.Filter.processFilterDialog();
193
            }
194
        });
195
    },
196
197
    processFilterDialog: function () {
198
        let filterOptions = OCA.Analytics.currentReportData.options.filteroptions;
199
        let dimension = document.getElementById('filterDialogDimension').value;
200
        if (filterOptions['filter'] === undefined) {
201
            filterOptions['filter'] = {};
202
        }
203
        if (filterOptions['filter'][dimension] === undefined) {
204
            filterOptions['filter'][dimension] = {};
205
        }
206
        filterOptions['filter'][dimension]['option'] = document.getElementById('filterDialogOption').value;
207
        filterOptions['filter'][dimension]['value'] = document.getElementById('filterDialogValue').value.replace(', ', ',');
208
209
        OCA.Analytics.currentReportData.options.filteroptions = filterOptions;
210
        OCA.Analytics.unsavedFilters = true;
211
        OCA.Analytics.Backend.getData();
212
        OCA.Analytics.Filter.close();
213
    },
214
215
    refreshFilterVisualisation: function () {
216
        document.getElementById('filterVisualisation').innerHTML = '';
217
        let filterDimensions = OCA.Analytics.currentReportData.dimensions;
218
        let filterOptions = OCA.Analytics.currentReportData.options.filteroptions;
219
        if (filterOptions !== null && filterOptions['filter'] !== undefined) {
220
            for (let filterDimension of Object.keys(filterOptions['filter'])) {
221
                let optionText = OCA.Analytics.Filter.optionTextsArray[filterOptions['filter'][filterDimension]['option']];
222
                let span = document.createElement('span');
223
                span.innerText = filterDimensions[filterDimension] + ' ' + optionText + ' ' + filterOptions['filter'][filterDimension]['value'];
224
                span.classList.add('filterVisualizationItem');
225
                span.id = filterDimension;
226
                span.addEventListener('click', OCA.Analytics.Filter.removeFilter)
227
                document.getElementById('filterVisualisation').appendChild(span);
228
            }
229
        }
230
        if (OCA.Analytics.unsavedFilters === true) {
231
            document.getElementById('saveIcon').style.removeProperty('display');
232
233
        } else {
234
            document.getElementById('saveIcon').style.display = 'none';
235
        }
236
237
    },
238
239
    removeFilter: function (evt) {
240
        let filterDimension = evt.target.id;
241
        let filterOptions = OCA.Analytics.currentReportData.options.filteroptions;
242
        delete filterOptions['filter'][filterDimension];
243
        if (Object.keys(filterOptions['filter']).length === 0) {
244
            delete filterOptions['filter'];
245
        }
246
        OCA.Analytics.currentReportData.options.filteroptions = filterOptions;
247
        OCA.Analytics.unsavedFilters = true;
248
        OCA.Analytics.Backend.getData();
249
    },
250
251
    openChartOptionsDialog: function () {
252
        OCA.Analytics.UI.hideReportMenu();
253
        let drilldownRows = '';
254
        let dataOptions;
255
        try {
256
            dataOptions = JSON.parse(OCA.Analytics.currentReportData.options.dataoptions);
257
        } catch (e) {
258
            dataOptions = '';
259
        }
260
        let distinctCategories = OCA.Analytics.Core.getDistinctValues(OCA.Analytics.currentReportData.data);
261
        if (dataOptions === null) dataOptions = {};
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
262
263
        // check if defined dataoptions don´t match the number of dataseries anymore
264
        if (Object.keys(dataOptions).length !== Object.keys(distinctCategories).length) {
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
265
            //dataOptions = '';
266
        }
267
268
        // get the default chart type to preset the drop downs
269
        let defaultChartType = OCA.Analytics.chartTypeMapping[OCA.Analytics.currentReportData.options.chart];
270
271
        for (let i = 0; i < Object.keys(distinctCategories).length; i++) {
272
            let color = OCA.Analytics.Filter.checkColor(dataOptions, i);
273
            drilldownRows = drilldownRows + '<div style="display: table-row;">'
274
                + '<div style="display: table-cell;">'
275
                + Object.values(distinctCategories)[i]
276
                + '</div>'
277
                + '<div style="display: table-cell;">'
278
                + '<select id="optionsYAxis' + [i] + '" name="optionsYAxis" class="optionsInput">'
279
                + '<option value="primary" ' + OCA.Analytics.Filter.checkOption(dataOptions, i, 'yAxisID', 'primary', 'primary') + '>' + t('analytics', 'Primary') + '</option>'
280
                + '<option value="secondary" ' + OCA.Analytics.Filter.checkOption(dataOptions, i, 'yAxisID', 'secondary', 'primary') + '>' + t('analytics', 'Secondary') + '</option>'
281
                + '</select>'
282
                + '</div>'
283
                + '<div style="display: table-cell;">'
284
                + '<select id="optionsChartType' + [i] + '" name="optionsChartType" class="optionsInput">'
285
                + '<option value="line" ' + OCA.Analytics.Filter.checkOption(dataOptions, i, 'type', 'line', defaultChartType) + '>' + t('analytics', 'Line') + '</option>'
286
                + '<option value="bar" ' + OCA.Analytics.Filter.checkOption(dataOptions, i, 'type', 'bar', defaultChartType) + '>' + t('analytics', 'Bar') + '</option>'
287
                + '</select>'
288
                + '</div>'
289
                + '<div style="display: table-cell;">'
290
                + '<input id="optionsColor' + [i] + '" name="optionsColor" value=' + color + ' style="background-color:' + color + ';" class="optionsInput">'
291
                + '</div>'
292
                + '</div>';
293
        }
294
295
        document.body.insertAdjacentHTML('beforeend',
296
            '<div id="analytics_dialog_overlay" class="oc-dialog-dim"></div>'
297
            + '<div id="analytics_dialog_container" class="oc-dialog" style="position: fixed;">'
298
            + '<div id="analytics_dialog">'
299
            + '<a class="oc-dialog-close" id="btnClose"></a>'
300
            + '<h2 class="oc-dialog-title" style="display:flex;margin-right:30px;">'
301
            + t('analytics', 'Chart options')
302
            + '</h2>'
303
            + '<div class="table" style="display: table;">'
304
305
            + '<div style="display: table-row;">'
306
            + '<div style="display: table-cell; width: 150px;">' + t('analytics', 'Data series')
307
            + '</div>'
308
            + '<div style="display: table-cell; width: 150px;">' + t('analytics', 'Vertical axis')
309
            + '</div>'
310
            + '<div style="display: table-cell; width: 150px;">' + t('analytics', 'Chart type')
311
            + '</div>'
312
            + '<div style="display: table-cell; width: 150px;">' + t('analytics', 'Color')
313
            + '</div>'
314
            + '</div>'
315
            + drilldownRows
316
            + '</div>'
317
            + '<div class="oc-dialog-buttonrow boutons" id="buttons">'
318
            + '<a class="button primary" id="drilldownDialogGo">' + t('analytics', 'OK') + '</a>'
319
            + '<a class="button primary" id="drilldownDialogCancel">' + t('analytics', 'Cancel') + '</a>'
320
            + '</div>'
321
        );
322
323
        let optionsColor = document.getElementsByName('optionsColor');
324
        for (let i = 0; i < optionsColor.length; i++) {
325
            optionsColor[i].addEventListener('keyup', OCA.Analytics.Filter.updateColor);
326
        }
327
328
        document.getElementById("btnClose").addEventListener("click", OCA.Analytics.Filter.close);
329
        document.getElementById("drilldownDialogCancel").addEventListener("click", OCA.Analytics.Filter.close);
330
        document.getElementById("drilldownDialogGo").addEventListener("click", OCA.Analytics.Filter.processOptionsDialog);
331
    },
332
333
    processOptionsDialog: function () {
334
        let dataOptions = OCA.Analytics.currentReportData.options.dataoptions;
335
        dataOptions === '' ? dataOptions = [] : dataOptions;
336
        let chartOptions = OCA.Analytics.currentReportData.options.chartoptions;
337
        chartOptions === '' ? chartOptions = {} : chartOptions;
338
        let userDatasetOptions = [];
339
        let nonDefaultValues, seondaryAxisRequired = false;
340
        let optionObject = {};
0 ignored issues
show
Unused Code introduced by
The assignment to variable optionObject seems to be never used. Consider removing it.
Loading history...
341
342
        // get the defaults (e.g. line or bar) to derive if there is any relevant change by the user
343
        let defaultChartType = OCA.Analytics.chartTypeMapping[OCA.Analytics.currentReportData.options.chart];
344
        let defaultYAxis = 'primary';
345
        let defaultColors = ["#aec7e8", "#ffbb78", "#98df8a", "#ff9896", "#c5b0d5", "#c49c94", "#f7b6d2", "#c7c7c7", "#dbdb8d", "#9edae5"];
346
347
        // loop all selections from the option dialog and add them to an array
348
        let optionsYAxis = document.getElementsByName('optionsYAxis');
349
        let optionsChartType = document.getElementsByName('optionsChartType');
350
        let optionsColor = document.getElementsByName('optionsColor');
351
352
        for (let i = 0; i < optionsYAxis.length; i++) {
353
            let j = i - (Math.floor(i / defaultColors.length) * defaultColors.length)
354
            optionObject = {};
355
            if (optionsYAxis[i].value !== defaultYAxis) {
356
                optionObject['yAxisID'] = optionsYAxis[i].value;
357
                seondaryAxisRequired = true;
358
            }
359
            if (optionsChartType[i].value !== defaultChartType) {
360
                optionObject['type'] = optionsChartType[i].value;
361
            }
362
            if (optionsColor[i].value !== defaultColors[j] && optionsColor[i].value !== '') {
363
                if (optionsColor[i].value.length === 7 && optionsColor[i].value.charAt(0) === '#') {
364
                    optionObject['backgroundColor'] = optionsColor[i].value;
365
                    optionObject['borderColor'] = optionsColor[i].value;
366
                }
367
            }
368
            if (Object.keys(dataOptions).length) nonDefaultValues = true;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
369
            userDatasetOptions.push(optionObject);
370
        }
371
372
        // decide of the dataseries array is relevant to be saved or not.
373
        // if all settings are default, all options can be removed can be removed completely
374
        // to keep the array clean, it will overwrite any existing settings.
375
        if (nonDefaultValues === true) {
0 ignored issues
show
Bug introduced by
The variable nonDefaultValues seems to not be initialized for all possible execution paths.
Loading history...
376
            //try {
377
            //    // if there are existing settings, merge them
378
            //    dataOptions = JSON.stringify(cloner.deep.merge(JSON.parse(dataOptions), userDatasetOptions));
379
            //} catch (e) {
380
            dataOptions = JSON.stringify(userDatasetOptions);
381
            //}
382
        } else {
383
            dataOptions = '';
384
        }
385
386
        // if any dataseries is tied to the secondary yAxis or not
387
        // if yes, it needs to be enabled in the chart options (in addition to the dataseries options)
388
        let enableAxisV2 = '{"scales":{"yAxes":[{},{"display":true}]}}';
389
        let enableAxis = '{"scales":{"secondary":{"display":true}}}';
390
        if (seondaryAxisRequired === true) {
391
            try {
392
                // if there are existing settings, merge them
393
                chartOptions = JSON.stringify(cloner.deep.merge(JSON.parse(chartOptions), JSON.parse(enableAxis)));
394
            } catch (e) {
395
                chartOptions = enableAxis;
396
            }
397
        } else {
398
            if (chartOptions === enableAxis || chartOptions === enableAxisV2) {
399
                // if the secondary axis is not required anymore but was enabled before
400
                // the options are cleared all together
401
                // this does only apply when ONLY the axis was enabled before
402
                // this does not do anything, if the user had own custom settings
403
                chartOptions = '';
404
            }
405
        }
406
407
        OCA.Analytics.currentReportData.options.dataoptions = dataOptions;
408
        OCA.Analytics.currentReportData.options.chartoptions = chartOptions;
409
        OCA.Analytics.unsavedFilters = true;
410
        OCA.Analytics.Backend.getData();
411
        OCA.Analytics.Filter.close();
412
    },
413
414
    close: function () {
415
        document.getElementById('analytics_dialog_container').remove();
416
        document.getElementById('analytics_dialog_overlay').remove();
417
    },
418
419
    // function for shorter coding of the dialog creation
420
    checkOption: function (array, index, field, check, defaultChartType) {
421
        if (Array.isArray(array) && array.length && array[index]) {
422
            if (field in array[index]) {
423
                return array[index][field] === check ? 'selected' : '';
424
            } else if (check === defaultChartType) {
425
                return 'selected';
426
            } else {
427
                return '';
428
            }
429
        } else if (check === defaultChartType) {
430
            return 'selected';
431
        } else {
432
            return '';
433
        }
434
    },
435
436
    // function to define the color for a data series
437
    checkColor: function (array, index) {
438
        let colors = ["#aec7e8", "#ffbb78", "#98df8a", "#ff9896", "#c5b0d5", "#c49c94", "#f7b6d2", "#c7c7c7", "#dbdb8d", "#9edae5"];
439
        let j = index - (Math.floor(index / colors.length) * colors.length)
440
        let field = 'backgroundColor';
441
        if (Array.isArray(array) && array.length && array[index]) {
442
            if (field in array[index]) {
443
                return array[index][field];
444
            } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
445
                return colors[j];
446
            }
447
        } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
448
            return colors[j];
449
        }
450
    },
451
452
    // live update the background color of the input boxes
453
    updateColor: function (evt) {
454
        let field = evt.target;
455
        if (field.value.length === 7 && field.value.charAt(0) === '#') {
456
            field.style.backgroundColor = field.value;
457
        }
458
    }
459
};
460
461
OCA.Analytics.Filter.Backend = {
462
    newReport: function () {
463
        const reportId = parseInt(OCA.Analytics.currentReportData.options.id);
464
465
        if (typeof (OCA.Analytics.currentReportData.options.filteroptions) === 'undefined') {
466
            OCA.Analytics.currentReportData.options.filteroptions = {};
467
        } else {
468
            OCA.Analytics.currentReportData.options.filteroptions = JSON.stringify(OCA.Analytics.currentReportData.options.filteroptions);
469
        }
470
471
        OCA.Analytics.unsavedFilters = false;
472
473
        $.ajax({
474
            type: 'POST',
475
            url: OC.generateUrl('apps/analytics/report/copy'),
476
            data: {
477
                'reportId': reportId,
478
                'chartoptions': OCA.Analytics.currentReportData.options.chartoptions,
479
                'dataoptions': OCA.Analytics.currentReportData.options.dataoptions,
480
                'filteroptions': OCA.Analytics.currentReportData.options.filteroptions,
481
            },
482
            success: function (data) {
483
                OCA.Analytics.Navigation.init(data);
484
            }
485
        });
486
487
    },
488
489
    updateReport: function () {
490
        const reportId = parseInt(OCA.Analytics.currentReportData.options.id);
491
492
        if (typeof (OCA.Analytics.currentReportData.options.filteroptions) === 'undefined') {
493
            OCA.Analytics.currentReportData.options.filteroptions = {};
494
        } else {
495
            OCA.Analytics.currentReportData.options.filteroptions = JSON.stringify(OCA.Analytics.currentReportData.options.filteroptions);
496
        }
497
498
        OCA.Analytics.unsavedFilters = false;
499
500
        $.ajax({
501
            type: 'POST',
502
            url: OC.generateUrl('apps/analytics/report/') + reportId + '/options',
503
            data: {
504
                'chartoptions': OCA.Analytics.currentReportData.options.chartoptions,
505
                'dataoptions': OCA.Analytics.currentReportData.options.dataoptions,
506
                'filteroptions': OCA.Analytics.currentReportData.options.filteroptions,
507
            },
508
            success: function () {
509
                delete OCA.Analytics.currentReportData.options;
510
                OCA.Analytics.Backend.getData();
511
            }
512
        });
513
    },
514
515
    saveRefresh: function (evt) {
516
        OCA.Analytics.UI.hideReportMenu();
517
        let refresh = evt.target.id;
518
        refresh = parseInt(refresh.substring(7));
519
        const datasetId = parseInt(OCA.Analytics.currentReportData.options.id);
520
521
        $.ajax({
522
            type: 'POST',
523
            url: OC.generateUrl('apps/analytics/report/') + datasetId + '/refresh',
524
            data: {
525
                'refresh': refresh,
526
            },
527
            success: function () {
528
                OCA.Analytics.Notification.notification('success', t('analytics', 'Saved'));
529
                OCA.Analytics.Backend.startRefreshTimer(refresh);
530
            }
531
        });
532
    },
533
534
};