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

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

Complexity

Total Complexity 43
Complexity/F 0

Size

Lines of Code 850
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 43
eloc 718
dl 0
loc 850
rs 8.842
c 0
b 0
f 0
mnd 43
bc 43
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/CombinedEquipment/CombinedEquipmentOutput.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 CombinedEquipmentOutput = ({ 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
  let onComparisonTypeChange = ({ target }) => {
243
    console.log(target.value);
244
    setComparisonType(target.value);
245
    if (target.value === 'year-over-year') {
246
      setBasePeriodDateRangePickerDisabled(true);
247
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'years').toDate(),
248
        moment(reportingPeriodDateRange[1]).subtract(1, 'years').toDate()]);
249
    } else if (target.value === 'month-on-month') {
250
      setBasePeriodDateRangePickerDisabled(true);
251
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'months').toDate(),
252
        moment(reportingPeriodDateRange[1]).subtract(1, 'months').toDate()]);
253
    } else if (target.value === 'free-comparison') {
254
      setBasePeriodDateRangePickerDisabled(false);
255
    } else if (target.value === 'none-comparison') {
256
      setBasePeriodDateRange([null, null]);
257
      setBasePeriodDateRangePickerDisabled(true);
258
    }
259
  };
260
261
  // Callback fired when value changed
262
  let onBasePeriodChange = (DateRange) => {
263
    if(DateRange == null) {
264
      setBasePeriodDateRange([null, null]);
265
    } else {
266
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
267
        // if the user did not change time value, set the default time to the end of day
268
        DateRange[1] = endOfDay(DateRange[1]);
269
      }
270
      setBasePeriodDateRange([DateRange[0], DateRange[1]]);
271
    }
272
  };
273
274
  // Callback fired when value changed
275
  let onReportingPeriodChange = (DateRange) => {
276
    if(DateRange == null) {
277
      setReportingPeriodDateRange([null, null]);
278
    } else {
279
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
280
        // if the user did not change time value, set the default time to the end of day
281
        DateRange[1] = endOfDay(DateRange[1]);
282
      }
283
      setReportingPeriodDateRange([DateRange[0], DateRange[1]]);
284
      if (comparisonType === 'year-over-year') {
285
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'years').toDate(), moment(DateRange[1]).clone().subtract(1, 'years').toDate()]);
286
      } else if (comparisonType === 'month-on-month') {
287
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'months').toDate(), moment(DateRange[1]).clone().subtract(1, 'months').toDate()]);
288
      }
289
    }
290
  };
291
292
  // Callback fired when value clean
293
  let onBasePeriodClean = event => {
294
    setBasePeriodDateRange([null, null]);
295
  };
296
297
  // Callback fired when value clean
298
  let onReportingPeriodClean = event => {
299
    setReportingPeriodDateRange([null, null]);
300
  };
301
302
  const isBasePeriodTimestampExists = (base_period_data) => {
303
    const timestamps = base_period_data['timestamps'];
304
305
    if (timestamps.length === 0) {
306
      return false;
307
    }
308
309
    for (let i = 0; i < timestamps.length; i++) {
310
      if (timestamps[i].length > 0) {
311
        return true;
312
      }
313
    }
314
    return false
315
  }
316
317
  // Handler
