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

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

Complexity

Total Complexity 48
Complexity/F 0

Size

Lines of Code 865
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 48
eloc 717
dl 0
loc 865
rs 8.443
c 0
b 0
f 0
mnd 48
bc 48
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

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

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

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