Passed
Push — master ( c8b356...ca4867 )
by Guangyu
09:12 queued 13s
created

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

Complexity

Total Complexity 41
Complexity/F 0

Size

Lines of Code 864
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 41
eloc 734
dl 0
loc 864
rs 8.986
c 0
b 0
f 0
mnd 41
bc 41
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/Equipment/EquipmentSaving.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
40
const EquipmentSaving = ({ 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 [equipmentList, setEquipmentList] = useState([]);
67
  const [selectedEquipment, setSelectedEquipment] = 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 [TCEShareData, setTCEShareData] = useState([]);
101
  const [TCO2EShareData, setTCO2EShareData] = useState([]);
102
103
  const [cardSummaryList, setCardSummaryList] = useState([]);
104
  const [totalInTCE, setTotalInTCE] = useState({});
105
  const [totalInTCO2E, setTotalInTCO2E] = useState({});
106
107
  const [equipmentBaseAndReportingNames, setEquipmentBaseAndReportingNames] = useState({"a0":""});
108
  const [equipmentBaseAndReportingUnits, setEquipmentBaseAndReportingUnits] = useState({"a0":"()"});
109
110
  const [equipmentBaseLabels, setEquipmentBaseLabels] = useState({"a0": []});
111
  const [equipmentBaseData, setEquipmentBaseData] = useState({"a0": []});
112
  const [equipmentBaseSubtotals, setEquipmentBaseSubtotals] = useState({"a0": (0).toFixed(2)});
113
114
  const [equipmentReportingLabels, setEquipmentReportingLabels] = useState({"a0": []});
115
  const [equipmentReportingData, setEquipmentReportingData] = useState({"a0": []});
116
  const [equipmentReportingSubtotals, setEquipmentReportingSubtotals] = useState({"a0": (0).toFixed(2)});
117
118
  const [equipmentReportingRates, setEquipmentReportingRates] = useState({"a0": []});
119
  const [equipmentReportingOptions, setEquipmentReportingOptions] = useState([]);
120
121
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
122
  const [parameterLineChartData, setParameterLineChartData] = useState({});
123
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
124
125
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
126
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
127
  const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
128
129
  useEffect(() => {
130
    let isResponseOK = false;
131
    fetch(APIBaseURL + '/spaces/tree', {
132
      method: 'GET',
133
      headers: {
134
        "Content-type": "application/json",
135
        "User-UUID": getCookieValue('user_uuid'),
136
        "Token": getCookieValue('token')
137
      },
138
      body: null,
139
140
    }).then(response => {
141
      console.log(response);
142
      if (response.ok) {
143
        isResponseOK = true;
144
      }
145
      return response.json();
146
    }).then(json => {
147
      console.log(json);
148
      if (isResponseOK) {
149
        // rename keys 
150
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
151
        setCascaderOptions(json);
152
        setSelectedSpaceName([json[0]].map(o => o.label));
153
        setSelectedSpaceID([json[0]].map(o => o.value));
154
        // get Equipments by root Space ID
155
        let isResponseOK = false;
156
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/equipments', {
157
          method: 'GET',
158
          headers: {
159
            "Content-type": "application/json",
160
            "User-UUID": getCookieValue('user_uuid'),
161
            "Token": getCookieValue('token')
162
          },
163
          body: null,
164
165
        }).then(response => {
166
          if (response.ok) {
167
            isResponseOK = true;
168
          }
169
          return response.json();
170
        }).then(json => {
171
          if (isResponseOK) {
172
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
173
            console.log(json);
174
            setEquipmentList(json[0]);
175
            if (json[0].length > 0) {
176
              setSelectedEquipment(json[0][0].value);
177
              // enable submit button
178
              setSubmitButtonDisabled(false);
179
            } else {
180
              setSelectedEquipment(undefined);
181
              // disable submit button
182
              setSubmitButtonDisabled(true);
183
            }
184
          } else {
185
            toast.error(t(json.description))
186
          }
187
        }).catch(err => {
188
          console.log(err);
189
        });
190
        // end of get Equipments by root Space ID
191
      } else {
192
        toast.error(t(json.description));
193
      }
194
    }).catch(err => {
195
      console.log(err);
196
    });
197
198
  }, []);
