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

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

Complexity

Total Complexity 46
Complexity/F 0

Size

Lines of Code 896
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 46
eloc 758
dl 0
loc 896
rs 8.562
c 0
b 0
f 0
mnd 46
bc 46
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

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