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

myems-web/src/components/MyEMS/CombinedEquipment/CombinedEquipmentLoad.js   C

Complexity

Total Complexity 53
Complexity/F 0

Size

Lines of Code 926
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 53
eloc 768
dl 0
loc 926
rs 6.792
c 0
b 0
f 0
mnd 53
bc 53
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/CombinedEquipment/CombinedEquipmentLoad.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 CombinedEquipmentLoad = ({ 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/combinedequipmentload?' +
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['average'] = json['reporting_period']['averages'][index];
374
          cardSummaryItem['average_increment_rate'] = parseFloat(json['reporting_period']['averages_increment_rate'][index] * 100).toFixed(2) + "%";
375
          cardSummaryItem['maximum'] = json['reporting_period']['maximums'][index];
376
          cardSummaryItem['maximum_increment_rate'] = parseFloat(json['reporting_period']['maximums_increment_rate'][index] * 100).toFixed(2) + "%";
377
          cardSummaryItem['factor'] = json['reporting_period']['factors'][index];
378
          cardSummaryItem['factor_increment_rate'] = parseFloat(json['reporting_period']['factors_increment_rate'][index] * 100).toFixed(2) + "%";
379
          cardSummaryArray.push(cardSummaryItem);
380
        });
381
        setCardSummaryList(cardSummaryArray);
382
383
        let base_timestamps = {}
384
        json['base_period']['timestamps'].forEach((currentValue, index) => {
385
          base_timestamps['a' + index] = currentValue;
386
        });
387
        setCombinedEquipmentBaseLabels(base_timestamps)
388
389
        let base_values = {}
390
        json['base_period']['sub_maximums'].forEach((currentValue, index) => {
391
          base_values['a' + index] = currentValue;
392
        });
393
        setCombinedEquipmentBaseData(base_values)
394
395
        /*
396
        * Tip:
397
        *     base_names === reporting_names
398
        *     base_units === reporting_units
399
        * */
400
401
        let base_and_reporting_names = {}
402
        json['reporting_period']['names'].forEach((currentValue, index) => {
403
          base_and_reporting_names['a' + index] = currentValue;
404
        });
405
        setCombinedEquipmentBaseAndReportingNames(base_and_reporting_names)
406
407
        let base_and_reporting_units = {}
408
        json['reporting_period']['units'].forEach((currentValue, index) => {
409
          base_and_reporting_units['a' + index] = "("+currentValue+"/H)";
410
        });
411
        setCombinedEquipmentBaseAndReportingUnits(base_and_reporting_units)
412
413
        // let base_subtotals = {}
414
        // json['base_period']['subtotals'].forEach((currentValue, index) => {
415
        //   base_subtotals['a' + index] = currentValue.toFixed(2);
416
        // });
417
        // setCombinedEquipmentBaseSubtotals(base_subtotals)
418
419
        let reporting_timestamps = {}
420
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
421
          reporting_timestamps['a' + index] = currentValue;
422
        });
423
        setCombinedEquipmentReportingLabels(reporting_timestamps);
424
425
        let reporting_values = {}
426
        json['reporting_period']['sub_maximums'].forEach((currentValue, index) => {
427
          reporting_values['a' + index] = currentValue;
428
        });
429
        setCombinedEquipmentReportingData(reporting_values);
430
431
        // let reporting_subtotals = {}
432
        // json['reporting_period']['subtotals'].forEach((currentValue, index) => {
433
        //   reporting_subtotals['a' + index] = currentValue.toFixed(2);
434
        // });
435
        // setCombinedEquipmentReportingSubtotals(reporting_subtotals);
436
437
        let rates = {}
438
        json['reporting_period']['rates_of_sub_maximums'].forEach((currentValue, index) => {
439
          let currentRate = Array();
440
          currentValue.forEach((rate) => {
441
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
442
          });
443
          rates['a' + index] = currentRate;
444
        });
445
        setCombinedEquipmentReportingRates(rates)
446
447
        let options = Array();