199
200
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
201
202
  let onSpaceCascaderChange = (value, selectedOptions) => {
203
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
204
    setSelectedSpaceID(value[value.length - 1]);
205
206
    let isResponseOK = false;
207
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/equipments', {
208
      method: 'GET',
209
      headers: {
210
        "Content-type": "application/json",
211
        "User-UUID": getCookieValue('user_uuid'),
212
        "Token": getCookieValue('token')
213
      },
214
      body: null,
215
216
    }).then(response => {
217
      if (response.ok) {
218
        isResponseOK = true;
219
      }
220
      return response.json();
221
    }).then(json => {
222
      if (isResponseOK) {
223
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
224
        console.log(json)
225
        setEquipmentList(json[0]);
226
        if (json[0].length > 0) {
227
          setSelectedEquipment(json[0][0].value);
228
          // enable submit button
229
          setSubmitButtonDisabled(false);
230
        } else {
231
          setSelectedEquipment(undefined);
232
          // disable submit button
233
          setSubmitButtonDisabled(true);
234
        }
235
      } else {
236
        toast.error(t(json.description))
237
      }
238
    }).catch(err => {
239
      console.log(err);
240
    });
241
  }
242
243
244
  let onComparisonTypeChange = ({ target }) => {
245
    console.log(target.value);
246
    setComparisonType(target.value);
247
    if (target.value === 'year-over-year') {
248
      setBasePeriodDateRangePickerDisabled(true);
249
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'years').toDate(),
250
        moment(reportingPeriodDateRange[1]).subtract(1, 'years').toDate()]);
251
    } else if (target.value === 'month-on-month') {
252
      setBasePeriodDateRangePickerDisabled(true);
253
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'months').toDate(),
254
        moment(reportingPeriodDateRange[1]).subtract(1, 'months').toDate()]);
255
    } else if (target.value === 'free-comparison') {
256
      setBasePeriodDateRangePickerDisabled(false);
257
    } else if (target.value === 'none-comparison') {
258
      setBasePeriodDateRange([null, null]);
259
      setBasePeriodDateRangePickerDisabled(true);
260
    }
261
  };
262
263
  // Callback fired when value changed
264
  let onBasePeriodChange = (DateRange) => {
265
    if(DateRange == null) {
266
      setBasePeriodDateRange([null, null]);
267
    } else {
268
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
269
        // if the user did not change time value, set the default time to the end of day
270
        DateRange[1] = endOfDay(DateRange[1]);
271
      }
272
      setBasePeriodDateRange([DateRange[0], DateRange[1]]);
273
    }
274
  };
275
276
  // Callback fired when value changed
277
  let onReportingPeriodChange = (DateRange) => {
278
    if(DateRange == null) {
279
      setReportingPeriodDateRange([null, null]);
280
    } else {
281
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
282
        // if the user did not change time value, set the default time to the end of day
283
        DateRange[1] = endOfDay(DateRange[1]);
284
      }
285
      setReportingPeriodDateRange([DateRange[0], DateRange[1]]);
286
      if (comparisonType === 'year-over-year') {
287
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'years').toDate(), moment(DateRange[1]).clone().subtract(1, 'years').toDate()]);
288
      } else if (comparisonType === 'month-on-month') {
289
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'months').toDate(), moment(DateRange[1]).clone().subtract(1, 'months').toDate()]);
290
      }
291
    }
292
  };
293
294
  // Callback fired when value clean
295
  let onBasePeriodClean = event => {
296
    setBasePeriodDateRange([null, null]);
297
  };
298
299
  // Callback fired when value clean
300
  let onReportingPeriodClean = event => {
301
    setReportingPeriodDateRange([null, null]);
302
  };
303
304
  const isBasePeriodTimestampExists = (base_period_data) => {
305
    const timestamps = base_period_data['timestamps'];
306
307
    if (timestamps.length === 0) {
308
      return false;
309
    }
310
311
    for (let i = 0; i < timestamps.length; i++) {
312
      if (timestamps[i].length > 0) {
313
        return true;
314
      }
315
    }
316
    return false
317
  }
