Passed
Push — master ( 107ae9...7e7300 )
by Guangyu
12:14 queued 12s
created

myems-web/src/components/MyEMS/Store/StoreStatistics.js   B

Complexity

Total Complexity 41
Complexity/F 0

Size

Lines of Code 868
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 41
eloc 741
dl 0
loc 868
rs 8.9789
c 0
b 0
f 0
mnd 41
bc 41
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/Store/StoreStatistics.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
import React, { Fragment, useEffect, useState, useContext } from 'react';
2
import {
3
  Breadcrumb,
4
  BreadcrumbItem,
5
  Row,
6
  Col,
7
  Card,
8
  CardBody,
9
  Button,
10
  ButtonGroup,
11
  Form,
12
  FormGroup,
13
  Input,
14
  Label,
15
  CustomInput,
16
  Spinner
17
} from 'reactstrap';
18
import CountUp from 'react-countup';
19
import moment from 'moment';
20
import loadable from '@loadable/component';
21
import Cascader from 'rc-cascader';
22
import CardSummary from '../common/CardSummary';
23
import MultiTrendChart from '../common/MultiTrendChart';
24
import { getCookieValue, createCookie } from '../../../helpers/utils';
25
import withRedirect from '../../../hoc/withRedirect';
26
import { withTranslation } from 'react-i18next';
27
import { toast } from 'react-toastify';
28
import ButtonIcon from '../../common/ButtonIcon';
29
import { APIBaseURL } from '../../../config';
30
import { periodTypeOptions } from '../common/PeriodTypeOptions';
31
import { comparisonTypeOptions } from '../common/ComparisonTypeOptions';
32
import DateRangePickerWrapper from '../common/DateRangePickerWrapper';
33
import { endOfDay} from 'date-fns';
34
import AppContext from '../../../context/Context';
35
import MultipleLineChart from '../common/MultipleLineChart';
36
37
const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
38
39
const StoreStatistics = ({ setRedirect, setRedirectUrl, t }) => {
40
  let current_moment = moment();
41
  useEffect(() => {
42
    let is_logged_in = getCookieValue('is_logged_in');
43
    let user_name = getCookieValue('user_name');
44
    let user_display_name = getCookieValue('user_display_name');
45
    let user_uuid = getCookieValue('user_uuid');
46
    let token = getCookieValue('token');
47
    if (is_logged_in === null || !is_logged_in) {
48
      setRedirectUrl(`/authentication/basic/login`);
49
      setRedirect(true);
50
    } else {
51
      //update expires time of cookies
52
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
53
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
54
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
55
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
56
      createCookie('token', token, 1000 * 60 * 60 * 8);
57
    }
58
  });
59
60
61
  // State
62
  // Query Parameters
63
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
64
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
65
  const [storeList, setStoreList] = useState([]);
66
  const [selectedStore, setSelectedStore] = useState(undefined);
67
  const [comparisonType, setComparisonType] = useState('month-on-month');
68
  const [periodType, setPeriodType] = useState('daily');
69
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
70
  const [basePeriodDateRange, setBasePeriodDateRange] = useState([current_moment.clone().subtract(1, 'months').startOf('month').toDate(), current_moment.clone().subtract(1, 'months').toDate()]);
71
  const [basePeriodDateRangePickerDisabled, setBasePeriodDateRangePickerDisabled] = useState(true);
72
  const [reportingPeriodDateRange, setReportingPeriodDateRange] = useState([current_moment.clone().startOf('month').toDate(), current_moment.toDate()]);
73
  const dateRangePickerLocale = {
74
    sunday: t('sunday'),
75
    monday: t('monday'),
76
    tuesday: t('tuesday'),
77
    wednesday: t('wednesday'),
78
    thursday: t('thursday'),
79
    friday: t('friday'),
80
    saturday: t('saturday'),
81
    ok: t('ok'),
82
    today: t('today'),
83
    yesterday: t('yesterday'),
84
    hours: t('hours'),
85
    minutes: t('minutes'),
86
    seconds: t('seconds'),
87
    last7Days: t('last7Days'),
88
    formattedMonthPattern: 'yyyy-MM-dd'
89
  };
90
  const dateRangePickerStyle = { display: 'block', zIndex: 10};
91
  const { language } = useContext(AppContext);
92
93
  // buttons
94
  const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
95
  const [spinnerHidden, setSpinnerHidden] = useState(true);
96
  const [exportButtonHidden, setExportButtonHidden] = useState(true);
97
98
  //Results
99
  const [cardSummaryList, setCardSummaryList] = useState([]);
100
101
  const [storeBaseAndReportingNames, setStoreBaseAndReportingNames] = useState({"a0":""});
102
  const [storeBaseAndReportingUnits, setStoreBaseAndReportingUnits] = useState({"a0":"()"});
103
104
  const [storeBaseLabels, setStoreBaseLabels] = useState({"a0": []});
105
  const [storeBaseData, setStoreBaseData] = useState({"a0": []});
106
  const [storeBaseSubtotals, setStoreBaseSubtotals] = useState({"a0": (0).toFixed(2)});
107
108
  const [storeReportingLabels, setStoreReportingLabels] = useState({"a0": []});
109
  const [storeReportingData, setStoreReportingData] = useState({"a0": []});
110
  const [storeReportingSubtotals, setStoreReportingSubtotals] = useState({"a0": (0).toFixed(2)});
111
112
  const [storeReportingRates, setStoreReportingRates] = useState({"a0": []});
113
  const [storeReportingOptions, setStoreReportingOptions] = useState([]);
114
115
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
116
  const [parameterLineChartData, setParameterLineChartData] = useState({});
117
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
118
119
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
120
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
121
  const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
122
123
  useEffect(() => {
124
    let isResponseOK = false;
125
    fetch(APIBaseURL + '/spaces/tree', {
126
      method: 'GET',
127
      headers: {
128
        "Content-type": "application/json",
129
        "User-UUID": getCookieValue('user_uuid'),
130
        "Token": getCookieValue('token')
131
      },
132
      body: null,
133
134
    }).then(response => {
135
      console.log(response);
136
      if (response.ok) {
137
        isResponseOK = true;
138
      }
139
      return response.json();
140
    }).then(json => {
141
      console.log(json);
142
      if (isResponseOK) {
143
        // rename keys 
144
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
145
        setCascaderOptions(json);
146
        setSelectedSpaceName([json[0]].map(o => o.label));
147
        setSelectedSpaceID([json[0]].map(o => o.value));
148
        // get Stores by root Space ID
149
        let isResponseOK = false;
150
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/stores', {
151
          method: 'GET',
152
          headers: {
153
            "Content-type": "application/json",
154
            "User-UUID": getCookieValue('user_uuid'),
155
            "Token": getCookieValue('token')
156
          },
157
          body: null,
158
159
        }).then(response => {
160
          if (response.ok) {
161
            isResponseOK = true;
162
          }
163
          return response.json();
164
        }).then(json => {
165
          if (isResponseOK) {
166
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
167
            console.log(json);
168
            setStoreList(json[0]);
169
            if (json[0].length > 0) {
170
              setSelectedStore(json[0][0].value);
171
              // enable submit button
172
              setSubmitButtonDisabled(false);
173
            } else {
174
              setSelectedStore(undefined);
175
              // disable submit button
176
              setSubmitButtonDisabled(true);
177
            }
178
          } else {
179
            toast.error(t(json.description))
180
          }
181
        }).catch(err => {
182
          console.log(err);
183
        });
184
        // end of get Stores by root Space ID
185
      } else {
186
        toast.error(t(json.description));
187
      }
188
    }).catch(err => {
189
      console.log(err);
190
    });
191
192
  }, []);