448
        json['reporting_period']['names'].forEach((currentValue, index) => {
449
          let unit = json['reporting_period']['units'][index];
450
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + '/H)'});
451
        });
452
        setCombinedEquipmentReportingOptions(options);
453
      
454
        let timestamps = {}
455
        json['parameters']['timestamps'].forEach((currentValue, index) => {
456
          timestamps['a' + index] = currentValue;
457
        });
458
        setParameterLineChartLabels(timestamps);
459
460
        let values = {}
461
        json['parameters']['values'].forEach((currentValue, index) => {
462
          values['a' + index] = currentValue;
463
        });
464
        setParameterLineChartData(values);
465
      
466
        let names = Array();
467
        json['parameters']['names'].forEach((currentValue, index) => {
468
          
469
          names.push({ 'value': 'a' + index, 'label': currentValue });
470
        });
471
        setParameterLineChartOptions(names);
472
473
        if(!isBasePeriodTimestampExists(json['base_period'])) {
474
          let detailed_value_list = [];
475
          if (json['reporting_period']['timestamps'].length > 0) {
476
            json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
477
              let detailed_value = {};
478
              detailed_value['id'] = timestampIndex;
479
              detailed_value['startdatetime'] = currentTimestamp;
480
              json['reporting_period']['sub_averages'].forEach((currentValue, energyCategoryIndex) => {
481
                if (json['reporting_period']['sub_averages'][energyCategoryIndex][timestampIndex] != null) {
482
                  detailed_value['a' + 2 * energyCategoryIndex] = json['reporting_period']['sub_averages'][energyCategoryIndex][timestampIndex];
483
                } else {
484
                  detailed_value['a' + 2 * energyCategoryIndex] = null;
485
                }
486
                ;
487
488
                if (json['reporting_period']['sub_maximums'][energyCategoryIndex][timestampIndex] != null) {
489
                  detailed_value['a' + (2 * energyCategoryIndex + 1)] = json['reporting_period']['sub_maximums'][energyCategoryIndex][timestampIndex];
490
                } else {
491
                  detailed_value['a' + (2 * energyCategoryIndex + 1)] = null;
492
                }
493
                ;
494
              });
495
              detailed_value_list.push(detailed_value);
496
            });
497
          }
498
          ;
499
500
          setTimeout(() => {
501
            setDetailedDataTableData(detailed_value_list);
502
          }, 0)
503
504
          let detailed_column_list = [];
505
          detailed_column_list.push({
506
            dataField: 'startdatetime',
507
            text: t('Datetime'),
508
            sort: true
509
          });
510
          json['reporting_period']['names'].forEach((currentValue, index) => {
511
            let unit = json['reporting_period']['units'][index];
512
            detailed_column_list.push({
513
              dataField: 'a' + 2 * index,
514
              text: currentValue + ' ' + t('Average Load') + ' (' + unit + '/H)',
515
              sort: true,
516
              formatter: function (decimalValue) {
517
                if (typeof decimalValue === 'number') {
518
                  return decimalValue.toFixed(2);
519
                } else {
520
                  return null;
521
                }
522
              }
523
            });
524
            detailed_column_list.push({
525
              dataField: 'a' + (2 * index + 1),
526
              text: currentValue + ' ' + t('Maximum Load') + ' (' + unit + '/H)',
527
              sort: true,
528
              formatter: function (decimalValue) {
529
                if (typeof decimalValue === 'number') {
530
                  return decimalValue.toFixed(2);
531
                } else {
532
                  return null;
533
                }
534
              }
535
            });
536
          });
537
          setDetailedDataTableColumns(detailed_column_list);