318
319
320
  // Handler
321
  const handleSubmit = e => {
322
    e.preventDefault();
323
    console.log('handleSubmit');
324
    console.log(selectedSpaceID);
325
    console.log(selectedEquipment);
326
    console.log(comparisonType);
327
    console.log(periodType);
328
    console.log(basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : null)
329
    console.log(basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : null)
330
    console.log(moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss'))
331
    console.log(moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss'));
332
333
    // disable submit button
334
    setSubmitButtonDisabled(true);
335
    // show spinner
336
    setSpinnerHidden(false);
337
    // hide export button
338
    setExportButtonHidden(true)
339
340
    // Reinitialize tables
341
    setDetailedDataTableData([]);
342
    
343
    let isResponseOK = false;
344
    fetch(APIBaseURL + '/reports/equipmentsaving?' +
345
      'equipmentid=' + selectedEquipment +
346
      '&periodtype=' + periodType +
347
      '&baseperiodstartdatetime=' + (basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : '') +
348
      '&baseperiodenddatetime=' + (basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : '') +
349
      '&reportingperiodstartdatetime=' + moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') +
350
      '&reportingperiodenddatetime=' + moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') +
351
      '&language=' + language, {
352
      method: 'GET',
353
      headers: {
354
        "Content-type": "application/json",
355
        "User-UUID": getCookieValue('user_uuid'),
356
        "Token": getCookieValue('token')
357
      },
358
      body: null,
359
360
    }).then(response => {
361
      if (response.ok) {
362
        isResponseOK = true;
363
      };
364
      return response.json();
365
    }).then(json => {
366
      if (isResponseOK) {
367
        console.log(json);
368
369
        let cardSummaryArray = []
370
        json['reporting_period']['names'].forEach((currentValue, index) => {
371
          let cardSummaryItem = {}
372
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
373
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
374
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals_saving'][index];
375
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates_saving'][index] * 100).toFixed(2) + "%";
376
          cardSummaryArray.push(cardSummaryItem);
377
        });
378
        setCardSummaryList(cardSummaryArray);
379
380
        let totalInTCE = {}; 
381
        totalInTCE['value'] = json['reporting_period']['total_in_kgce_saving'] / 1000; // convert from kg to t
382
        totalInTCE['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgce_saving'] * 100).toFixed(2) + "%";
383
        setTotalInTCE(totalInTCE);
384
385
        let totalInTCO2E = {}; 
386
        totalInTCO2E['value'] = json['reporting_period']['total_in_kgco2e_saving'] / 1000; // convert from kg to t
387
        totalInTCO2E['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgco2e_saving'] * 100).toFixed(2) + "%";
388
        setTotalInTCO2E(totalInTCO2E);
389
390
        let TCEDataArray = [];
391
        json['reporting_period']['names'].forEach((currentValue, index) => {
392
          let TCEDataItem = {}
393
          TCEDataItem['id'] = index;
394
          TCEDataItem['name'] = currentValue;
395
          TCEDataItem['value'] = json['reporting_period']['subtotals_in_kgce_saving'][index] / 1000; // convert from kg to t
396
          TCEDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
397
          TCEDataArray.push(TCEDataItem);
398
        });
399
        setTCEShareData(TCEDataArray);
400
401
        let TCO2EDataArray = [];
402
        json['reporting_period']['names'].forEach((currentValue, index) => {
403
          let TCO2EDataItem = {}
404
          TCO2EDataItem['id'] = index;
405
          TCO2EDataItem['name'] = currentValue;
406
          TCO2EDataItem['value'] = json['reporting_period']['subtotals_in_kgco2e_saving'][index] / 1000; // convert from kg to t
407
          TCO2EDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
408
          TCO2EDataArray.push(TCO2EDataItem);
409
        });
410
        setTCO2EShareData(TCO2EDataArray);
411
412
        let base_timestamps = {}
413
        json['base_period']['timestamps'].forEach((currentValue, index) => {
414
          base_timestamps['a' + index] = currentValue;
415
        });
416
        setEquipmentBaseLabels(base_timestamps)
417
418
        let base_values = {}
419
        json['base_period']['values_saving'].forEach((currentValue, index) => {
420
          base_values['a' + index] = currentValue;
421
        });
422
        setEquipmentBaseData(base_values)
423
424
        /*
425
        * Tip:
426
        *     base_names === reporting_names
427
        *     base_units === reporting_units
428
        * */
429
430
        let base_and_reporting_names = {}
431
        json['reporting_period']['names'].forEach((currentValue, index) => {
432
          base_and_reporting_names['a' + index] = currentValue;
433
        });
434
        setEquipmentBaseAndReportingNames(base_and_reporting_names)
435
436
        let base_and_reporting_units = {}
437
        json['reporting_period']['units'].forEach((currentValue, index) => {
438
          base_and_reporting_units['a' + index] = "("+currentValue+")";
439
        });
440
        setEquipmentBaseAndReportingUnits(base_and_reporting_units)
441
442
        let base_subtotals = {}
443
        json['base_period']['subtotals_saving'].forEach((currentValue, index) => {
444
          base_subtotals['a' + index] = currentValue.toFixed(2);
445
        });
446
        setEquipmentBaseSubtotals(base_subtotals)
447
448
        let reporting_timestamps = {}
449
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
450
          reporting_timestamps['a' + index] = currentValue;
451
        });
452
        setEquipmentReportingLabels(reporting_timestamps);
453
454
        let reporting_values = {}
455
        json['reporting_period']['values_saving'].forEach((currentValue, index) => {
456
          reporting_values['a' + index] = currentValue;
457
        });
458
        setEquipmentReportingData(reporting_values);
459
460
        let reporting_subtotals = {}
461
        json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
462
          reporting_subtotals['a' + index] = currentValue.toFixed(2);
463
        });