193
194
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
195
196
  let onSpaceCascaderChange = (value, selectedOptions) => {
197
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
198
    setSelectedSpaceID(value[value.length - 1]);
199
200
    let isResponseOK = false;
201
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/stores', {
202
      method: 'GET',
203
      headers: {
204
        "Content-type": "application/json",
205
        "User-UUID": getCookieValue('user_uuid'),
206
        "Token": getCookieValue('token')
207
      },
208
      body: null,
209
210
    }).then(response => {
211
      if (response.ok) {
212
        isResponseOK = true;
213
      }
214
      return response.json();
215
    }).then(json => {
216
      if (isResponseOK) {
217
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
218
        console.log(json)
219
        setStoreList(json[0]);
220
        if (json[0].length > 0) {
221
          setSelectedStore(json[0][0].value);
222
          // enable submit button
223
          setSubmitButtonDisabled(false);
224
        } else {
225
          setSelectedStore(undefined);
226
          // disable submit button
227
          setSubmitButtonDisabled(true);
228
        }
229
      } else {
230
        toast.error(t(json.description))
231
      }
232
    }).catch(err => {
233
      console.log(err);
234
    });
235
  }
236
237
238
  let onComparisonTypeChange = ({ target }) => {
239
    console.log(target.value);
240
    setComparisonType(target.value);
241
    if (target.value === 'year-over-year') {
242
      setBasePeriodDateRangePickerDisabled(true);
243
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'years').toDate(),
244
        moment(reportingPeriodDateRange[1]).subtract(1, 'years').toDate()]);
