Passed
Push — master ( 107ae9...7e7300 )
by Guangyu
12:14 queued 12s
created

myems-web/src/components/MyEMS/Store/StoreSaving.js   B

Complexity

Total Complexity 41
Complexity/F 0

Size

Lines of Code 875
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 41
eloc 746
dl 0
loc 875
rs 8.974
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/Store/StoreSaving.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 StoreSaving = ({ 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 [storeList, setStoreList] = useState([]);
67
  const [selectedStore, setSelectedStore] = 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 [storeBaseAndReportingNames, setStoreBaseAndReportingNames] = useState({"a0":""});
108
  const [storeBaseAndReportingUnits, setStoreBaseAndReportingUnits] = useState({"a0":"()"});
109
110
  const [storeBaseLabels, setStoreBaseLabels] = useState({"a0": []});
111
  const [storeBaseData, setStoreBaseData] = useState({"a0": []});
112
  const [storeBaseSubtotals, setStoreBaseSubtotals] = useState({"a0": (0).toFixed(2)});
113
114
  const [storeReportingLabels, setStoreReportingLabels] = useState({"a0": []});
115
  const [storeReportingData, setStoreReportingData] = useState({"a0": []});
116
  const [storeReportingSubtotals, setStoreReportingSubtotals] = useState({"a0": (0).toFixed(2)});
117
118
  const [storeReportingRates, setStoreReportingRates] = useState({"a0": []});
119
  const [storeReportingOptions, setStoreReportingOptions] = 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 Stores by root Space ID
155
        let isResponseOK = false;
156
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/stores', {
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
            setStoreList(json[0]);
175
            if (json[0].length > 0) {
176
              setSelectedStore(json[0][0].value);
177
              // enable submit button
178
              setSubmitButtonDisabled(false);
179
            } else {
180
              setSelectedStore(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 Stores 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] + '/stores', {
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
        setStoreList(json[0]);
226
        if (json[0].length > 0) {
227
          setSelectedStore(json[0][0].value);
228
          // enable submit button
229
          setSubmitButtonDisabled(false);
230
        } else {
231
          setSelectedStore(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
  // Handler
320
  const handleSubmit = e => {
321
    e.preventDefault();
322
    console.log('handleSubmit');
323
    console.log(selectedSpaceID);
324
    console.log(selectedStore);
325
    console.log(comparisonType);
326
    console.log(periodType);
327
    console.log(basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : null)
328
    console.log(basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : null)
329
    console.log(moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss'))
330
    console.log(moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss'));
331
332
    // disable submit button
333
    setSubmitButtonDisabled(true);
334
    // show spinner
335
    setSpinnerHidden(false);
336
    // hide export button
337
    setExportButtonHidden(true)
338
339
    // Reinitialize tables
340
    setDetailedDataTableData([]);
341
    
342
    let isResponseOK = false;
343
    fetch(APIBaseURL + '/reports/storesaving?' +
344
      'storeid=' + selectedStore +
345
      '&periodtype=' + periodType +
346
      '&baseperiodstartdatetime=' + (basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : '') +
347
      '&baseperiodenddatetime=' + (basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : '') +
348
      '&reportingperiodstartdatetime=' + moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') +
349
      '&reportingperiodenddatetime=' + moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') + 
350
      '&language=' + language, {
351
      method: 'GET',
352
      headers: {
353
        "Content-type": "application/json",
354
        "User-UUID": getCookieValue('user_uuid'),
355
        "Token": getCookieValue('token')
356
      },
357
      body: null,
358
359
    }).then(response => {
360
      if (response.ok) {
361
        isResponseOK = true;
362
      };
363
      return response.json();
364
    }).then(json => {
365
      if (isResponseOK) {
366
        console.log(json);
367
368
        let cardSummaryArray = []
369
        json['reporting_period']['names'].forEach((currentValue, index) => {
370
          let cardSummaryItem = {}
371
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
372
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
373
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals_saving'][index];
374
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates_saving'][index] * 100).toFixed(2) + "%";
375
          cardSummaryItem['subtotal_per_unit_area'] = json['reporting_period']['subtotals_per_unit_area_saving'][index];
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
        totalInTCE['value_per_unit_area'] = json['reporting_period']['total_in_kgce_per_unit_area_saving'] / 1000; // convert from kg to t
384
        setTotalInTCE(totalInTCE);
385
386
        let totalInTCO2E = {}; 
387
        totalInTCO2E['value'] = json['reporting_period']['total_in_kgco2e_saving'] / 1000; // convert from kg to t
388
        totalInTCO2E['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgco2e_saving'] * 100).toFixed(2) + "%";
389
        totalInTCO2E['value_per_unit_area'] = json['reporting_period']['total_in_kgco2e_per_unit_area_saving'] / 1000; // convert from kg to t
390
        setTotalInTCO2E(totalInTCO2E);
391
392
        let TCEDataArray = [];
393
        json['reporting_period']['names'].forEach((currentValue, index) => {
394
          let TCEDataItem = {}
395
          TCEDataItem['id'] = index;
396
          TCEDataItem['name'] = currentValue;
397
          TCEDataItem['value'] = json['reporting_period']['subtotals_in_kgce_saving'][index] / 1000; // convert from kg to t
398
          TCEDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
399
          TCEDataArray.push(TCEDataItem);
400
        });
401
        setTCEShareData(TCEDataArray);
402
403
        let TCO2EDataArray = [];
404
        json['reporting_period']['names'].forEach((currentValue, index) => {
405
          let TCO2EDataItem = {}
406
          TCO2EDataItem['id'] = index;
407
          TCO2EDataItem['name'] = currentValue;
408
          TCO2EDataItem['value'] = json['reporting_period']['subtotals_in_kgco2e_saving'][index] / 1000; // convert from kg to t
409
          TCO2EDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
410
          TCO2EDataArray.push(TCO2EDataItem);
411
        });
412
        setTCO2EShareData(TCO2EDataArray);
413
414
        let base_timestamps = {}
415
        json['base_period']['timestamps'].forEach((currentValue, index) => {
416
          base_timestamps['a' + index] = currentValue;
417
        });
418
        setStoreBaseLabels(base_timestamps)
419
420
        let base_values = {}
421
        json['base_period']['values_saving'].forEach((currentValue, index) => {
422
          base_values['a' + index] = currentValue;
423
        });
424
        setStoreBaseData(base_values)
425
426
        /*
427
        * Tip:
428
        *     base_names === reporting_names
429
        *     base_units === reporting_units
430
        * */
431
432
        let base_and_reporting_names = {}
433
        json['reporting_period']['names'].forEach((currentValue, index) => {
434
          base_and_reporting_names['a' + index] = currentValue;
435
        });
436
        setStoreBaseAndReportingNames(base_and_reporting_names)
437
438
        let base_and_reporting_units = {}
439
        json['reporting_period']['units'].forEach((currentValue, index) => {
440
          base_and_reporting_units['a' + index] = "("+currentValue+")";
441
        });
442
        setStoreBaseAndReportingUnits(base_and_reporting_units)
443
444
        let base_subtotals = {}
445
        json['base_period']['subtotals_saving'].forEach((currentValue, index) => {
446
          base_subtotals['a' + index] = currentValue.toFixed(2);
447
        });
448
        setStoreBaseSubtotals(base_subtotals)
449
450
        let reporting_timestamps = {}
451
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
452
          reporting_timestamps['a' + index] = currentValue;
453
        });
454
        setStoreReportingLabels(reporting_timestamps);
455
456
        let reporting_values = {}
457
        json['reporting_period']['values_saving'].forEach((currentValue, index) => {
458
          reporting_values['a' + index] = currentValue;
459
        });
460
        setStoreReportingData(reporting_values);
461
462
        let reporting_subtotals = {}
463
        json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
464
          reporting_subtotals['a' + index] = currentValue.toFixed(2);
465
        });
466
        setStoreReportingSubtotals(reporting_subtotals);
467
468
        let rates = {}
469
        json['reporting_period']['rates_saving'].forEach((currentValue, index) => {
470
          let currentRate = Array();
471
          currentValue.forEach((rate) => {
472
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
473
          });
474
          rates['a' + index] = currentRate;
475
        });
476
        setStoreReportingRates(rates)
477
478
        let options = Array();
479
        json['reporting_period']['names'].forEach((currentValue, index) => {
480
          let unit = json['reporting_period']['units'][index];
481
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
482
        });
483
        setStoreReportingOptions(options);
484
485
        let timestamps = {}
486
        json['parameters']['timestamps'].forEach((currentValue, index) => {
487
          timestamps['a' + index] = currentValue;
488
        });
489
        setParameterLineChartLabels(timestamps);
490
491
        let values = {}
492
        json['parameters']['values'].forEach((currentValue, index) => {
493
          values['a' + index] = currentValue;
494
        });
495
        setParameterLineChartData(values);
496
      
497
        let names = Array();
498
        json['parameters']['names'].forEach((currentValue, index) => {
499
          
500
          names.push({ 'value': 'a' + index, 'label': currentValue });
501
        });
502
        setParameterLineChartOptions(names);
503
504
        if(!isBasePeriodTimestampExists(json['base_period'])) {
505
          let detailed_value_list = [];
506
          if (json['reporting_period']['timestamps'].length > 0) {
507
            json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
508
              let detailed_value = {};
509
              detailed_value['id'] = timestampIndex;
510
              detailed_value['startdatetime'] = currentTimestamp;
511
              json['reporting_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
512
                detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values_saving'][energyCategoryIndex][timestampIndex];
513
              });
514
              detailed_value_list.push(detailed_value);
515
            });
516
          }
517
          ;
518
519
          let detailed_value = {};
520
          detailed_value['id'] = detailed_value_list.length;
521
          detailed_value['startdatetime'] = t('Subtotal');
522
          json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
523
            detailed_value['a' + index] = currentValue;
524
          });
525
          detailed_value_list.push(detailed_value);
526
          setTimeout(() => {
527
            setDetailedDataTableData(detailed_value_list);
528
          }, 0)
529
530
          let detailed_column_list = [];
531
          detailed_column_list.push({
532
            dataField: 'startdatetime',
533
            text: t('Datetime'),
534
            sort: true
535
          });
536
          json['reporting_period']['names'].forEach((currentValue, index) => {
537
            let unit = json['reporting_period']['units'][index];
538
            detailed_column_list.push({
539
              dataField: 'a' + index,
540
              text: currentValue + ' (' + unit + ')',
541
              sort: true,
542
              formatter: function (decimalValue) {
543
                if (typeof decimalValue === 'number') {
544
                  return decimalValue.toFixed(2);
545
                } else {
546
                  return null;
547
                }
548
              }
549
            });
550
          });
551
          setDetailedDataTableColumns(detailed_column_list);
552
        }else {
553
          /*
554
          * Tip:
555
          *     json['base_period']['names'] ===  json['reporting_period']['names']
556
          *     json['base_period']['units'] ===  json['reporting_period']['units']
557
          * */
558
          let detailed_column_list = [];
559
          detailed_column_list.push({
560
            dataField: 'basePeriodDatetime',
561
            text: t('Base Period') + ' - ' + t('Datetime'),
562
            sort: true
563
          })
564
565
          json['base_period']['names'].forEach((currentValue, index) => {
566
            let unit = json['base_period']['units'][index];
567
            detailed_column_list.push({
568
              dataField: 'a' + index,
569
              text: t('Base Period') + ' - ' + currentValue + ' (' + unit + ')',
570
              sort: true,
571
              formatter: function (decimalValue) {
572
                if (typeof decimalValue === 'number') {
573
                  return decimalValue.toFixed(2);
574
                } else {
575
                  return null;
576
                }
577
              }
578
            })
579
          });
580
581
          detailed_column_list.push({
582
            dataField: 'reportingPeriodDatetime',
583
            text: t('Reporting Period') + ' - ' + t('Datetime'),
584
            sort: true
585
          })
586
587
          json['reporting_period']['names'].forEach((currentValue, index) => {
588
            let unit = json['reporting_period']['units'][index];
589
            detailed_column_list.push({
590
              dataField: 'b' + index,
591
              text: t('Reporting Period') + ' - ' + currentValue + ' (' + unit + ')',
592
              sort: true,
593
              formatter: function (decimalValue) {
594
                if (typeof decimalValue === 'number') {
595
                  return decimalValue.toFixed(2);
596
                } else {
597
                  return null;
598
                }
599
              }
600
            })
601
          });
602
          setDetailedDataTableColumns(detailed_column_list);
603
604
          let detailed_value_list = [];
605
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
606
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
607
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
608
            for (let index = 0; index < max_timestamps_length; index++) {
609
              let detailed_value = {};
610
              detailed_value['id'] = index;
611
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
612
              json['base_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
613
                detailed_value['a' + energyCategoryIndex] = index < json['base_period']['values_saving'][energyCategoryIndex].length? json['base_period']['values_saving'][energyCategoryIndex][index] : null;
614
              });
615
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
616
              json['reporting_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
617
                detailed_value['b' + energyCategoryIndex] = index < json['reporting_period']['values_saving'][energyCategoryIndex].length? json['reporting_period']['values_saving'][energyCategoryIndex][index] : null;
618
              });
619
              detailed_value_list.push(detailed_value);
620
            }
621
622
            let detailed_value = {};
623
            detailed_value['id'] = detailed_value_list.length;
624
            detailed_value['basePeriodDatetime'] = t('Subtotal');
625
            json['base_period']['subtotals_saving'].forEach((currentValue, index) => {
626
              detailed_value['a' + index] = currentValue;
627
            });
628
            detailed_value['reportingPeriodDatetime'] = t('Subtotal');
629
            json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
630
              detailed_value['b' + index] = currentValue;
631
            });
632
            detailed_value_list.push(detailed_value);
633
            setTimeout( () => {
634
              setDetailedDataTableData(detailed_value_list);
635
            }, 0)
636
          }