318
  const handleSubmit = e => {
319
    e.preventDefault();
320
    console.log('handleSubmit');
321
    console.log(selectedSpaceID);
322
    console.log(selectedCombinedEquipment);
323
    console.log(comparisonType);
324
    console.log(periodType);
325
    console.log(basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : null)
326
    console.log(basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : null)
327
    console.log(moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss'))
328
    console.log(moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss'));
329
330
    // disable submit button
331
    setSubmitButtonDisabled(true);
332
    // show spinner
333
    setSpinnerHidden(false);
334
    // hide export button
335
    setExportButtonHidden(true)
336
337
    // Reinitialize tables
338
    setDetailedDataTableData([]);
339
    setAssociatedEquipmentTableData([]);
340
    
341
    let isResponseOK = false;
342
    fetch(APIBaseURL + '/reports/combinedequipmentoutput?' +
343
      'combinedequipmentid=' + selectedCombinedEquipment +
344
      '&periodtype=' + periodType +
345
      '&baseperiodstartdatetime=' + (basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : '') +
346
      '&baseperiodenddatetime=' + (basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : '') +
347
      '&reportingperiodstartdatetime=' + moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') +
348
      '&reportingperiodenddatetime=' + moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') +
349
      '&language=' + language, {
350
      method: 'GET',
351
      headers: {
352
        "Content-type": "application/json",
353
        "User-UUID": getCookieValue('user_uuid'),
354
        "Token": getCookieValue('token')
355
      },
356
      body: null,
357
358
    }).then(response => {
359
      if (response.ok) {
360
        isResponseOK = true;
361
      };
362
      return response.json();
363
    }).then(json => {
364
      if (isResponseOK) {
365
        console.log(json)
366
                    
367
        let cardSummaryArray = []
368
        json['reporting_period']['names'].forEach((currentValue, index) => {
369
          let cardSummaryItem = {}
370
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
371
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
372
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals'][index];
373
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates'][index] * 100).toFixed(2) + "%";
374
          cardSummaryArray.push(cardSummaryItem);
375
        });
376
        setCardSummaryList(cardSummaryArray);
377
378
        let base_timestamps = {}
379
        json['base_period']['timestamps'].forEach((currentValue, index) => {
380
          base_timestamps['a' + index] = currentValue;
381
        });
382
        setCombinedEquipmentBaseLabels(base_timestamps)
383
384
        let base_values = {}
385
        json['base_period']['values'].forEach((currentValue, index) => {
386
          base_values['a' + index] = currentValue;
387
        });
388
        setCombinedEquipmentBaseData(base_values)
389
390
        /*
391
        * Tip:
392
        *     base_names === reporting_names
393
        *     base_units === reporting_units
394
        * */
395
396
        let base_and_reporting_names = {}
397
        json['reporting_period']['names'].forEach((currentValue, index) => {
398
          base_and_reporting_names['a' + index] = currentValue;
399
        });
400
        setCombinedEquipmentBaseAndReportingNames(base_and_reporting_names)
401
402
        let base_and_reporting_units = {}
403
        json['reporting_period']['units'].forEach((currentValue, index) => {
404
          base_and_reporting_units['a' + index] = "("+currentValue+")";
405
        });
406
        setCombinedEquipmentBaseAndReportingUnits(base_and_reporting_units)
407
408
        let base_subtotals = {}
409
        json['base_period']['subtotals'].forEach((currentValue, index) => {
410
          base_subtotals['a' + index] = currentValue.toFixed(2);
411
        });
412
        setCombinedEquipmentBaseSubtotals(base_subtotals)
413
414
        let reporting_timestamps = {}
415
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
416
          reporting_timestamps['a' + index] = currentValue;
417
        });
418
        setCombinedEquipmentReportingLabels(reporting_timestamps);
419
420
        let reporting_values = {}
421
        json['reporting_period']['values'].forEach((currentValue, index) => {
422
          reporting_values['a' + index] = currentValue;
423
        });
424
        setCombinedEquipmentReportingData(reporting_values);
425
426
        let reporting_subtotals = {}
427
        json['reporting_period']['subtotals'].forEach((currentValue, index) => {
428
          reporting_subtotals['a' + index] = currentValue.toFixed(2);
429
        });
430
        setCombinedEquipmentReportingSubtotals(reporting_subtotals);
431
432
        let rates = {}
433
        json['reporting_period']['rates'].forEach((currentValue, index) => {
434
          let currentRate = Array();
435
          currentValue.forEach((rate) => {
436
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
437
          });
438
          rates['a' + index] = currentRate;
439
        });
440
        setCombinedEquipmentReportingRates(rates)
441
442
        let options = Array();
443
        json['reporting_period']['names'].forEach((currentValue, index) => {
444
          let unit = json['reporting_period']['units'][index];
445
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
446
        });
447
        setCombinedEquipmentReportingOptions(options);
448
       
449
        let timestamps = {}
450
        json['parameters']['timestamps'].forEach((currentValue, index) => {
451
          timestamps['a' + index] = currentValue;
452
        });
453
        setParameterLineChartLabels(timestamps);
454
455
        let values = {}
456
        json['parameters']['values'].forEach((currentValue, index) => {
457
          values['a' + index] = currentValue;
458
        });
459
        setParameterLineChartData(values);
460
      
461
        let names = Array();
462
        json['parameters']['names'].forEach((currentValue, index) => {
463
          
464
          names.push({ 'value': 'a' + index, 'label': currentValue });
465
        });
466
        setParameterLineChartOptions(names);
467
468
        if(!isBasePeriodTimestampExists(json['base_period'])) {
469
          let detailed_value_list = [];
470
          if (json['reporting_period']['timestamps'].length > 0) {
471
            json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
472
              let detailed_value = {};
473
              detailed_value['id'] = timestampIndex;
474
              detailed_value['startdatetime'] = currentTimestamp;
475
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
476
                detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values'][energyCategoryIndex][timestampIndex];
477
              });
478
              detailed_value_list.push(detailed_value);
479
            });
480
          }
481
          ;
482
483
          let detailed_value = {};
484
          detailed_value['id'] = detailed_value_list.length;
485
          detailed_value['startdatetime'] = t('Subtotal');
486
          json['reporting_period']['subtotals'].forEach((currentValue, index) => {
487
            detailed_value['a' + index] = currentValue;
488
          });
489
          detailed_value_list.push(detailed_value);
490
          setTimeout(() => {
491
            setDetailedDataTableData(detailed_value_list);
492
          }, 0)
493
494
          let detailed_column_list = [];
495
          detailed_column_list.push({
496
            dataField: 'startdatetime',
497
            text: t('Datetime'),
498
            sort: true
499
          });
500
          json['reporting_period']['names'].forEach((currentValue, index) => {
501
            let unit = json['reporting_period']['units'][index];
502
            detailed_column_list.push({
503
              dataField: 'a' + index,
504
              text: currentValue + ' (' + unit + ')',
505
              sort: true,
506
              formatter: function (decimalValue) {
507
                if (typeof decimalValue === 'number') {
508
                  return decimalValue.toFixed(2);
509
                } else {
510
                  return null;
511
                }
512
              }
513
            });
514
          });
515
          setDetailedDataTableColumns(detailed_column_list);
516
        }else {
517
          /*
518
          * Tip:
519
          *     json['base_period']['names'] ===  json['reporting_period']['names']
520
          *     json['base_period']['units'] ===  json['reporting_period']['units']
521
          * */
522
          let detailed_column_list = [];
523
          detailed_column_list.push({
524
            dataField: 'basePeriodDatetime',
525
            text: t('Base Period') + ' - ' + t('Datetime'),
526
            sort: true
527
          })
528
529
          json['base_period']['names'].forEach((currentValue, index) => {
530
            let unit = json['base_period']['units'][index];
531
            detailed_column_list.push({
532
              dataField: 'a' + index,
533
              text: t('Base Period') + ' - ' + currentValue + ' (' + unit + ')',
534
              sort: true,
535
              formatter: function (decimalValue) {
536
                if (typeof decimalValue === 'number') {
537
                  return decimalValue.toFixed(2);
538
                } else {
539
                  return null;
540
                }
541
              }
542
            })
543
          });
544
545
          detailed_column_list.push({
546
            dataField: 'reportingPeriodDatetime',
547
            text: t('Reporting Period') + ' - ' + t('Datetime'),
548
            sort: true
549
          })
550
551
          json['reporting_period']['names'].forEach((currentValue, index) => {
552
            let unit = json['reporting_period']['units'][index];
553
            detailed_column_list.push({
554
              dataField: 'b' + index,
555
              text: t('Reporting Period') + ' - ' + currentValue + ' (' + unit + ')',
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
          });
566
          setDetailedDataTableColumns(detailed_column_list);
567
568
          let detailed_value_list = [];
569
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
570
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
571
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
572
            for (let index = 0; index < max_timestamps_length; index++) {
573
              let detailed_value = {};
574
              detailed_value['id'] = index;
575
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
576
              json['base_period']['values'].forEach((currentValue, energyCategoryIndex) => {
577
                detailed_value['a' + energyCategoryIndex] = index < json['base_period']['values'][energyCategoryIndex].length? json['base_period']['values'][energyCategoryIndex][index] : null;
578
              });
579
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
580
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
581
                detailed_value['b' + energyCategoryIndex] = index < json['reporting_period']['values'][energyCategoryIndex].length? json['reporting_period']['values'][energyCategoryIndex][index] : null;
582
              });
583
              detailed_value_list.push(detailed_value);
584
            }
585
586
            let detailed_value = {};
587
            detailed_value['id'] = detailed_value_list.length;
588
            detailed_value['basePeriodDatetime'] = t('Subtotal');
589
            json['base_period']['subtotals'].forEach((currentValue, index) => {
590
              detailed_value['a' + index] = currentValue;
591
            });
592
            detailed_value['reportingPeriodDatetime'] = t('Subtotal');
593
            json['reporting_period']['subtotals'].forEach((currentValue, index) => {
594
              detailed_value['b' + index] = currentValue;
595
            });
596
            detailed_value_list.push(detailed_value);
597
            setTimeout( () => {
598
              setDetailedDataTableData(detailed_value_list);
599
            }, 0)
600
          }