464
        setEquipmentReportingSubtotals(reporting_subtotals);
465
466
        let rates = {}
467
        json['reporting_period']['rates_saving'].forEach((currentValue, index) => {
468
          let currentRate = Array();
469
          currentValue.forEach((rate) => {
470
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
471
          });
472
          rates['a' + index] = currentRate;
473
        });
474
        setEquipmentReportingRates(rates)
475
476
        let options = Array();
477
        json['reporting_period']['names'].forEach((currentValue, index) => {
478
          let unit = json['reporting_period']['units'][index];
479
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
480
        });
481
        setEquipmentReportingOptions(options);
482
       
483
        let timestamps = {}
484
        json['parameters']['timestamps'].forEach((currentValue, index) => {
485
          timestamps['a' + index] = currentValue;
486
        });
487
        setParameterLineChartLabels(timestamps);
488
489
        let values = {}
490
        json['parameters']['values'].forEach((currentValue, index) => {
491
          values['a' + index] = currentValue;
492
        });
493
        setParameterLineChartData(values);
494
      
495
        let names = Array();
496
        json['parameters']['names'].forEach((currentValue, index) => {
497
          
498
          names.push({ 'value': 'a' + index, 'label': currentValue });
499
        });
500
        setParameterLineChartOptions(names);
501
502
        if(!isBasePeriodTimestampExists(json['base_period'])) {
503
          let detailed_value_list = [];
504
          if (json['reporting_period']['timestamps'].length > 0) {
505
            json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
506
              let detailed_value = {};
507
              detailed_value['id'] = timestampIndex;
508
              detailed_value['startdatetime'] = currentTimestamp;
509
              json['reporting_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
510
                detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values_saving'][energyCategoryIndex][timestampIndex];
511
              });
512
              detailed_value_list.push(detailed_value);
513
            });
514
          }
515
          ;
516
517
          let detailed_value = {};
518
          detailed_value['id'] = detailed_value_list.length;
519
          detailed_value['startdatetime'] = t('Subtotal');
520
          json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
521
            detailed_value['a' + index] = currentValue;
522
          });
523
          detailed_value_list.push(detailed_value);
524
          setTimeout(() => {
525
            setDetailedDataTableData(detailed_value_list);
526
          }, 0)
527
528
          let detailed_column_list = [];
