Passed
Push — master ( 414b30...be43ee )
by Guangyu
14:19 queued 13s
created

myems-web/src/components/MyEMS/CombinedEquipment/CombinedEquipmentStatistics.js   B

Complexity

Total Complexity 43
Complexity/F 0

Size

Lines of Code 893
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 43
eloc 758
dl 0
loc 893
rs 8.802
c 0
b 0
f 0
mnd 43
bc 43
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/CombinedEquipment/CombinedEquipmentStatistics.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
const AssociatedEquipmentTable = loadable(() => import('../common/AssociatedEquipmentTable'));
39
40
const CombinedEquipmentStatistics = ({ setRedirect, setRedirectUrl, t }) => {
41
  let current_moment = moment();
42
  useEffect(() => {
43
    let is_logged_in = getCookieValue('is_logged_in');
44
    let user_name = getCookieValue('user_name');
45
    let user_display_name = getCookieValue('user_display_name');
46
    let user_uuid = getCookieValue('user_uuid');
47
    let token = getCookieValue('token');
48
    if (is_logged_in === null || !is_logged_in) {
49
      setRedirectUrl(`/authentication/basic/login`);
50
      setRedirect(true);
51
    } else {
52
      //update expires time of cookies
53
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
54
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
55
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
56
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
57
      createCookie('token', token, 1000 * 60 * 60 * 8);
58
    }
59
  });
60
61
62
  // State
63
  // Query Parameters
64
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
65
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
66
  const [combinedEquipmentList, setCombinedEquipmentList] = useState([]);
67
  const [selectedCombinedEquipment, setSelectedCombinedEquipment] = useState(undefined);
68
  const [comparisonType, setComparisonType] = useState('month-on-month');
69
  const [periodType, setPeriodType] = useState('daily');
70
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
71
  const [basePeriodDateRange, setBasePeriodDateRange] = useState([current_moment.clone().subtract(1, 'months').startOf('month').toDate(), current_moment.clone().subtract(1, 'months').toDate()]);
72
  const [basePeriodDateRangePickerDisabled, setBasePeriodDateRangePickerDisabled] = useState(true);
73
  const [reportingPeriodDateRange, setReportingPeriodDateRange] = useState([current_moment.clone().startOf('month').toDate(), current_moment.toDate()]);
74
  const dateRangePickerLocale = {
75
    sunday: t('sunday'),
76
    monday: t('monday'),
77
    tuesday: t('tuesday'),
78
    wednesday: t('wednesday'),
79
    thursday: t('thursday'),
80
    friday: t('friday'),
81
    saturday: t('saturday'),
82
    ok: t('ok'),
83
    today: t('today'),
84
    yesterday: t('yesterday'),
85
    hours: t('hours'),
86
    minutes: t('minutes'),
87
    seconds: t('seconds'),
88
    last7Days: t('last7Days'),
89
    formattedMonthPattern: 'yyyy-MM-dd'
90
  };
91
  const dateRangePickerStyle = { display: 'block', zIndex: 10};
92
  const { language } = useContext(AppContext);
93
94
  // buttons
95
  const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
96
  const [spinnerHidden, setSpinnerHidden] = useState(true);
97
  const [exportButtonHidden, setExportButtonHidden] = useState(true);
98
  
99
  //Results
100
  const [cardSummaryList, setCardSummaryList] = useState([]);
101
102
  const [combinedEquipmentBaseAndReportingNames, setCombinedEquipmentBaseAndReportingNames] = useState({"a0":""});
103
  const [combinedEquipmentBaseAndReportingUnits, setCombinedEquipmentBaseAndReportingUnits] = useState({"a0":"()"});
104
105
  const [combinedEquipmentBaseLabels, setCombinedEquipmentBaseLabels] = useState({"a0": []});
106
  const [combinedEquipmentBaseData, setCombinedEquipmentBaseData] = useState({"a0": []});
107
  const [combinedEquipmentBaseSubtotals, setCombinedEquipmentBaseSubtotals] = useState({"a0": (0).toFixed(2)});
108
109
  const [combinedEquipmentReportingLabels, setCombinedEquipmentReportingLabels] = useState({"a0": []});
110
  const [combinedEquipmentReportingData, setCombinedEquipmentReportingData] = useState({"a0": []});
111
  const [combinedEquipmentReportingSubtotals, setCombinedEquipmentReportingSubtotals] = useState({"a0": (0).toFixed(2)});
112
113
  const [combinedEquipmentReportingRates, setCombinedEquipmentReportingRates] = useState({"a0": []});
114
  const [combinedEquipmentReportingOptions, setCombinedEquipmentReportingOptions] = useState([]);
115
116
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
117
  const [parameterLineChartData, setParameterLineChartData] = useState({});
118
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
119
120
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
121
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
122
  
123
  const [associatedEquipmentTableData, setAssociatedEquipmentTableData] = useState([]);
124
  const [associatedEquipmentTableColumns, setAssociatedEquipmentTableColumns] = useState([{dataField: 'name', text: t('Associated Equipment'), sort: true }]);
125
  
126
  const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
127
  
128
  useEffect(() => {
129
    let isResponseOK = false;
130
    fetch(APIBaseURL + '/spaces/tree', {
131
      method: 'GET',
132
      headers: {
133
        "Content-type": "application/json",
134
        "User-UUID": getCookieValue('user_uuid'),
135
        "Token": getCookieValue('token')
136
      },
137
      body: null,
138
139
    }).then(response => {
140
      console.log(response);
141
      if (response.ok) {
142
        isResponseOK = true;
143
      }
144
      return response.json();
145
    }).then(json => {
146
      console.log(json);
147
      if (isResponseOK) {
148
        // rename keys 
149
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
150
        setCascaderOptions(json);
151
        setSelectedSpaceName([json[0]].map(o => o.label));
152
        setSelectedSpaceID([json[0]].map(o => o.value));
153
        // get Combined Equipments by root Space ID
154
        let isResponseOK = false;
155
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/combinedequipments', {
156
          method: 'GET',
157
          headers: {
158
            "Content-type": "application/json",
159
            "User-UUID": getCookieValue('user_uuid'),
160
            "Token": getCookieValue('token')
161
          },
162
          body: null,
163
164
        }).then(response => {
165
          if (response.ok) {
166
            isResponseOK = true;
167
          }
168
          return response.json();
169
        }).then(json => {
170
          if (isResponseOK) {
171
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
172
            console.log(json);
173
            setCombinedEquipmentList(json[0]);
174
            if (json[0].length > 0) {
175
              setSelectedCombinedEquipment(json[0][0].value);
176
              // enable submit button
177
              setSubmitButtonDisabled(false);
178
            } else {
179
              setSelectedCombinedEquipment(undefined);
180
              // disable submit button
181
              setSubmitButtonDisabled(true);
182
            }
183
          } else {
184
            toast.error(t(json.description))
185
          }
186
        }).catch(err => {
187
          console.log(err);
188
        });
189
        // end of get Combined Equipments by root Space ID
190
      } else {
191
        toast.error(t(json.description));
192
      }
193
    }).catch(err => {
194
      console.log(err);
195
    });
196
197
  }, []);
