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

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

Complexity

Total Complexity 43
Complexity/F 0

Size

Lines of Code 910
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 43
eloc 775
dl 0
loc 910
rs 8.785
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/CombinedEquipmentSaving.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

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

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