529
          detailed_column_list.push({
530
            dataField: 'startdatetime',
531
            text: t('Datetime'),
532
            sort: true
533
          });
534
          json['reporting_period']['names'].forEach((currentValue, index) => {
535
            let unit = json['reporting_period']['units'][index];
536
            detailed_column_list.push({
537
              dataField: 'a' + index,
538
              text: 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
          setDetailedDataTableColumns(detailed_column_list);
550
        }else {
551
          /*
552
          * Tip:
553
          *     json['base_period']['names'] ===  json['reporting_period']['names']
554
          *     json['base_period']['units'] ===  json['reporting_period']['units']
555
          * */
556
          let detailed_column_list = [];
557
          detailed_column_list.push({
558
            dataField: 'basePeriodDatetime',
559
            text: t('Base Period') + ' - ' + t('Datetime'),
560
            sort: true
561
          })
562
563
          json['base_period']['names'].forEach((currentValue, index) => {
564
            let unit = json['base_period']['units'][index];
565
            detailed_column_list.push({
566
              dataField: 'a' + index,
567
              text: t('Base Period') + ' - ' + currentValue + ' (' + unit + ')',
568
              sort: true,
569
              formatter: function (decimalValue) {
570
                if (typeof decimalValue === 'number') {
571
                  return decimalValue.toFixed(2);
572
                } else {
573
                  return null;
574
                }
575
              }
576
            })
577
          });
578
579
          detailed_column_list.push({
580
            dataField: 'reportingPeriodDatetime',
581
            text: t('Reporting Period') + ' - ' + t('Datetime'),
582
            sort: true
583
          })
584
585
          json['reporting_period']['names'].forEach((currentValue, index) => {
586
            let unit = json['reporting_period']['units'][index];
587
            detailed_column_list.push({
588
              dataField: 'b' + index,
589
              text: t('Reporting Period') + ' - ' + currentValue + ' (' + unit + ')',
590
              sort: true,
591
              formatter: function (decimalValue) {
592
                if (typeof decimalValue === 'number') {
593
                  return decimalValue.toFixed(2);
594
                } else {
595
                  return null;
596
                }
597
              }
598
            })
599
          });
600
          setDetailedDataTableColumns(detailed_column_list);
601
602
          let detailed_value_list = [];
603
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
604
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
605
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
606
            for (let index = 0; index < max_timestamps_length; index++) {
607
              let detailed_value = {};
608
              detailed_value['id'] = index;
609
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
610
              json['base_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
611
                detailed_value['a' + energyCategoryIndex] = index < json['base_period']['values_saving'][energyCategoryIndex].length? json['base_period']['values_saving'][energyCategoryIndex][index] : null;
612
              });
613
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
614
              json['reporting_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
615
                detailed_value['b' + energyCategoryIndex] = index < json['reporting_period']['values_saving'][energyCategoryIndex].length? json['reporting_period']['values_saving'][energyCategoryIndex][index] : null;
616
              });
617
              detailed_value_list.push(detailed_value);
618
            }
619
620
            let detailed_value = {};
621
            detailed_value['id'] = detailed_value_list.length;
622
            detailed_value['basePeriodDatetime'] = t('Subtotal');
623
            json['base_period']['subtotals_saving'].forEach((currentValue, index) => {
624
              detailed_value['a' + index] = currentValue;
625
            });
626
            detailed_value['reportingPeriodDatetime'] = t('Subtotal');
627
            json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
628
              detailed_value['b' + index] = currentValue;
629
            });
630
            detailed_value_list.push(detailed_value);
631
            setTimeout( () => {
632
              setDetailedDataTableData(detailed_value_list);
633
            }, 0)
634
          }
635
        }
636
        
637
        setExcelBytesBase64(json['excel_bytes_base64']);
638
639
        // enable submit button
640
        setSubmitButtonDisabled(false);
641
        // hide spinner
642
        setSpinnerHidden(true);
643
        // show export button
644
        setExportButtonHidden(false);
645
        
646
      } else {
647
        toast.error(t(json.description))
648
      }
649
    }).catch(err => {
650
      console.log(err);
651
    });