538
        }else {
539
          /*
540
          * Tip:
541
          *     json['base_period']['names'] ===  json['reporting_period']['names']
542
          *     json['base_period']['units'] ===  json['reporting_period']['units']
543
          * */
544
          let detailed_column_list = [];
545
          detailed_column_list.push({
546
            dataField: 'basePeriodDatetime',
547
            text: t('Base Period') + ' - ' + t('Datetime'),
548
            sort: true
549
          })
550
551
          json['base_period']['names'].forEach((currentValue, index) => {
552
            let unit = json['base_period']['units'][index];
553
            detailed_column_list.push({
554
              dataField: 'a' + 2 * index,
555
              text: t('Base Period') + ' - ' + currentValue + ' ' + t('Average Load') + ' (' + unit + '/H)',
556
              sort: true,
557
              formatter: function (decimalValue) {
558
                if (typeof decimalValue === 'number') {
559
                  return decimalValue.toFixed(2);
560
                } else {
561
                  return null;
562
                }
563
              }
564
            });
565
            detailed_column_list.push({
566
              dataField: 'a' + (2 * index + 1),
567
              text: t('Base Period') + ' - ' + currentValue + ' ' + t('Maximum Load') + ' (' + unit + '/H)',
568
              sort: true,
569
              formatter: function (decimalValue) {
570
                if (typeof decimalValue === 'number') {
571
                  return decimalValue.toFixed(2);
572
                } else {
573
                  return null;
574
                }
575
              }
576
            });
577
          });
578
579
          detailed_column_list.push({
580
            dataField: 'reportingPeriodDatetime',
581
            text: t('Reporting Period') + ' - ' + t('Datetime'),
582
            sort: true
583
          })
584
585
          json['reporting_period']['names'].forEach((currentValue, index) => {
586
            let unit = json['reporting_period']['units'][index];
587
            detailed_column_list.push({
588
              dataField: 'b' + 2 * index,
589
              text: t('Reporting Period') + ' - ' + currentValue + ' ' + t('Average Load') + ' (' + unit + '/H)',
590
              sort: true,
591
              formatter: function (decimalValue) {
592
                if (typeof decimalValue === 'number') {
593
                  return decimalValue.toFixed(2);
594
                } else {
595
                  return null;
596
                }
597
              }
598
            });
599
            detailed_column_list.push({
600
              dataField: 'b' + (2 * index + 1),
601
              text: t('Reporting Period') + ' - ' + currentValue + ' ' + t('Maximum Load') + ' (' + unit + '/H)',
602
              sort: true,
603
              formatter: function (decimalValue) {
604
                if (typeof decimalValue === 'number') {
605
                  return decimalValue.toFixed(2);
606
                } else {
607
                  return null;
608
                }
609
              }
610
            });
611
          });
612
          setDetailedDataTableColumns(detailed_column_list);
613
614
          let detailed_value_list = [];
615
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
616
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
617
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
618
            for (let index = 0; index < max_timestamps_length; index++) {
619
              let detailed_value = {};
620
              detailed_value['id'] = index;
621
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
622
              json['base_period']['sub_averages'].forEach((currentValue, energyCategoryIndex) => {
623
                detailed_value['a' + energyCategoryIndex*2] = index < json['base_period']['sub_averages'][energyCategoryIndex].length? json['base_period']['sub_averages'][energyCategoryIndex][index] : null;
624
              });
625
              json['base_period']['sub_maximums'].forEach((currentValue, energyCategoryIndex) => {
626
                detailed_value['a' + (energyCategoryIndex*2+1)] = index < json['base_period']['sub_maximums'][energyCategoryIndex].length? json['base_period']['sub_maximums'][energyCategoryIndex][index] : null;
627
              });
628
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
629
              json['reporting_period']['sub_averages'].forEach((currentValue, energyCategoryIndex) => {
630
                detailed_value['b' + energyCategoryIndex*2] = index < json['reporting_period']['sub_averages'][energyCategoryIndex].length? json['reporting_period']['sub_averages'][energyCategoryIndex][index] : null;
631
              });
632
              json['reporting_period']['sub_maximums'].forEach((currentValue, energyCategoryIndex) => {
633
                detailed_value['b' + (energyCategoryIndex*2+1)] = index < json['reporting_period']['sub_maximums'][energyCategoryIndex].length? json['reporting_period']['sub_maximums'][energyCategoryIndex][index] : null;
634
              });
635
              detailed_value_list.push(detailed_value);
636
            }
637
            setTimeout( () => {
638
              setDetailedDataTableData(detailed_value_list);
639
            }, 0)
640
          }