245
    } else if (target.value === 'month-on-month') {
246
      setBasePeriodDateRangePickerDisabled(true);
247
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'months').toDate(),
248
        moment(reportingPeriodDateRange[1]).subtract(1, 'months').toDate()]);
249
    } else if (target.value === 'free-comparison') {
250
      setBasePeriodDateRangePickerDisabled(false);
251
    } else if (target.value === 'none-comparison') {
252
      setBasePeriodDateRange([null, null]);
253
      setBasePeriodDateRangePickerDisabled(true);
254
    }
255
  };
256
257
  // Callback fired when value changed
258
  let onBasePeriodChange = (DateRange) => {
259
    if(DateRange == null) {
260
      setBasePeriodDateRange([null, null]);
261
    } else {
262
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
263
        // if the user did not change time value, set the default time to the end of day
264
        DateRange[1] = endOfDay(DateRange[1]);
265
      }
266
      setBasePeriodDateRange([DateRange[0], DateRange[1]]);
267
    }
268
  };
269
270
  // Callback fired when value changed
271
  let onReportingPeriodChange = (DateRange) => {
272
    if(DateRange == null) {
273
      setReportingPeriodDateRange([null, null]);
274
    } else {
275
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
276
        // if the user did not change time value, set the default time to the end of day
277
        DateRange[1] = endOfDay(DateRange[1]);
278
      }
279
      setReportingPeriodDateRange([DateRange[0], DateRange[1]]);
280
      if (comparisonType === 'year-over-year') {
281
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'years').toDate(), moment(DateRange[1]).clone().subtract(1, 'years').toDate()]);
282
      } else if (comparisonType === 'month-on-month') {
283
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'months').toDate(), moment(DateRange[1]).clone().subtract(1, 'months').toDate()]);
284
      }
285
    }
286
  };
287
288
  // Callback fired when value clean
289
  let onBasePeriodClean = event => {
290
    setBasePeriodDateRange([null, null]);
291
  };
292
293
  // Callback fired when value clean
294
  let onReportingPeriodClean = event => {
295
    setReportingPeriodDateRange([null, null]);
296
  };
297
298
  const isBasePeriodTimestampExists = (base_period_data) => {
299
    const timestamps = base_period_data['timestamps'];
300
301
    if (timestamps.length === 0) {
302
      return false;
303
    }
304
305
    for (let i = 0; i < timestamps.length; i++) {
306
      if (timestamps[i].length > 0) {
307
        return true;
308
      }
309
    }
310
    return false
311
  }
312
313
  // Handler