601
        }
602
        
603
        let associated_equipment_value_list = [];
604
        if (json['associated_equipment']['associated_equipment_names_array'].length > 0) {
605
          json['associated_equipment']['associated_equipment_names_array'][0].forEach((currentEquipmentName, equipmentIndex) => {
606
            let associated_equipment_value = {};
607
            associated_equipment_value['id'] = equipmentIndex;
608
            associated_equipment_value['name'] = currentEquipmentName;
609
            json['associated_equipment']['energy_category_names'].forEach((currentValue, energyCategoryIndex) => {
610
              associated_equipment_value['a' + energyCategoryIndex] = json['associated_equipment']['subtotals_array'][energyCategoryIndex][equipmentIndex];
611
            });
612
            associated_equipment_value_list.push(associated_equipment_value);
613
          });
614
        };
615
616
        setAssociatedEquipmentTableData(associated_equipment_value_list);
617
618
        let associated_equipment_column_list = [];
619
        associated_equipment_column_list.push({
620
          dataField: 'name',
621
          text: t('Associated Equipment'),
622
          sort: true
623
        });
624
        json['associated_equipment']['energy_category_names'].forEach((currentValue, index) => {
625
          let unit = json['associated_equipment']['units'][index];
626
          associated_equipment_column_list.push({
627
            dataField: 'a' + index,
628
            text: currentValue + ' (' + unit + ')',
629
            sort: true,
630
            formatter: function (decimalValue) {
631
              if (typeof decimalValue === 'number') {
632
                return decimalValue.toFixed(2);
633
              } else {
634
                return null;
635
              }
636
            }
637
          });
638
        });