637
        }
638
        
639
        setExcelBytesBase64(json['excel_bytes_base64']);
640
641
        // enable submit button
642
        setSubmitButtonDisabled(false);
643
        // hide spinner
644
        setSpinnerHidden(true);
645
        // show export button
646
        setExportButtonHidden(false)
647
648
      } else {
649
        toast.error(t(json.description))
650
      }
651
    }).catch(err => {
652
      console.log(err);
653
    });
654
  };
655
656
  const handleExport = e => {
657
    e.preventDefault();
658
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
659
    const fileName = 'storesaving.xlsx'
660
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
661
    fetch(fileUrl)
662
        .then(response => response.blob())
663
        .then(blob => {
664
            var link = window.document.createElement("a");
665
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
666
            link.download = fileName;
667
            document.body.appendChild(link);
668
            link.click();
669
            document.body.removeChild(link);
670
        });
671
  };
672
  
673
674
675
  return (
676
    <Fragment>
677
      <div>
678
        <Breadcrumb>
679
          <BreadcrumbItem>{t('Store Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Saving')}</BreadcrumbItem>
680
        </Breadcrumb>
681
      </div>
682
      <Card className="bg-light mb-3">
683
        <CardBody className="p-3">
684
          <Form onSubmit={handleSubmit}>
685
            <Row form>
686
              <Col xs={6} sm={3}>
687
                <FormGroup className="form-group">
688
                  <Label className={labelClasses} for="space">
689
                    {t('Space')}
690
                  </Label>
691
                  <br />
692
                  <Cascader options={cascaderOptions}
693
                    onChange={onSpaceCascaderChange}
694
                    changeOnSelect
695
                    expandTrigger="hover">
696
                    <Input value={selectedSpaceName || ''} readOnly />
697
                  </Cascader>
698
                </FormGroup>
699
              </Col>
700
              <Col xs="auto">
701
                <FormGroup>
702
                  <Label className={labelClasses} for="storeSelect">
703
                    {t('Store')}
704
                  </Label>
705
                  <CustomInput type="select" id="storeSelect" name="storeSelect" onChange={({ target }) => setSelectedStore(target.value)}
706
                  >
707
                    {storeList.map((store, index) => (
708
                      <option value={store.value} key={store.value}>
709
                        {store.label}
710
                      </option>
711
                    ))}
712
                  </CustomInput>
713
                </FormGroup>
714
              </Col>
715
              <Col xs="auto">
716
                <FormGroup>
717
                  <Label className={labelClasses} for="comparisonType">
718
                    {t('Comparison Types')}
719
                  </Label>
720
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
721
                    defaultValue="month-on-month"
722
                    onChange={onComparisonTypeChange}
723
                  >
724
                    {comparisonTypeOptions.map((comparisonType, index) => (
725
                      <option value={comparisonType.value} key={comparisonType.value} >
726
                        {t(comparisonType.label)}
727
                      </option>
728
                    ))}
729
                  </CustomInput>
730
                </FormGroup>
731
              </Col>
732
              <Col xs="auto">
733
                <FormGroup>
734
                  <Label className={labelClasses} for="periodType">
735
                    {t('Period Types')}
736
                  </Label>
737
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
738
                  >
739
                    {periodTypeOptions.map((periodType, index) => (
740
                      <option value={periodType.value} key={periodType.value} >
741
                        {t(periodType.label)}
742
                      </option>
743
                    ))}
744
                  </CustomInput>
745
                </FormGroup>
746
              </Col>
747
              <Col xs={6} sm={3}>
748
                <FormGroup className="form-group">
749
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
750
                  <DateRangePickerWrapper 
751
                    id='basePeriodDateRangePicker'
752
                    disabled={basePeriodDateRangePickerDisabled}
753
                    format="yyyy-MM-dd HH:mm:ss"
754
                    value={basePeriodDateRange}
755
                    onChange={onBasePeriodChange}
756
                    size="md"
757
                    style={dateRangePickerStyle}
758
                    onClean={onBasePeriodClean}
759
                    locale={dateRangePickerLocale}
760
                    placeholder={t("Select Date Range")}
761
                   />
762
                </FormGroup>
763
              </Col>
764
              <Col xs={6} sm={3}>
765
                <FormGroup className="form-group">
766
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
767
                  <br/>
768
                  <DateRangePickerWrapper
769
                    id='reportingPeriodDateRangePicker'
770
                    format="yyyy-MM-dd HH:mm:ss"
771
                    value={reportingPeriodDateRange}
772
                    onChange={onReportingPeriodChange}
773
                    size="md"
774
                    style={dateRangePickerStyle}
775
                    onClean={onReportingPeriodClean}
776
                    locale={dateRangePickerLocale}
777
                    placeholder={t("Select Date Range")}
778
                  />
779
                </FormGroup>
780
              </Col>
781
              <Col xs="auto">
782
                <FormGroup>
783
                  <br></br>
784
                  <ButtonGroup id="submit">
785
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
786
                  </ButtonGroup>
787
                </FormGroup>
788
              </Col>
789
              <Col xs="auto">
790
                <FormGroup>
791
                  <br></br>
792
                  <Spinner color="primary" hidden={spinnerHidden}  />
793
                </FormGroup>
794
              </Col>
795
              <Col xs="auto">
796
                  <br></br>
797
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
798
                  hidden={exportButtonHidden}
799
                  onClick={handleExport} >
800
                    {t('Export')}
801
                  </ButtonIcon>
802
              </Col>
803
            </Row>
804
          </Form>
805
        </CardBody>
806
      </Card>
807
      <div className="card-deck">
808
        {cardSummaryList.map(cardSummaryItem => (
809
          <CardSummary key={cardSummaryItem['name']}
810
            rate={cardSummaryItem['increment_rate']}
811
            title={t('Reporting Period Saving CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
812
            color="success" 
813
            footnote={t('Per Unit Area')} 
814
            footvalue={cardSummaryItem['subtotal_per_unit_area']}
815
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
816
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
817
          </CardSummary>
818
        ))}
819
       
820
        <CardSummary 
821
          rate={totalInTCE['increment_rate'] || ''} 
822
          title={t('Reporting Period Saving CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Standard Coal'), 'UNIT': '(TCE)' })}
823
          color="warning" 
824
          footnote={t('Per Unit Area')} 
825
          footvalue={totalInTCE['value_per_unit_area']} 
826
          footunit="(TCE/M²)">
827
          {totalInTCE['value'] && <CountUp end={totalInTCE['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
828
        </CardSummary>
829
        <CardSummary 
830
          rate={totalInTCO2E['increment_rate'] || ''} 
831
          title={t('Reporting Period Decreased CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Carbon Dioxide Emissions'), 'UNIT': '(TCO2E)' })}
832
          color="warning" 
833
          footnote={t('Per Unit Area')} 
834
          footvalue={totalInTCO2E['value_per_unit_area']} 
835
          footunit="(TCO2E/M²)">
836
          {totalInTCO2E['value'] && <CountUp end={totalInTCO2E['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
837
        </CardSummary>
838
      </div>
839
      <Row noGutters>
840
        <Col className="mb-3 pr-lg-2 mb-3">
841
          <SharePie data={TCEShareData} title={t('Ton of Standard Coal by Energy Category')} />
842
        </Col>
843
        <Col className="mb-3 pr-lg-2 mb-3">
844
          <SharePie data={TCO2EShareData} title={t('Ton of Carbon Dioxide Emissions by Energy Category')} />
845
        </Col>
846
      </Row>
847
848
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": storeBaseAndReportingNames, "VALUE": storeReportingSubtotals, "UNIT": storeBaseAndReportingUnits}}
849
        baseTitle = {{"name": "Base Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": storeBaseAndReportingNames, "VALUE": storeBaseSubtotals, "UNIT": storeBaseAndReportingUnits}}
850
        reportingTooltipTitle = {{"name": "Reporting Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": storeBaseAndReportingNames, "VALUE": null, "UNIT": storeBaseAndReportingUnits}}
851
        baseTooltipTitle = {{"name": "Base Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": storeBaseAndReportingNames, "VALUE": null, "UNIT": storeBaseAndReportingUnits}}
852
        reportingLabels={storeReportingLabels}
853
        reportingData={storeReportingData}
854
        baseLabels={storeBaseLabels}
855
        baseData={storeBaseData}
856
        rates={storeReportingRates}
857
        options={storeReportingOptions}>
858
      </MultiTrendChart>
859
860
      <MultipleLineChart reportingTitle={t('Related Parameters')}
861
        baseTitle=''
862
        labels={parameterLineChartLabels}
863
        data={parameterLineChartData}
864
        options={parameterLineChartOptions}>
865
      </MultipleLineChart>
866
      <br />
867
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
868
      </DetailedDataTable>
869
870
    </Fragment>
871
  );
872
};
873
874
export default withTranslation()(withRedirect(StoreSaving));
875