314
  const handleSubmit = e => {
315
    e.preventDefault();
316
    console.log('handleSubmit');
317
    console.log(selectedSpaceID);
318
    console.log(selectedStore);
319
    console.log(comparisonType);
320
    console.log(periodType);
321
    console.log(basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : null)
322
    console.log(basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : null)
323
    console.log(moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss'))
324
    console.log(moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss'));
325
326
    // disable submit button
327
    setSubmitButtonDisabled(true);
328
    // show spinner
329
    setSpinnerHidden(false);
330
    // hide export button
331
    setExportButtonHidden(true)
332
333
    // Reinitialize tables
334
    setDetailedDataTableData([]);
335
    
336
    let isResponseOK = false;
337
    fetch(APIBaseURL + '/reports/storestatistics?' +
338
      'storeid=' + selectedStore +
339
      '&periodtype=' + periodType +
340
      '&baseperiodstartdatetime=' + (basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : '') +
341
      '&baseperiodenddatetime=' + (basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : '') +
342
      '&reportingperiodstartdatetime=' + moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') +
343
      '&reportingperiodenddatetime=' + moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') + 
344
      '&language=' + language, {
345
      method: 'GET',
346
      headers: {
347
        "Content-type": "application/json",
348
        "User-UUID": getCookieValue('user_uuid'),
349
        "Token": getCookieValue('token')
350
      },
351
      body: null,
352
353
    }).then(response => {
354
      if (response.ok) {
355
        isResponseOK = true;
356
      };
357
      return response.json();
358
    }).then(json => {
359
      if (isResponseOK) {
360
        console.log(json)
361
362
        let cardSummaryArray = []
363
        json['reporting_period']['names'].forEach((currentValue, index) => {
364
          let cardSummaryItem = {}
365
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
366
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
367
          cardSummaryItem['mean'] = json['reporting_period']['means'][index];
368
          cardSummaryItem['mean_increment_rate'] = parseFloat(json['reporting_period']['means_increment_rate'][index] * 100).toFixed(2) + "%";
369
          cardSummaryItem['mean_per_unit_area'] = json['reporting_period']['means_per_unit_area'][index];
370
          cardSummaryItem['median'] = json['reporting_period']['medians'][index];
371
          cardSummaryItem['median_increment_rate'] = parseFloat(json['reporting_period']['medians_increment_rate'][index] * 100).toFixed(2) + "%";
372
          cardSummaryItem['median_per_unit_area'] = json['reporting_period']['medians_per_unit_area'][index];
373
          cardSummaryItem['minimum'] = json['reporting_period']['minimums'][index];
374
          cardSummaryItem['minimum_increment_rate'] = parseFloat(json['reporting_period']['minimums_increment_rate'][index] * 100).toFixed(2) + "%";
375
          cardSummaryItem['minimum_per_unit_area'] = json['reporting_period']['minimums_per_unit_area'][index];
376
          cardSummaryItem['maximum'] = json['reporting_period']['maximums'][index];
377
          cardSummaryItem['maximum_increment_rate'] = parseFloat(json['reporting_period']['maximums_increment_rate'][index] * 100).toFixed(2) + "%";
378
          cardSummaryItem['maximum_per_unit_area'] = json['reporting_period']['maximums_per_unit_area'][index];
379
          cardSummaryItem['stdev'] = json['reporting_period']['stdevs'][index];
380
          cardSummaryItem['stdev_increment_rate'] = parseFloat(json['reporting_period']['stdevs_increment_rate'][index] * 100).toFixed(2) + "%";
381
          cardSummaryItem['stdev_per_unit_area'] = json['reporting_period']['stdevs_per_unit_area'][index];
382
          cardSummaryItem['variance'] = json['reporting_period']['variances'][index];
383
          cardSummaryItem['variance_increment_rate'] = parseFloat(json['reporting_period']['variances_increment_rate'][index] * 100).toFixed(2) + "%";
384
          cardSummaryItem['variance_per_unit_area'] = json['reporting_period']['variances_per_unit_area'][index];          
385
          cardSummaryArray.push(cardSummaryItem);
386
        });
387
        setCardSummaryList(cardSummaryArray);
388
389
        let base_timestamps = {}
390
        json['base_period']['timestamps'].forEach((currentValue, index) => {
391
          base_timestamps['a' + index] = currentValue;
392
        });
393
        setStoreBaseLabels(base_timestamps)
394
395
        let base_values = {}
396
        json['base_period']['values'].forEach((currentValue, index) => {
397
          base_values['a' + index] = currentValue;
398
        });
399
        setStoreBaseData(base_values)
400
401
        /*
402
        * Tip:
403
        *     base_names === reporting_names
404
        *     base_units === reporting_units
405
        * */
406
407
        let base_and_reporting_names = {}
408
        json['reporting_period']['names'].forEach((currentValue, index) => {
409
          base_and_reporting_names['a' + index] = currentValue;
410
        });
411
        setStoreBaseAndReportingNames(base_and_reporting_names)
412
413
        let base_and_reporting_units = {}
414
        json['reporting_period']['units'].forEach((currentValue, index) => {
415
          base_and_reporting_units['a' + index] = "("+currentValue+")";
416
        });
417
        setStoreBaseAndReportingUnits(base_and_reporting_units)
418
419
        let base_subtotals = {}
420
        json['base_period']['subtotals'].forEach((currentValue, index) => {
421
          base_subtotals['a' + index] = currentValue.toFixed(2);
422
        });
423
        setStoreBaseSubtotals(base_subtotals)
424
425
        let reporting_timestamps = {}
426
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
427
          reporting_timestamps['a' + index] = currentValue;
428
        });
429
        setStoreReportingLabels(reporting_timestamps);
430
431
        let reporting_values = {}
432
        json['reporting_period']['values'].forEach((currentValue, index) => {
433
          reporting_values['a' + index] = currentValue;
434
        });
435
        setStoreReportingData(reporting_values);
436
437
        let reporting_subtotals = {}
438
        json['reporting_period']['subtotals'].forEach((currentValue, index) => {
439
          reporting_subtotals['a' + index] = currentValue.toFixed(2);
440
        });
441
        setStoreReportingSubtotals(reporting_subtotals);
442
443
        let rates = {}
444
        json['reporting_period']['rates'].forEach((currentValue, index) => {
445
          let currentRate = Array();
446
          currentValue.forEach((rate) => {
447
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
448
          });
449
          rates['a' + index] = currentRate;
450
        });
451
        setStoreReportingRates(rates)
452
453
        let options = Array();
454
        json['reporting_period']['names'].forEach((currentValue, index) => {
455
          let unit = json['reporting_period']['units'][index];
456
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
457
        });
458
        setStoreReportingOptions(options);
459
460
        let timestamps = {}
461
        json['parameters']['timestamps'].forEach((currentValue, index) => {
462
          timestamps['a' + index] = currentValue;
463
        });
464
        setParameterLineChartLabels(timestamps);
465
466
        let values = {}
467
        json['parameters']['values'].forEach((currentValue, index) => {
468
          values['a' + index] = currentValue;
469
        });
470
        setParameterLineChartData(values);
471
      
472
        let names = Array();
473
        json['parameters']['names'].forEach((currentValue, index) => {
474
          
475
          names.push({ 'value': 'a' + index, 'label': currentValue });
476
        });
477
        setParameterLineChartOptions(names);
478
479
        if(!isBasePeriodTimestampExists(json['base_period'])) {
480
          let detailed_value_list = [];
481
          if (json['reporting_period']['timestamps'].length > 0) {
482
            json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
483
              let detailed_value = {};
484
              detailed_value['id'] = timestampIndex;
485
              detailed_value['startdatetime'] = currentTimestamp;
486
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
487
                detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values'][energyCategoryIndex][timestampIndex];
488
              });
489
              detailed_value_list.push(detailed_value);
490
            });
491
          }
492
          ;
493
494
          let detailed_value = {};
495
          detailed_value['id'] = detailed_value_list.length;
496
          detailed_value['startdatetime'] = t('Subtotal');
497
          json['reporting_period']['subtotals'].forEach((currentValue, index) => {
498
            detailed_value['a' + index] = currentValue;
499
          });
500
          detailed_value_list.push(detailed_value);
501
          setTimeout(() => {
502
            setDetailedDataTableData(detailed_value_list);
503
          }, 0)
504
505
          let detailed_column_list = [];
506
          detailed_column_list.push({
507
            dataField: 'startdatetime',
508
            text: t('Datetime'),
509
            sort: true
510
          });
511
          json['reporting_period']['names'].forEach((currentValue, index) => {
512
            let unit = json['reporting_period']['units'][index];
513
            detailed_column_list.push({
514
              dataField: 'a' + index,
515
              text: currentValue + ' (' + unit + ')',
516
              sort: true,
517
              formatter: function (decimalValue) {
518
                if (typeof decimalValue === 'number') {
519
                  return decimalValue.toFixed(2);
520
                } else {
521
                  return null;
522
                }
523
              }
524
            });
525
          });
526
          setDetailedDataTableColumns(detailed_column_list);
527
        }else {
528
          /*
529
          * Tip:
530
          *     json['base_period']['names'] ===  json['reporting_period']['names']
531
          *     json['base_period']['units'] ===  json['reporting_period']['units']
532
          * */
533
          let detailed_column_list = [];
534
          detailed_column_list.push({
535
            dataField: 'basePeriodDatetime',
536
            text: t('Base Period') + ' - ' + t('Datetime'),
537
            sort: true
538
          })
539
540
          json['base_period']['names'].forEach((currentValue, index) => {
541
            let unit = json['base_period']['units'][index];
542
            detailed_column_list.push({
543
              dataField: 'a' + index,
544
              text: t('Base Period') + ' - ' + currentValue + ' (' + unit + ')',
545
              sort: true,
546
              formatter: function (decimalValue) {
547
                if (typeof decimalValue === 'number') {
548
                  return decimalValue.toFixed(2);
549
                } else {
550
                  return null;
551
                }
552
              }
553
            })
554
          });
555
556
          detailed_column_list.push({
557
            dataField: 'reportingPeriodDatetime',
558
            text: t('Reporting Period') + ' - ' + t('Datetime'),
559
            sort: true
560
          })
561
562
          json['reporting_period']['names'].forEach((currentValue, index) => {
563
            let unit = json['reporting_period']['units'][index];
564
            detailed_column_list.push({
565
              dataField: 'b' + index,
566
              text: t('Reporting Period') + ' - ' + currentValue + ' (' + unit + ')',
567
              sort: true,
568
              formatter: function (decimalValue) {
569
                if (typeof decimalValue === 'number') {
570
                  return decimalValue.toFixed(2);
571
                } else {
572
                  return null;
573
                }
574
              }
575
            })
576
          });
577
          setDetailedDataTableColumns(detailed_column_list);
578
579
          let detailed_value_list = [];
580
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
581
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
582
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
583
            for (let index = 0; index < max_timestamps_length; index++) {
584
              let detailed_value = {};
585
              detailed_value['id'] = index;
586
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
587
              json['base_period']['values'].forEach((currentValue, energyCategoryIndex) => {
588
                detailed_value['a' + energyCategoryIndex] = index < json['base_period']['values'][energyCategoryIndex].length? json['base_period']['values'][energyCategoryIndex][index] : null;
589
              });
590
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
591
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
592
                detailed_value['b' + energyCategoryIndex] = index < json['reporting_period']['values'][energyCategoryIndex].length? json['reporting_period']['values'][energyCategoryIndex][index] : null;
593
              });