641
        }
642
        
643
        let associated_equipment_value_list = [];
644
        if (json['associated_equipment']['associated_equipment_names_array'].length > 0) {
645
          json['associated_equipment']['associated_equipment_names_array'][0].forEach((currentEquipmentName, equipmentIndex) => {
646
            let associated_equipment_value = {};
647
            associated_equipment_value['id'] = equipmentIndex;
648
            associated_equipment_value['name'] = currentEquipmentName;
649
            json['associated_equipment']['energy_category_names'].forEach((currentValue, energyCategoryIndex) => {
650
              if (json['associated_equipment']['sub_averages_array'][energyCategoryIndex][equipmentIndex] != null) {
651
                associated_equipment_value['a' + 2 * energyCategoryIndex] = json['associated_equipment']['sub_averages_array'][energyCategoryIndex][equipmentIndex];
652
              } else {
653
                associated_equipment_value['a' + 2 * energyCategoryIndex] = null
654
              };  
655
              if (json['associated_equipment']['sub_maximums_array'][energyCategoryIndex][equipmentIndex] != null) {
656
                associated_equipment_value['a' + (2 * energyCategoryIndex + 1)] = json['associated_equipment']['sub_maximums_array'][energyCategoryIndex][equipmentIndex];
657
              } else {
658
                associated_equipment_value['a' + (2 * energyCategoryIndex + 1)] = null;
659
              };       
660
              
661
            });
662
            associated_equipment_value_list.push(associated_equipment_value);
663
          });
664
        };
665
666
        setAssociatedEquipmentTableData(associated_equipment_value_list);
667
668
        let associated_equipment_column_list = [];
669
        associated_equipment_column_list.push({
670
          dataField: 'name',
671
          text: t('Associated Equipment'),
672
          sort: true
673
        });
674
        json['associated_equipment']['energy_category_names'].forEach((currentValue, index) => {
675
          let unit = json['associated_equipment']['units'][index];
676
          associated_equipment_column_list.push({
677
            dataField: 'a' + 2 * index,
678
            text: currentValue + ' ' + t('Average Load') + ' (' + unit + '/H)',
679
            sort: true,
680
            formatter: function (decimalValue) {
681
              if (typeof decimalValue === 'number') {
682
                return decimalValue.toFixed(2);
683
              } else {
684
                return null;
685
              }
686
            }
687
          });
688
          associated_equipment_column_list.push({
689
            dataField: 'a' + (2 * index + 1),
690
            text: currentValue + ' ' + t('Maximum Load') + ' (' + unit + '/H)',
691
            sort: true,
692
            formatter: function (decimalValue) {
693
              if (typeof decimalValue === 'number') {
694
                return decimalValue.toFixed(2);
695
              } else {
696
                return null;
697
              }
698
            }
699
          });
700
        });
701
702
        setAssociatedEquipmentTableColumns(associated_equipment_column_list);
703
704
        setExcelBytesBase64(json['excel_bytes_base64']);
705
706
        // enable submit button
707
        setSubmitButtonDisabled(false);
708
        // hide spinner
709
        setSpinnerHidden(true);
710
        // show export button
711
        setExportButtonHidden(false);
712
          
713
      } else {
714
        toast.error(t(json.description))
715
      }
716
    }).catch(err => {
717
      console.log(err);
718
    });
719
  };
720
721
  const handleExport = e => {
722
    e.preventDefault();
723
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
724
    const fileName = 'combinedequipmentload.xlsx'
725
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
726
    fetch(fileUrl)
727
        .then(response => response.blob())
728
        .then(blob => {
729
            var link = window.document.createElement("a");
730
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
731
            link.download = fileName;
732
            document.body.appendChild(link);
733
            link.click();
734
            document.body.removeChild(link);
735
        });
736
  };
737
  