198
199
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
200
201
  let onSpaceCascaderChange = (value, selectedOptions) => {
202
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
203
    setSelectedSpaceID(value[value.length - 1]);
204
205
    let isResponseOK = false;
206
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/combinedequipments', {
207
      method: 'GET',
208
      headers: {
209
        "Content-type": "application/json",
210
        "User-UUID": getCookieValue('user_uuid'),
211
        "Token": getCookieValue('token')
212
      },
213
      body: null,
214
215
    }).then(response => {
216
      if (response.ok) {
217
        isResponseOK = true;
218
      }
219
      return response.json();
220
    }).then(json => {
221
      if (isResponseOK) {
222
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
223
        console.log(json)
224
        setCombinedEquipmentList(json[0]);
225
        if (json[0].length > 0) {
226
          setSelectedCombinedEquipment(json[0][0].value);
227
          // enable submit button
228
          setSubmitButtonDisabled(false);
229
        } else {
230
          setSelectedCombinedEquipment(undefined);
231
          // disable submit button
232
          setSubmitButtonDisabled(true);
233
        }
234
      } else {
235
        toast.error(t(json.description))
236
      }
237
    }).catch(err => {
238
      console.log(err);
239
    });
240
  }
241
242
243
  let onComparisonTypeChange = ({ target }) => {
244
    console.log(target.value);
245
    setComparisonType(target.value);
246
    if (target.value === 'year-over-year') {
247
      setBasePeriodDateRangePickerDisabled(true);
248
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'years').toDate(),
249
        moment(reportingPeriodDateRange[1]).subtract(1, 'years').toDate()]);