594
              detailed_value_list.push(detailed_value);
595
            }
596
597
            let detailed_value = {};
598
            detailed_value['id'] = detailed_value_list.length;
599
            detailed_value['basePeriodDatetime'] = t('Subtotal');
600
            json['base_period']['subtotals'].forEach((currentValue, index) => {
601
              detailed_value['a' + index] = currentValue;
602
            });
603
            detailed_value['reportingPeriodDatetime'] = t('Subtotal');
604
            json['reporting_period']['subtotals'].forEach((currentValue, index) => {
605
              detailed_value['b' + index] = currentValue;
606
            });
607
            detailed_value_list.push(detailed_value);
608
            setTimeout( () => {
609
              setDetailedDataTableData(detailed_value_list);
610
            }, 0)
611
          }
612
        }
613
        
614
        setExcelBytesBase64(json['excel_bytes_base64']);
615
616
        // enable submit button
617
        setSubmitButtonDisabled(false);
618
        // hide spinner
619
        setSpinnerHidden(true);
620
        // show export button
621
        setExportButtonHidden(false)
622
623
      } else {
624
        toast.error(t(json.description))
625
      }
626
    }).catch(err => {
627
      console.log(err);
628
    });
629
  };
630
631
  const handleExport = e => {
632
    e.preventDefault();
633
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
634
    const fileName = 'storestatistics.xlsx'
635
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
636
    fetch(fileUrl)
637
        .then(response => response.blob())
638
        .then(blob => {
639
            var link = window.document.createElement("a");
640
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
641
            link.download = fileName;
642
            document.body.appendChild(link);
643
            link.click();
644
            document.body.removeChild(link);
645
        });
646
  };
