Passed
Push — master ( ad5689...ea18a2 )
by Guangyu
08:17 queued 13s
created

myems-web/src/components/MyEMS/Equipment/EquipmentOutput.js   B

Complexity

Total Complexity 42
Complexity/F 0

Size

Lines of Code 814
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 42
eloc 686
mnd 42
bc 42
fnc 0
dl 0
loc 814
rs 8.954
bpm 0
cpm 0
noi 0
c 0
b 0
f 0

How to fix   Complexity   

Complexity

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

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

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