250
    } else if (target.value === 'month-on-month') {
251
      setBasePeriodDateRangePickerDisabled(true);
252
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'months').toDate(),
253
        moment(reportingPeriodDateRange[1]).subtract(1, 'months').toDate()]);
254
    } else if (target.value === 'free-comparison') {
255
      setBasePeriodDateRangePickerDisabled(false);
256
    } else if (target.value === 'none-comparison') {
257
      setBasePeriodDateRange([null, null]);
258
      setBasePeriodDateRangePickerDisabled(true);
259
    }
260
  };
261
262
  // Callback fired when value changed
263
  let onBasePeriodChange = (DateRange) => {
264
    if(DateRange == null) {
265
      setBasePeriodDateRange([null, null]);
266
    } else {
267
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
268
        // if the user did not change time value, set the default time to the end of day
269
        DateRange[1] = endOfDay(DateRange[1]);
270
      }
271
      setBasePeriodDateRange([DateRange[0], DateRange[1]]);
272
    }
273
  };
274
275
  // Callback fired when value changed
276
  let onReportingPeriodChange = (DateRange) => {
277
    if(DateRange == null) {
278
      setReportingPeriodDateRange([null, null]);
279
    } else {
280
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
281
        // if the user did not change time value, set the default time to the end of day
282
        DateRange[1] = endOfDay(DateRange[1]);
283
      }
284
      setReportingPeriodDateRange([DateRange[0], DateRange[1]]);
285
      if (comparisonType === 'year-over-year') {
286
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'years').toDate(), moment(DateRange[1]).clone().subtract(1, 'years').toDate()]);
287
      } else if (comparisonType === 'month-on-month') {
288
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'months').toDate(), moment(DateRange[1]).clone().subtract(1, 'months').toDate()]);
289
      }
290
    }
291
  };
292
293
  // Callback fired when value clean
294
  let onBasePeriodClean = event => {
295
    setBasePeriodDateRange([null, null]);
296
  };
297
298
  // Callback fired when value clean
299
  let onReportingPeriodClean = event => {
300
    setReportingPeriodDateRange([null, null]);
301
  };
302
303
  const isBasePeriodTimestampExists = (base_period_data) => {
304
    const timestamps = base_period_data['timestamps'];
305
306
    if (timestamps.length === 0) {
307
      return false;
308
    }
309
310
    for (let i = 0; i < timestamps.length; i++) {
311
      if (timestamps[i].length > 0) {
312
        return true;
313
      }
314
    }
315
    return false
316
  }
317
318
  // Handler