647
  
648
649
650
  return (
651
    <Fragment>
652
      <div>
653
        <Breadcrumb>
654
          <BreadcrumbItem>{t('Store Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Statistics')}</BreadcrumbItem>
655
        </Breadcrumb>
656
      </div>
657
      <Card className="bg-light mb-3">
658
        <CardBody className="p-3">
659
          <Form onSubmit={handleSubmit}>
660
            <Row form>
661
              <Col xs={6} sm={3}>
662
                <FormGroup className="form-group">
663
                  <Label className={labelClasses} for="space">
664
                    {t('Space')}
665
                  </Label>
666
                  <br />
667
                  <Cascader options={cascaderOptions}
668
                    onChange={onSpaceCascaderChange}
669
                    changeOnSelect
670
                    expandTrigger="hover">
671
                    <Input value={selectedSpaceName || ''} readOnly />
672
                  </Cascader>
673
                </FormGroup>
674
              </Col>
675
              <Col xs="auto">
676
                <FormGroup>
677
                  <Label className={labelClasses} for="storeSelect">
678
                    {t('Store')}
679
                  </Label>
680
                  <CustomInput type="select" id="storeSelect" name="storeSelect" onChange={({ target }) => setSelectedStore(target.value)}
681
                  >
682
                    {storeList.map((store, index) => (
683
                      <option value={store.value} key={store.value}>
684
                        {store.label}
685
                      </option>
686
                    ))}
687
                  </CustomInput>
688
                </FormGroup>
689
              </Col>
690
              <Col xs="auto">
691
                <FormGroup>
692
                  <Label className={labelClasses} for="comparisonType">
693
                    {t('Comparison Types')}
694
                  </Label>
695
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
696
                    defaultValue="month-on-month"
697
                    onChange={onComparisonTypeChange}
698
                  >
699
                    {comparisonTypeOptions.map((comparisonType, index) => (
700
                      <option value={comparisonType.value} key={comparisonType.value} >
701
                        {t(comparisonType.label)}
702
                      </option>
703
                    ))}
704
                  </CustomInput>
705
                </FormGroup>
706
              </Col>
707
              <Col xs="auto">
708
                <FormGroup>
709
                  <Label className={labelClasses} for="periodType">
710
                    {t('Period Types')}
711
                  </Label>
712
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
713
                  >
714
                    {periodTypeOptions.map((periodType, index) => (
715
                      <option value={periodType.value} key={periodType.value} >
716
                        {t(periodType.label)}
717
                      </option>
718
                    ))}
719
                  </CustomInput>
720
                </FormGroup>
721
              </Col>
722
              <Col xs={6} sm={3}>
723
                <FormGroup className="form-group">
724
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
725
                  <DateRangePickerWrapper 
726
                    id='basePeriodDateRangePicker'
727
                    disabled={basePeriodDateRangePickerDisabled}
728
                    format="yyyy-MM-dd HH:mm:ss"
729
                    value={basePeriodDateRange}
730
                    onChange={onBasePeriodChange}
731
                    size="md"
732
                    style={dateRangePickerStyle}
733
                    onClean={onBasePeriodClean}
734
                    locale={dateRangePickerLocale}
735
                    placeholder={t("Select Date Range")}
736
                   />
737
                </FormGroup>
738
              </Col>
739
              <Col xs={6} sm={3}>
740
                <FormGroup className="form-group">
741
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
742
                  <br/>
743
                  <DateRangePickerWrapper
744
                    id='reportingPeriodDateRangePicker'
745
                    format="yyyy-MM-dd HH:mm:ss"
746
                    value={reportingPeriodDateRange}
747
                    onChange={onReportingPeriodChange}
748
                    size="md"
749
                    style={dateRangePickerStyle}
750
                    onClean={onReportingPeriodClean}
751
                    locale={dateRangePickerLocale}
752
                    placeholder={t("Select Date Range")}
753
                  />
754
                </FormGroup>
755
              </Col>
756
              <Col xs="auto">
757
                <FormGroup>
758
                  <br></br>
759
                  <ButtonGroup id="submit">
760
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
761
                  </ButtonGroup>
762
                </FormGroup>
763
              </Col>
764
              <Col xs="auto">
765
                <FormGroup>
766
                  <br></br>
767
                  <Spinner color="primary" hidden={spinnerHidden}  />
768
                </FormGroup>
769
              </Col>
770
              <Col xs="auto">
771
                  <br></br>
772
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
773
                  hidden={exportButtonHidden}
774
                  onClick={handleExport} >
775
                    {t('Export')}
776
                  </ButtonIcon>
777
              </Col>
778
            </Row>
779
          </Form>
780
        </CardBody>
781
      </Card>
782
      {cardSummaryList.map(cardSummaryItem => (
783
        <div className="card-deck" key={cardSummaryItem['name']}>
784
          <CardSummary key={cardSummaryItem['name'] + 'mean'}
785
            rate={cardSummaryItem['mean_increment_rate']}
786
            title={t('Reporting Period CATEGORY Mean UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
787
            color="success" 
788
            footnote={t('Per Unit Area')} 
789
            footvalue={cardSummaryItem['mean_per_unit_area']}
790
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
791
            {cardSummaryItem['mean'] && <CountUp end={cardSummaryItem['mean']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
792
          </CardSummary>
793
          <CardSummary key={cardSummaryItem['name'] + 'median'}
794
            rate={cardSummaryItem['median_increment_rate']}
795
            title={t('Reporting Period CATEGORY Median UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
796
            color="success" 
797
            footnote={t('Per Unit Area')} 
798
            footvalue={cardSummaryItem['median_per_unit_area']}
799
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
800
            {cardSummaryItem['median'] && <CountUp end={cardSummaryItem['median']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
801
          </CardSummary>
802
          <CardSummary key={cardSummaryItem['name'] + 'minimum'}
803
            rate={cardSummaryItem['minimum_increment_rate']}
804
            title={t('Reporting Period CATEGORY Minimum UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
805
            color="success" 
806
            footnote={t('Per Unit Area')} 
807
            footvalue={cardSummaryItem['minimum_per_unit_area']}
808
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
809
            {cardSummaryItem['minimum'] && <CountUp end={cardSummaryItem['minimum']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
810
          </CardSummary>
811
          <CardSummary key={cardSummaryItem['name'] + 'maximum'}
812
            rate={cardSummaryItem['maximum_increment_rate']}
813
            title={t('Reporting Period CATEGORY Maximum UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
814
            color="success" 
815
            footnote={t('Per Unit Area')} 
816
            footvalue={cardSummaryItem['maximum_per_unit_area']}
817
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
818
            {cardSummaryItem['maximum'] && <CountUp end={cardSummaryItem['maximum']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
819
          </CardSummary>
820
          <CardSummary key={cardSummaryItem['name'] + 'stdev'}
821
            rate={cardSummaryItem['stdev_increment_rate']}
822
            title={t('Reporting Period CATEGORY Stdev UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
823
            color="success" 
824
            footnote={t('Per Unit Area')} 
825
            footvalue={cardSummaryItem['stdev_per_unit_area']}
826
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
827
            {cardSummaryItem['stdev'] && <CountUp end={cardSummaryItem['stdev']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
828
          </CardSummary>
829
          <CardSummary key={cardSummaryItem['name'] + 'variance'}
830
            rate={cardSummaryItem['variance_increment_rate']}
831
            title={t('Reporting Period CATEGORY Variance UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
832
            color="success"
833
            footnote={t('Per Unit Area')} 
834
            footvalue={cardSummaryItem['variance_per_unit_area']}
835
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
836
            {cardSummaryItem['variance'] && <CountUp end={cardSummaryItem['variance']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
837
          </CardSummary>
838
        </div>
839
      ))}
840
841
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": storeBaseAndReportingNames, "VALUE": storeReportingSubtotals, "UNIT": storeBaseAndReportingUnits}}
842
        baseTitle = {{"name": "Base Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": storeBaseAndReportingNames, "VALUE": storeBaseSubtotals, "UNIT": storeBaseAndReportingUnits}}
843
        reportingTooltipTitle = {{"name": "Reporting Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": storeBaseAndReportingNames, "VALUE": null, "UNIT": storeBaseAndReportingUnits}}
844
        baseTooltipTitle = {{"name": "Base Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": storeBaseAndReportingNames, "VALUE": null, "UNIT": storeBaseAndReportingUnits}}
845
        reportingLabels={storeReportingLabels}
846
        reportingData={storeReportingData}
847
        baseLabels={storeBaseLabels}
848
        baseData={storeBaseData}
849
        rates={storeReportingRates}
850
        options={storeReportingOptions}>
851
      </MultiTrendChart>
852
853
      <MultipleLineChart reportingTitle={t('Related Parameters')}
854
        baseTitle=''
855
        labels={parameterLineChartLabels}
856
        data={parameterLineChartData}
857
        options={parameterLineChartOptions}>
858
      </MultipleLineChart>
859
      <br />
860
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
861
      </DetailedDataTable>
862
863
    </Fragment>
864
  );
865
};
866
867
export default withTranslation()(withRedirect(StoreStatistics));
868