738
739
740
  return (
741
    <Fragment>
742
      <div>
743
        <Breadcrumb>
744
          <BreadcrumbItem>{t('Combined Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Load')}</BreadcrumbItem>
745
        </Breadcrumb>
746
      </div>
747
      <Card className="bg-light mb-3">
748
        <CardBody className="p-3">
749
          <Form onSubmit={handleSubmit}>
750
            <Row form>
751
              <Col xs={6} sm={3}>
752
                <FormGroup className="form-group">
753
                  <Label className={labelClasses} for="space">
754
                    {t('Space')}
755
                  </Label>
756
                  <br />
757
                  <Cascader options={cascaderOptions}
758
                    onChange={onSpaceCascaderChange}
759
                    changeOnSelect
760
                    expandTrigger="hover">
761
                    <Input value={selectedSpaceName || ''} readOnly />
762
                  </Cascader>
763
                </FormGroup>
764
              </Col>
765
              <Col xs="auto">
766
                <FormGroup>
767
                  <Label className={labelClasses} for="combinedEquipmentSelect">
768
                    {t('Combined Equipment')}
769
                  </Label>
770
                  <CustomInput type="select" id="combinedEquipmentSelect" name="combinedEquipmentSelect" onChange={({ target }) => setSelectedCombinedEquipment(target.value)}
771
                  >
772
                    {combinedEquipmentList.map((combinedEquipment, index) => (
773
                      <option value={combinedEquipment.value} key={combinedEquipment.value}>
774
                        {combinedEquipment.label}
775
                      </option>
776
                    ))}
777
                  </CustomInput>
778
                </FormGroup>
779
              </Col>
780
              <Col xs="auto">
781
                <FormGroup>
782
                  <Label className={labelClasses} for="comparisonType">
783
                    {t('Comparison Types')}
784
                  </Label>
785
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
786
                    defaultValue="month-on-month"
787
                    onChange={onComparisonTypeChange}
788
                  >
789
                    {comparisonTypeOptions.map((comparisonType, index) => (
790
                      <option value={comparisonType.value} key={comparisonType.value} >
791
                        {t(comparisonType.label)}
792
                      </option>
793
                    ))}
794
                  </CustomInput>
795
                </FormGroup>
796
              </Col>
797
              <Col xs="auto">
798
                <FormGroup>
799
                  <Label className={labelClasses} for="periodType">
800
                    {t('Period Types')}
801
                  </Label>
802
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
803
                  >
804
                    {periodTypeOptions.map((periodType, index) => (
805
                      <option value={periodType.value} key={periodType.value} >
806
                        {t(periodType.label)}
807
                      </option>
808
                    ))}
809
                  </CustomInput>
810
                </FormGroup>
811
              </Col>
812
              <Col xs={6} sm={3}>
813
                <FormGroup className="form-group">
814
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
815
                  <DateRangePickerWrapper 
816
                    id='basePeriodDateRangePicker'
817
                    disabled={basePeriodDateRangePickerDisabled}
818
                    format="yyyy-MM-dd HH:mm:ss"
819
                    value={basePeriodDateRange}
820
                    onChange={onBasePeriodChange}
821
                    size="md"
822
                    style={dateRangePickerStyle}
823
                    onClean={onBasePeriodClean}
824
                    locale={dateRangePickerLocale}
825
                    placeholder={t("Select Date Range")}
826
                   />
827
                </FormGroup>
828
              </Col>
829
              <Col xs={6} sm={3}>
830
                <FormGroup className="form-group">
831
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
832
                  <br/>
833
                  <DateRangePickerWrapper
834
                    id='reportingPeriodDateRangePicker'
835
                    format="yyyy-MM-dd HH:mm:ss"
836
                    value={reportingPeriodDateRange}
837
                    onChange={onReportingPeriodChange}
838
                    size="md"
839
                    style={dateRangePickerStyle}
840
                    onClean={onReportingPeriodClean}
841
                    locale={dateRangePickerLocale}
842
                    placeholder={t("Select Date Range")}
843
                  />
844
                </FormGroup>
845
              </Col>
846
              <Col xs="auto">
847
                <FormGroup>
848
                  <br></br>
849
                  <ButtonGroup id="submit">
850
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
851
                  </ButtonGroup>
852
                </FormGroup>
853
              </Col>
854
              <Col xs="auto">
855
                <FormGroup>
856
                  <br></br>
857
                  <Spinner color="primary" hidden={spinnerHidden}  />
858
                </FormGroup>
859
              </Col>
860
              <Col xs="auto">
861
                  <br></br>
862
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
863
                  hidden={exportButtonHidden}
864
                  onClick={handleExport} >
865
                    {t('Export')}
866
                  </ButtonIcon>
867
              </Col>
868
            </Row>
869
          </Form>
870
        </CardBody>
871
      </Card>
872
      {cardSummaryList.map(cardSummaryItem => (
873
        <div className="card-deck" key={cardSummaryItem['name']}>
874
          <CardSummary key={cardSummaryItem['name'] + 'average'}
875
            rate={cardSummaryItem['average_increment_rate']}
876
            title={t('Reporting Period CATEGORY Average Load UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + '/H)' })}
877
            color="success" >
878
            {cardSummaryItem['average'] && <CountUp end={cardSummaryItem['average']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
879
          </CardSummary>
880
          <CardSummary key={cardSummaryItem['name'] + 'maximum'}
881
            rate={cardSummaryItem['maximum_increment_rate']}
882
            title={t('Reporting Period CATEGORY Maximum Load UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + '/H)' })}
883
            color="success" >
884
            {cardSummaryItem['maximum'] && <CountUp end={cardSummaryItem['maximum']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
885
          </CardSummary>
886
          <CardSummary key={cardSummaryItem['name'] + 'factor'}
887
            rate={cardSummaryItem['factor_increment_rate']}
888
            title={t('Reporting Period CATEGORY Load Factor', { 'CATEGORY': cardSummaryItem['name'] })}
889
            color="success" 
890
            footnote={t('Ratio of Average Load to Maximum Load')} >
891
            {cardSummaryItem['factor'] && <CountUp end={cardSummaryItem['factor']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
892
          </CardSummary>
893
        </div>
894
      ))}
895
896
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period CATEGORY Maximum Load UNIT", "substitute": ["CATEGORY", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "UNIT": combinedEquipmentBaseAndReportingUnits}}
897
        baseTitle = {{"name": "Base Period CATEGORY Maximum Load UNIT", "substitute": ["CATEGORY", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "UNIT": combinedEquipmentBaseAndReportingUnits}}
898
        reportingTooltipTitle = {{"name": "Reporting Period CATEGORY Maximum Load UNIT", "substitute": ["CATEGORY", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "UNIT": combinedEquipmentBaseAndReportingUnits}}
899
        baseTooltipTitle = {{"name": "Base Period CATEGORY Maximum Load UNIT", "substitute": ["CATEGORY", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "UNIT": combinedEquipmentBaseAndReportingUnits}}
900
        reportingLabels={combinedEquipmentReportingLabels}
901
        reportingData={combinedEquipmentReportingData}
902
        baseLabels={combinedEquipmentBaseLabels}
903
        baseData={combinedEquipmentBaseData}
904
        rates={combinedEquipmentReportingRates}
905
        options={combinedEquipmentReportingOptions}>
906
      </MultiTrendChart>
907
908
      <MultipleLineChart reportingTitle={t('Related Parameters')}
909
        baseTitle=''
910
        labels={parameterLineChartLabels}
911
        data={parameterLineChartData}
912
        options={parameterLineChartOptions}>
913
      </MultipleLineChart>
914
      <br />
915
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
916
      </DetailedDataTable>
917
      <br />
918
      <AssociatedEquipmentTable data={associatedEquipmentTableData} title={t('Associated Equipment Data')} columns={associatedEquipmentTableColumns}>
919
      </AssociatedEquipmentTable>
920
921
    </Fragment>
922
  );
923
};
924
925
export default withTranslation()(withRedirect(CombinedEquipmentLoad));
926