319
  const handleSubmit = e => {
320
    e.preventDefault();
321
    console.log('handleSubmit');
322
    console.log(selectedSpaceID);
323
    console.log(selectedCombinedEquipment);
324
    console.log(comparisonType);
325
    console.log(periodType);
326
    console.log(basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : null)
327
    console.log(basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : null)
328
    console.log(moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss'))
329
    console.log(moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss'));
330
331
    // disable submit button
332
    setSubmitButtonDisabled(true);
333
    // show spinner
334
    setSpinnerHidden(false);
335
    // hide export button
336
    setExportButtonHidden(true)
337
338
    // Reinitialize tables
339
    setDetailedDataTableData([]);
340
    setAssociatedEquipmentTableData([]);
341
    
342
    let isResponseOK = false;
343
    fetch(APIBaseURL + '/reports/combinedequipmentstatistics?' +
344
      'combinedequipmentid=' + selectedCombinedEquipment +
345
      '&periodtype=' + periodType +
346
      '&baseperiodstartdatetime=' + (basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : '') +
347
      '&baseperiodenddatetime=' + (basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : '') +
348
      '&reportingperiodstartdatetime=' + moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') +
349
      '&reportingperiodenddatetime=' + moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') +
350
      '&language=' + language, {
351
      method: 'GET',
352
      headers: {
353
        "Content-type": "application/json",
354
        "User-UUID": getCookieValue('user_uuid'),
355
        "Token": getCookieValue('token')
356
      },
357
      body: null,
358
359
    }).then(response => {
360
      if (response.ok) {
361
        isResponseOK = true;
362
      };
363
      return response.json();
364
    }).then(json => {
365
      if (isResponseOK) {
366
        console.log(json)
367
368
        let cardSummaryArray = []
369
        json['reporting_period']['names'].forEach((currentValue, index) => {
370
          let cardSummaryItem = {}
371
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
372
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
373
          cardSummaryItem['mean'] = json['reporting_period']['means'][index];
374
          cardSummaryItem['mean_increment_rate'] = parseFloat(json['reporting_period']['means_increment_rate'][index] * 100).toFixed(2) + "%";
375
          cardSummaryItem['median'] = json['reporting_period']['medians'][index];
376
          cardSummaryItem['median_increment_rate'] = parseFloat(json['reporting_period']['medians_increment_rate'][index] * 100).toFixed(2) + "%";
377
          cardSummaryItem['minimum'] = json['reporting_period']['minimums'][index];
378
          cardSummaryItem['minimum_increment_rate'] = parseFloat(json['reporting_period']['minimums_increment_rate'][index] * 100).toFixed(2) + "%";
379
          cardSummaryItem['maximum'] = json['reporting_period']['maximums'][index];
380
          cardSummaryItem['maximum_increment_rate'] = parseFloat(json['reporting_period']['maximums_increment_rate'][index] * 100).toFixed(2) + "%";
381
          cardSummaryItem['stdev'] = json['reporting_period']['stdevs'][index];
382
          cardSummaryItem['stdev_increment_rate'] = parseFloat(json['reporting_period']['stdevs_increment_rate'][index] * 100).toFixed(2) + "%";
383
          cardSummaryItem['variance'] = json['reporting_period']['variances'][index];
384
          cardSummaryItem['variance_increment_rate'] = parseFloat(json['reporting_period']['variances_increment_rate'][index] * 100).toFixed(2) + "%";
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
        setCombinedEquipmentBaseLabels(base_timestamps)
394
395
        let base_values = {}
396
        json['base_period']['values'].forEach((currentValue, index) => {
397
          base_values['a' + index] = currentValue;
398
        });
399
        setCombinedEquipmentBaseData(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
        setCombinedEquipmentBaseAndReportingNames(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
        setCombinedEquipmentBaseAndReportingUnits(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
        setCombinedEquipmentBaseSubtotals(base_subtotals)
424
425
        let reporting_timestamps = {}
426
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
427
          reporting_timestamps['a' + index] = currentValue;
428
        });
429
        setCombinedEquipmentReportingLabels(reporting_timestamps);
430
431
        let reporting_values = {}
432
        json['reporting_period']['values'].forEach((currentValue, index) => {
433
          reporting_values['a' + index] = currentValue;
434
        });
435
        setCombinedEquipmentReportingData(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
        setCombinedEquipmentReportingSubtotals(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
        setCombinedEquipmentReportingRates(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
        setCombinedEquipmentReportingOptions(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
        let associated_equipment_value_list = [];
615
        if (json['associated_equipment']['associated_equipment_names_array'].length > 0) {
616
          json['associated_equipment']['associated_equipment_names_array'][0].forEach((currentEquipmentName, equipmentIndex) => {
617
            let associated_equipment_value = {};
618
            associated_equipment_value['id'] = equipmentIndex;
619
            associated_equipment_value['name'] = currentEquipmentName;
620
            json['associated_equipment']['energy_category_names'].forEach((currentValue, energyCategoryIndex) => {
621
              associated_equipment_value['a' + energyCategoryIndex] = json['associated_equipment']['subtotals_array'][energyCategoryIndex][equipmentIndex];
622
            });
623
            associated_equipment_value_list.push(associated_equipment_value);
624
          });
625
        };
626
627
        setAssociatedEquipmentTableData(associated_equipment_value_list);
628
629
        let associated_equipment_column_list = [];
630
        associated_equipment_column_list.push({
631
          dataField: 'name',
632
          text: t('Associated Equipment'),
633
          sort: true
634
        });
635
        json['associated_equipment']['energy_category_names'].forEach((currentValue, index) => {
636
          let unit = json['associated_equipment']['units'][index];
637
          associated_equipment_column_list.push({
638
            dataField: 'a' + index,
639
            text: currentValue + ' (' + unit + ')',
640
            sort: true,
641
            formatter: function (decimalValue) {
642
              if (typeof decimalValue === 'number') {
643
                return decimalValue.toFixed(2);
644
              } else {
645
                return null;
646
              }
647
            }
648
          });
649
        });
650
651
        setAssociatedEquipmentTableColumns(associated_equipment_column_list);
652
        
653
        setExcelBytesBase64(json['excel_bytes_base64']);
654
655
        // enable submit button
656
        setSubmitButtonDisabled(false);
657
        // hide spinner
658
        setSpinnerHidden(true);
659
        // show export button
660
        setExportButtonHidden(false);
661
          
662
      } else {
663
        toast.error(t(json.description))
664
      }
665
    }).catch(err => {
666
      console.log(err);
667
    });
668
  };
669
  
670
  const handleExport = e => {
671
    e.preventDefault();
672
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
673
    const fileName = 'combinedequipmentstatistics.xlsx'
674
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
675
    fetch(fileUrl)
676
        .then(response => response.blob())
677
        .then(blob => {
678
            var link = window.document.createElement("a");
679
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
680
            link.download = fileName;
681
            document.body.appendChild(link);
682
            link.click();
683
            document.body.removeChild(link);
684
        });
685
  };
686
  
687
688
689
  return (
690
    <Fragment>
691
      <div>
692
        <Breadcrumb>
693
          <BreadcrumbItem>{t('Combined Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Statistics')}</BreadcrumbItem>
694
        </Breadcrumb>
695
      </div>
696
      <Card className="bg-light mb-3">
697
        <CardBody className="p-3">
698
          <Form onSubmit={handleSubmit}>
699
            <Row form>
700
              <Col xs={6} sm={3}>
701
                <FormGroup className="form-group">
702
                  <Label className={labelClasses} for="space">
703
                    {t('Space')}
704
                  </Label>
705
                  <br />
706
                  <Cascader options={cascaderOptions}
707
                    onChange={onSpaceCascaderChange}
708
                    changeOnSelect
709
                    expandTrigger="hover">
710
                    <Input value={selectedSpaceName || ''} readOnly />
711
                  </Cascader>
712
                </FormGroup>
713
              </Col>
714
              <Col xs="auto">
715
                <FormGroup>
716
                  <Label className={labelClasses} for="combinedEquipmentSelect">
717
                    {t('Combined Equipment')}
718
                  </Label>
719
                  <CustomInput type="select" id="combinedEquipmentSelect" name="combinedEquipmentSelect" onChange={({ target }) => setSelectedCombinedEquipment(target.value)}
720
                  >
721
                    {combinedEquipmentList.map((combinedEquipment, index) => (
722
                      <option value={combinedEquipment.value} key={combinedEquipment.value}>
723
                        {combinedEquipment.label}
724
                      </option>
725
                    ))}
726
                  </CustomInput>
727
                </FormGroup>
728
              </Col>
729
              <Col xs="auto">
730
                <FormGroup>
731
                  <Label className={labelClasses} for="comparisonType">
732
                    {t('Comparison Types')}
733
                  </Label>
734
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
735
                    defaultValue="month-on-month"
736
                    onChange={onComparisonTypeChange}
737
                  >
738
                    {comparisonTypeOptions.map((comparisonType, index) => (
739
                      <option value={comparisonType.value} key={comparisonType.value} >
740
                        {t(comparisonType.label)}
741
                      </option>
742
                    ))}
743
                  </CustomInput>
744
                </FormGroup>
745
              </Col>
746
              <Col xs="auto">
747
                <FormGroup>
748
                  <Label className={labelClasses} for="periodType">
749
                    {t('Period Types')}
750
                  </Label>
751
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
752
                  >
753
                    {periodTypeOptions.map((periodType, index) => (
754
                      <option value={periodType.value} key={periodType.value} >
755
                        {t(periodType.label)}
756
                      </option>
757
                    ))}
758
                  </CustomInput>
759
                </FormGroup>
760
              </Col>
761
              <Col xs={6} sm={3}>
762
                <FormGroup className="form-group">
763
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
764
                  <DateRangePickerWrapper 
765
                    id='basePeriodDateRangePicker'
766
                    disabled={basePeriodDateRangePickerDisabled}
767
                    format="yyyy-MM-dd HH:mm:ss"
768
                    value={basePeriodDateRange}
769
                    onChange={onBasePeriodChange}
770
                    size="md"
771
                    style={dateRangePickerStyle}
772
                    onClean={onBasePeriodClean}
773
                    locale={dateRangePickerLocale}
774
                    placeholder={t("Select Date Range")}
775
                   />
776
                </FormGroup>
777
              </Col>
778
              <Col xs={6} sm={3}>
779
                <FormGroup className="form-group">
780
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
781
                  <br/>
782
                  <DateRangePickerWrapper
783
                    id='reportingPeriodDateRangePicker'
784
                    format="yyyy-MM-dd HH:mm:ss"
785
                    value={reportingPeriodDateRange}
786
                    onChange={onReportingPeriodChange}
787
                    size="md"
788
                    style={dateRangePickerStyle}
789
                    onClean={onReportingPeriodClean}
790
                    locale={dateRangePickerLocale}
791
                    placeholder={t("Select Date Range")}
792
                  />
793
                </FormGroup>
794
              </Col>
795
              <Col xs="auto">
796
                <FormGroup>
797
                  <br></br>
798
                  <ButtonGroup id="submit">
799
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
800
                  </ButtonGroup>
801
                </FormGroup>
802
              </Col>
803
              <Col xs="auto">
804
                <FormGroup>
805
                  <br></br>
806
                  <Spinner color="primary" hidden={spinnerHidden}  />
807
                </FormGroup>
808
              </Col>
809
              <Col xs="auto">
810
                  <br></br>
811
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
812
                  hidden={exportButtonHidden}
813
                  onClick={handleExport} >
814
                    {t('Export')}
815
                  </ButtonIcon>
816
              </Col>
817
            </Row>
818
          </Form>
819
        </CardBody>
820
      </Card>
821
      {cardSummaryList.map(cardSummaryItem => (
822
        <div className="card-deck" key={cardSummaryItem['name']}>
823
          <CardSummary key={cardSummaryItem['name'] + 'mean'}
824
            rate={cardSummaryItem['mean_increment_rate']}
825
            title={t('Reporting Period CATEGORY Mean UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
826
            color="success" >
827
            {cardSummaryItem['mean'] && <CountUp end={cardSummaryItem['mean']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
828
          </CardSummary>
829
          <CardSummary key={cardSummaryItem['name'] + 'median'}
830
            rate={cardSummaryItem['median_increment_rate']}
831
            title={t('Reporting Period CATEGORY Median UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
832
            color="success" >
833
            {cardSummaryItem['median'] && <CountUp end={cardSummaryItem['median']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
834
          </CardSummary>
835
          <CardSummary key={cardSummaryItem['name'] + 'minimum'}
836
            rate={cardSummaryItem['minimum_increment_rate']}
837
            title={t('Reporting Period CATEGORY Minimum UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
838
            color="success" >
839
            {cardSummaryItem['minimum'] && <CountUp end={cardSummaryItem['minimum']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
840
          </CardSummary>
841
          <CardSummary key={cardSummaryItem['name'] + 'maximum'}
842
            rate={cardSummaryItem['maximum_increment_rate']}
843
            title={t('Reporting Period CATEGORY Maximum UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
844
            color="success" >
845
            {cardSummaryItem['maximum'] && <CountUp end={cardSummaryItem['maximum']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
846
          </CardSummary>
847
          <CardSummary key={cardSummaryItem['name'] + 'stdev'}
848
            rate={cardSummaryItem['stdev_increment_rate']}
849
            title={t('Reporting Period CATEGORY Stdev UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
850
            color="success" >
851
            {cardSummaryItem['stdev'] && <CountUp end={cardSummaryItem['stdev']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
852
          </CardSummary>
853
          <CardSummary key={cardSummaryItem['name'] + 'variance'}
854
            rate={cardSummaryItem['variance_increment_rate']}
855
            title={t('Reporting Period CATEGORY Variance UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
856
            color="success" >
857
            {cardSummaryItem['variance'] && <CountUp end={cardSummaryItem['variance']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
858
          </CardSummary>
859
        </div>
860
      ))}
861
862
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "VALUE": combinedEquipmentReportingSubtotals, "UNIT": combinedEquipmentBaseAndReportingUnits}}
863
        baseTitle = {{"name": "Base Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "VALUE": combinedEquipmentBaseSubtotals, "UNIT": combinedEquipmentBaseAndReportingUnits}}
864
        reportingTooltipTitle = {{"name": "Reporting Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "VALUE": null, "UNIT": combinedEquipmentBaseAndReportingUnits}}
865
        baseTooltipTitle = {{"name": "Base Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "VALUE": null, "UNIT": combinedEquipmentBaseAndReportingUnits}}
866
        reportingLabels={combinedEquipmentReportingLabels}
867
        reportingData={combinedEquipmentReportingData}
868
        baseLabels={combinedEquipmentBaseLabels}
869
        baseData={combinedEquipmentBaseData}
870
        rates={combinedEquipmentReportingRates}
871
        options={combinedEquipmentReportingOptions}>
872
      </MultiTrendChart>
873
874
875
      <MultipleLineChart reportingTitle={t('Related Parameters')}
876
        baseTitle=''
877
        labels={parameterLineChartLabels}
878
        data={parameterLineChartData}
879
        options={parameterLineChartOptions}>
880
      </MultipleLineChart>
881
      <br />
882
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
883
      </DetailedDataTable>
884
      <br />
885
      <AssociatedEquipmentTable data={associatedEquipmentTableData} title={t('Associated Equipment Data')} columns={associatedEquipmentTableColumns}>
886
      </AssociatedEquipmentTable>
887
888
    </Fragment>
889
  );
890
};
891
892
export default withTranslation()(withRedirect(CombinedEquipmentStatistics));
893