652
  };
653
654
  const handleExport = e => {
655
    e.preventDefault();
656
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
657
    const fileName = 'equipmentsaving.xlsx'
658
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
659
    fetch(fileUrl)
660
        .then(response => response.blob())
661
        .then(blob => {
662
            var link = window.document.createElement("a");
663
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
664
            link.download = fileName;
665
            document.body.appendChild(link);
666
            link.click();
667
            document.body.removeChild(link);
668
        });
669
  };
670
  
671
672
673
  return (
674
    <Fragment>
675
      <div>
676
        <Breadcrumb>
677
          <BreadcrumbItem>{t('Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Saving')}</BreadcrumbItem>
678
        </Breadcrumb>
679
      </div>
680
      <Card className="bg-light mb-3">
681
        <CardBody className="p-3">
682
          <Form onSubmit={handleSubmit}>
683
            <Row form>
684
              <Col xs={6} sm={3}>
685
                <FormGroup className="form-group">
686
                  <Label className={labelClasses} for="space">
687
                    {t('Space')}
688
                  </Label>
689
                  <br />
690
                  <Cascader options={cascaderOptions}
691
                    onChange={onSpaceCascaderChange}
692
                    changeOnSelect
693
                    expandTrigger="hover">
694
                    <Input value={selectedSpaceName || ''} readOnly />
695
                  </Cascader>
696
                </FormGroup>
697
              </Col>
698
              <Col xs="auto">
699
                <FormGroup>
700
                  <Label className={labelClasses} for="equipmentSelect">
701
                    {t('Equipment')}
702
                  </Label>
703
                  <CustomInput type="select" id="equipmentSelect" name="equipmentSelect" onChange={({ target }) => setSelectedEquipment(target.value)}
704
                  >
705
                    {equipmentList.map((equipment, index) => (
706
                      <option value={equipment.value} key={equipment.value}>
707
                        {equipment.label}
708
                      </option>
709
                    ))}
710
                  </CustomInput>
711
                </FormGroup>
712
              </Col>
713
              <Col xs="auto">
714
                <FormGroup>
715
                  <Label className={labelClasses} for="comparisonType">
716
                    {t('Comparison Types')}
717
                  </Label>
718
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
719
                    defaultValue="month-on-month"
720
                    onChange={onComparisonTypeChange}
721
                  >
722
                    {comparisonTypeOptions.map((comparisonType, index) => (
723
                      <option value={comparisonType.value} key={comparisonType.value} >
724
                        {t(comparisonType.label)}
725
                      </option>
726
                    ))}
727
                  </CustomInput>
728
                </FormGroup>
729
              </Col>
730
              <Col xs="auto">
731
                <FormGroup>
732
                  <Label className={labelClasses} for="periodType">
733
                    {t('Period Types')}
734
                  </Label>
735
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
736
                  >
737
                    {periodTypeOptions.map((periodType, index) => (
738
                      <option value={periodType.value} key={periodType.value} >
739
                        {t(periodType.label)}
740
                      </option>
741
                    ))}
742
                  </CustomInput>
743
                </FormGroup>
744
              </Col>
745
              <Col xs={6} sm={3}>
746
                <FormGroup className="form-group">
747
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
748
                  <DateRangePickerWrapper 
749
                    id='basePeriodDateRangePicker'
750
                    disabled={basePeriodDateRangePickerDisabled}
751
                    format="yyyy-MM-dd HH:mm:ss"
752
                    value={basePeriodDateRange}
753
                    onChange={onBasePeriodChange}
754
                    size="md"
755
                    style={dateRangePickerStyle}
756
                    onClean={onBasePeriodClean}
757
                    locale={dateRangePickerLocale}
758
                    placeholder={t("Select Date Range")}
759
                   />
760
                </FormGroup>
761
              </Col>
762
              <Col xs={6} sm={3}>
763
                <FormGroup className="form-group">
764
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
765
                  <br/>
766
                  <DateRangePickerWrapper
767
                    id='reportingPeriodDateRangePicker'
768
                    format="yyyy-MM-dd HH:mm:ss"
769
                    value={reportingPeriodDateRange}
770
                    onChange={onReportingPeriodChange}
771
                    size="md"
772
                    style={dateRangePickerStyle}
773
                    onClean={onReportingPeriodClean}
774
                    locale={dateRangePickerLocale}
775
                    placeholder={t("Select Date Range")}
776
                  />
777
                </FormGroup>
778
              </Col>
779
              <Col xs="auto">
780
                <FormGroup>
781
                  <br></br>
782
                  <ButtonGroup id="submit">
783
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
784
                  </ButtonGroup>
785
                </FormGroup>
786
              </Col>
787
              <Col xs="auto">
788
                <FormGroup>
789
                  <br></br>
790
                  <Spinner color="primary" hidden={spinnerHidden}  />
791
                </FormGroup>
792
              </Col>
793
              <Col xs="auto">
794
                  <br></br>
795
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
796
                  hidden={exportButtonHidden}
797
                  onClick={handleExport} >
798
                    {t('Export')}
799
                  </ButtonIcon>
800
              </Col>
801
            </Row>
802
          </Form>
803
        </CardBody>
804
      </Card>
805
      <div className="card-deck">
806
        {cardSummaryList.map(cardSummaryItem => (
807
          <CardSummary key={cardSummaryItem['name']}
808
            rate={cardSummaryItem['increment_rate']}
809
            title={t('Reporting Period Saving CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
810
            color="success" >
811
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
812
          </CardSummary>
813
        ))}
814
       
815
        <CardSummary 
816
          rate={totalInTCE['increment_rate'] || ''} 
817
          title={t('Reporting Period Saving CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Standard Coal'), 'UNIT': '(TCE)' })}
818
          color="warning" >
819
          {totalInTCE['value'] && <CountUp end={totalInTCE['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
820
        </CardSummary>
821
        <CardSummary 
822
          rate={totalInTCO2E['increment_rate'] || ''} 
823
          title={t('Reporting Period Decreased CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Carbon Dioxide Emissions'), 'UNIT': '(TCO2E)' })}
824
          color="warning" >
825
          {totalInTCO2E['value'] && <CountUp end={totalInTCO2E['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
826
        </CardSummary>
827
      </div>
828
      <Row noGutters>
829
        <Col className="mb-3 pr-lg-2 mb-3">
830
          <SharePie data={TCEShareData} title={t('Ton of Standard Coal by Energy Category')} />
831
        </Col>
832
        <Col className="mb-3 pr-lg-2 mb-3">
833
          <SharePie data={TCO2EShareData} title={t('Ton of Carbon Dioxide Emissions by Energy Category')} />
834
        </Col>
835
      </Row>
836
837
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": equipmentBaseAndReportingNames, "VALUE": equipmentReportingSubtotals, "UNIT": equipmentBaseAndReportingUnits}}
838
        baseTitle = {{"name": "Base Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": equipmentBaseAndReportingNames, "VALUE": equipmentBaseSubtotals, "UNIT": equipmentBaseAndReportingUnits}}
839
        reportingTooltipTitle = {{"name": "Reporting Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": equipmentBaseAndReportingNames, "VALUE": null, "UNIT": equipmentBaseAndReportingUnits}}
840
        baseTooltipTitle = {{"name": "Base Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": equipmentBaseAndReportingNames, "VALUE": null, "UNIT": equipmentBaseAndReportingUnits}}
841
        reportingLabels={equipmentReportingLabels}
842
        reportingData={equipmentReportingData}
843
        baseLabels={equipmentBaseLabels}
844
        baseData={equipmentBaseData}
845
        rates={equipmentReportingRates}
846
        options={equipmentReportingOptions}>
847
      </MultiTrendChart>
848
849
      <MultipleLineChart reportingTitle={t('Related Parameters')}
850
        baseTitle=''
851
        labels={parameterLineChartLabels}
852
        data={parameterLineChartData}
853
        options={parameterLineChartOptions}>
854
      </MultipleLineChart>
855
      <br />
856
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
857
      </DetailedDataTable>
858
859
    </Fragment>
860
  );
861
};
862
863
export default withTranslation()(withRedirect(EquipmentSaving));
864