639
640
        setAssociatedEquipmentTableColumns(associated_equipment_column_list);
641
642
        setExcelBytesBase64(json['excel_bytes_base64']);
643
644
        // enable submit button
645
        setSubmitButtonDisabled(false);
646
        // hide spinner
647
        setSpinnerHidden(true);
648
        // show export button
649
        setExportButtonHidden(false);
650
        
651
      } else {
652
        toast.error(t(json.description))
653
      }
654
    }).catch(err => {
655
      console.log(err);
656
    });
657
  };
658
659
  const handleExport = e => {
660
    e.preventDefault();
661
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
662
    const fileName = 'combinedequipmentoutput.xlsx'
663
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
664
    fetch(fileUrl)
665
        .then(response => response.blob())
666
        .then(blob => {
667
            var link = window.document.createElement("a");
668
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
669
            link.download = fileName;
670
            document.body.appendChild(link);
671
            link.click();
672
            document.body.removeChild(link);
673
        });
674
  };
675
  
676
677
  return (
678
    <Fragment>
679
      <div>
680
        <Breadcrumb>
681
          <BreadcrumbItem>{t('Combined Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Output')}</BreadcrumbItem>
682
        </Breadcrumb>
683
      </div>
684
      <Card className="bg-light mb-3">
685
        <CardBody className="p-3">
686
          <Form onSubmit={handleSubmit}>
687
            <Row form>
688
              <Col xs={6} sm={3}>
689
                <FormGroup className="form-group">
690
                  <Label className={labelClasses} for="space">
691
                    {t('Space')}
692
                  </Label>
693
                  <br />
694
                  <Cascader options={cascaderOptions}
695
                    onChange={onSpaceCascaderChange}
696
                    changeOnSelect
697
                    expandTrigger="hover">
698
                    <Input value={selectedSpaceName || ''} readOnly />
699
                  </Cascader>
700
                </FormGroup>
701
              </Col>
702
              <Col xs="auto">
703
                <FormGroup>
704
                  <Label className={labelClasses} for="combinedEquipmentSelect">
705
                    {t('Combined Equipment')}
706
                  </Label>
707
                  <CustomInput type="select" id="combinedEquipmentSelect" name="combinedEquipmentSelect" onChange={({ target }) => setSelectedCombinedEquipment(target.value)}
708
                  >
709
                    {combinedEquipmentList.map((combinedEquipment, index) => (
710
                      <option value={combinedEquipment.value} key={combinedEquipment.value}>
711
                        {combinedEquipment.label}
712
                      </option>
713
                    ))}
714
                  </CustomInput>
715
                </FormGroup>
716
              </Col>
717
              <Col xs="auto">
718
                <FormGroup>
719
                  <Label className={labelClasses} for="comparisonType">
720
                    {t('Comparison Types')}
721
                  </Label>
722
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
723
                    defaultValue="month-on-month"
724
                    onChange={onComparisonTypeChange}
725
                  >
726
                    {comparisonTypeOptions.map((comparisonType, index) => (
727
                      <option value={comparisonType.value} key={comparisonType.value} >
728
                        {t(comparisonType.label)}
729
                      </option>
730
                    ))}
731
                  </CustomInput>
732
                </FormGroup>
733
              </Col>
734
              <Col xs="auto">
735
                <FormGroup>
736
                  <Label className={labelClasses} for="periodType">
737
                    {t('Period Types')}
738
                  </Label>
739
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
740
                  >
741
                    {periodTypeOptions.map((periodType, index) => (
742
                      <option value={periodType.value} key={periodType.value} >
743
                        {t(periodType.label)}
744
                      </option>
745
                    ))}
746
                  </CustomInput>
747
                </FormGroup>
748
              </Col>
749
              <Col xs={6} sm={3}>
750
                <FormGroup className="form-group">
751
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
752
                  <DateRangePickerWrapper 
753
                    id='basePeriodDateRangePicker'
754
                    disabled={basePeriodDateRangePickerDisabled}
755
                    format="yyyy-MM-dd HH:mm:ss"
756
                    value={basePeriodDateRange}
757
                    onChange={onBasePeriodChange}
758
                    size="md"
759
                    style={dateRangePickerStyle}
760
                    onClean={onBasePeriodClean}
761
                    locale={dateRangePickerLocale}
762
                    placeholder={t("Select Date Range")}
763
                   />
764
                </FormGroup>
765
              </Col>
766
              <Col xs={6} sm={3}>
767
                <FormGroup className="form-group">
768
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
769
                  <br/>
770
                  <DateRangePickerWrapper
771
                    id='reportingPeriodDateRangePicker'
772
                    format="yyyy-MM-dd HH:mm:ss"
773
                    value={reportingPeriodDateRange}
774
                    onChange={onReportingPeriodChange}
775
                    size="md"
776
                    style={dateRangePickerStyle}
777
                    onClean={onReportingPeriodClean}
778
                    locale={dateRangePickerLocale}
779
                    placeholder={t("Select Date Range")}
780
                  />
781
                </FormGroup>
782
              </Col>
783
              <Col xs="auto">
784
                <FormGroup>
785
                  <br></br>
786
                  <ButtonGroup id="submit">
787
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
788
                  </ButtonGroup>
789
                </FormGroup>
790
              </Col>
791
              <Col xs="auto">
792
                <FormGroup>
793
                  <br></br>
794
                  <Spinner color="primary" hidden={spinnerHidden}  />
795
                </FormGroup>
796
              </Col>
797
              <Col xs="auto">
798
                  <br></br>
799
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
800
                  hidden={exportButtonHidden}
801
                  onClick={handleExport} >
802
                    {t('Export')}
803
                  </ButtonIcon>
804
              </Col>
805
            </Row>
806
          </Form>
807
        </CardBody>
808
      </Card>
809
      <div className="card-deck">
810
      {cardSummaryList.map(cardSummaryItem => (
811
          <CardSummary key={cardSummaryItem['name']}
812
            rate={cardSummaryItem['increment_rate']}
813
            title={t('Reporting Period Output CATEGORY UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
814
            color="success" >
815
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
816
          </CardSummary>
817
        ))}
818
      </div>
819
820
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Output CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "VALUE": combinedEquipmentReportingSubtotals, "UNIT": combinedEquipmentBaseAndReportingUnits}}
821
        baseTitle = {{"name": "Base Period Output CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "VALUE": combinedEquipmentBaseSubtotals, "UNIT": combinedEquipmentBaseAndReportingUnits}}
822
        reportingTooltipTitle = {{"name": "Reporting Period Output CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "VALUE": null, "UNIT": combinedEquipmentBaseAndReportingUnits}}
823
        baseTooltipTitle = {{"name": "Base Period Output CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": combinedEquipmentBaseAndReportingNames, "VALUE": null, "UNIT": combinedEquipmentBaseAndReportingUnits}}
824
        reportingLabels={combinedEquipmentReportingLabels}
825
        reportingData={combinedEquipmentReportingData}
826
        baseLabels={combinedEquipmentBaseLabels}
827
        baseData={combinedEquipmentBaseData}
828
        rates={combinedEquipmentReportingRates}
829
        options={combinedEquipmentReportingOptions}>
830
      </MultiTrendChart>
831
832
      <MultipleLineChart reportingTitle={t('Related Parameters')}
833
        baseTitle=''
834
        labels={parameterLineChartLabels}
835
        data={parameterLineChartData}
836
        options={parameterLineChartOptions}>
837
      </MultipleLineChart>
838
      <br />
839
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
840
      </DetailedDataTable>
841
      <br />
842
      <AssociatedEquipmentTable data={associatedEquipmentTableData} title={t('Associated Equipment Data')} columns={associatedEquipmentTableColumns}>
843
      </AssociatedEquipmentTable>
844
845
    </Fragment>
846
  );
847
};
848
849
export default withTranslation()(withRedirect(CombinedEquipmentOutput));
850