Passed
Push — master ( 82dd0d...8c8679 )
by Guangyu
10:18 queued 13s
created

myems-web/src/components/MyEMS/Tenant/TenantEnergyCategory.js   B

Complexity

Total Complexity 42
Complexity/F 0

Size

Lines of Code 913
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 42
eloc 783
dl 0
loc 913
rs 8.857
c 0
b 0
f 0
mnd 42
bc 42
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/Tenant/TenantEnergyCategory.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 TenantEnergyCategory = ({ 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 [tenantList, setTenantList] = useState([]);
67
  const [selectedTenant, setSelectedTenant] = 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 [timeOfUseShareData, setTimeOfUseShareData] = useState([]);
101
  const [TCEShareData, setTCEShareData] = useState([]);
102
  const [TCO2EShareData, setTCO2EShareData] = useState([]);
103
104
  const [cardSummaryList, setCardSummaryList] = useState([]);
105
  const [totalInTCE, setTotalInTCE] = useState({});
106
  const [totalInTCO2E, setTotalInTCO2E] = useState({});
107
108
  const [tenantBaseAndReportingNames, setTenantBaseAndReportingNames] = useState({"a0":""});
109
  const [tenantBaseAndReportingUnits, setTenantBaseAndReportingUnits] = useState({"a0":"()"});
110
111
  const [tenantBaseLabels, setTenantBaseLabels] = useState({"a0": []});
112
  const [tenantBaseData, setTenantBaseData] = useState({"a0": []});
113
  const [tenantBaseSubtotals, setTenantBaseSubtotals] = useState({"a0": (0).toFixed(2)});
114
115
  const [tenantReportingLabels, setTenantReportingLabels] = useState({"a0": []});
116
  const [tenantReportingData, setTenantReportingData] = useState({"a0": []});
117
  const [tenantReportingSubtotals, setTenantReportingSubtotals] = useState({"a0": (0).toFixed(2)});
118
119
  const [tenantReportingRates, setTenantReportingRates] = useState({"a0": []});
120
  const [tenantReportingOptions, setTenantReportingOptions] = useState([]);
121
  
122
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
123
  const [parameterLineChartData, setParameterLineChartData] = useState({});
124
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
125
126
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
127
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
128
  const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
129
  
130
  useEffect(() => {
131
    let isResponseOK = false;
132
    fetch(APIBaseURL + '/spaces/tree', {
133
      method: 'GET',
134
      headers: {
135
        "Content-type": "application/json",
136
        "User-UUID": getCookieValue('user_uuid'),
137
        "Token": getCookieValue('token')
138
      },
139
      body: null,
140
141
    }).then(response => {
142
      console.log(response);
143
      if (response.ok) {
144
        isResponseOK = true;
145
      }
146
      return response.json();
147
    }).then(json => {
148
      console.log(json);
149
      if (isResponseOK) {
150
        // rename keys 
151
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
152
        setCascaderOptions(json);
153
        setSelectedSpaceName([json[0]].map(o => o.label));
154
        setSelectedSpaceID([json[0]].map(o => o.value));
155
        // get Tenants by root Space ID
156
        let isResponseOK = false;
157
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/tenants', {
158
          method: 'GET',
159
          headers: {
160
            "Content-type": "application/json",
161
            "User-UUID": getCookieValue('user_uuid'),
162
            "Token": getCookieValue('token')
163
          },
164
          body: null,
165
166
        }).then(response => {
167
          if (response.ok) {
168
            isResponseOK = true;
169
          }
170
          return response.json();
171
        }).then(json => {
172
          if (isResponseOK) {
173
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
174
            console.log(json);
175
            setTenantList(json[0]);
176
            if (json[0].length > 0) {
177
              setSelectedTenant(json[0][0].value);
178
              // enable submit button
179
              setSubmitButtonDisabled(false);
180
            } else {
181
              setSelectedTenant(undefined);
182
              // disable submit button
183
              setSubmitButtonDisabled(true);
184
            }
185
          } else {
186
            toast.error(t(json.description))
187
          }
188
        }).catch(err => {
189
          console.log(err);
190
        });
191
        // end of get Tenants by root Space ID
192
      } else {
193
        toast.error(t(json.description));
194
      }
195
    }).catch(err => {
196
      console.log(err);
197
    });
198
199
  }, []);
200
201
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
202
203
  let onSpaceCascaderChange = (value, selectedOptions) => {
204
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
205
    setSelectedSpaceID(value[value.length - 1]);
206
207
    let isResponseOK = false;
208
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/tenants', {
209
      method: 'GET',
210
      headers: {
211
        "Content-type": "application/json",
212
        "User-UUID": getCookieValue('user_uuid'),
213
        "Token": getCookieValue('token')
214
      },
215
      body: null,
216
217
    }).then(response => {
218
      if (response.ok) {
219
        isResponseOK = true;
220
      }
221
      return response.json();
222
    }).then(json => {
223
      if (isResponseOK) {
224
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
225
        console.log(json)
226
        setTenantList(json[0]);
227
        if (json[0].length > 0) {
228
          setSelectedTenant(json[0][0].value);
229
          // enable submit button
230
          setSubmitButtonDisabled(false);
231
        } else {
232
          setSelectedTenant(undefined);
233
          // disable submit button
234
          setSubmitButtonDisabled(true);
235
        }
236
      } else {
237
        toast.error(t(json.description))
238
      }
239
    }).catch(err => {
240
      console.log(err);
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(selectedTenant);
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/tenantenergycategory?' +
344
      'tenantid=' + selectedTenant +
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'][index];
374
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates'][index] * 100).toFixed(2) + "%";
375
          cardSummaryItem['subtotal_per_unit_area'] = json['reporting_period']['subtotals_per_unit_area'][index];
376
          cardSummaryArray.push(cardSummaryItem);
377
        });
378
        setCardSummaryList(cardSummaryArray);
379
        
380
        let timeOfUseArray = [];
381
        json['reporting_period']['energy_category_ids'].forEach((currentValue, index) => {
382
          if(currentValue === 1) {
383
            // energy_category_id 1 electricity
384
            let timeOfUseItem = {}
385
            timeOfUseItem['id'] = 1;
386
            timeOfUseItem['name'] =  t('Top-Peak');
387
            timeOfUseItem['value'] = json['reporting_period']['toppeaks'][index];
388
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
389
            timeOfUseArray.push(timeOfUseItem);
390
            
391
            timeOfUseItem = {}
392
            timeOfUseItem['id'] = 2;
393
            timeOfUseItem['name'] =  t('On-Peak');
394
            timeOfUseItem['value'] = json['reporting_period']['onpeaks'][index];
395
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
396
            timeOfUseArray.push(timeOfUseItem);
397
398
            timeOfUseItem = {}
399
            timeOfUseItem['id'] = 3;
400
            timeOfUseItem['name'] =  t('Mid-Peak');
401
            timeOfUseItem['value'] = json['reporting_period']['midpeaks'][index];
402
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
403
            timeOfUseArray.push(timeOfUseItem);
404
405
            timeOfUseItem = {}
406
            timeOfUseItem['id'] = 4;
407
            timeOfUseItem['name'] =  t('Off-Peak');
408
            timeOfUseItem['value'] = json['reporting_period']['offpeaks'][index];
409
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
410
            timeOfUseArray.push(timeOfUseItem);
411
          }
412
        });
413
        setTimeOfUseShareData(timeOfUseArray);
414
415
        
416
        let totalInTCE = {}; 
417
        totalInTCE['value'] = json['reporting_period']['total_in_kgce'] / 1000; // convert from kg to t
418
        totalInTCE['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgce'] * 100).toFixed(2) + "%";
419
        totalInTCE['value_per_unit_area'] = json['reporting_period']['total_in_kgce_per_unit_area'] / 1000; // convert from kg to t
420
        setTotalInTCE(totalInTCE);
421
422
        let totalInTCO2E = {}; 
423
        totalInTCO2E['value'] = json['reporting_period']['total_in_kgco2e'] / 1000; // convert from kg to t
424
        totalInTCO2E['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgco2e'] * 100).toFixed(2) + "%";
425
        totalInTCO2E['value_per_unit_area'] = json['reporting_period']['total_in_kgco2e_per_unit_area'] / 1000; // convert from kg to t
426
        setTotalInTCO2E(totalInTCO2E);
427
428
        let TCEDataArray = [];
429
        json['reporting_period']['names'].forEach((currentValue, index) => {
430
          let TCEDataItem = {}
431
          TCEDataItem['id'] = index;
432
          TCEDataItem['name'] = currentValue;
433
          TCEDataItem['value'] = json['reporting_period']['subtotals_in_kgce'][index] / 1000; // convert from kg to t
434
          TCEDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
435
          TCEDataArray.push(TCEDataItem);
436
        });
437
        setTCEShareData(TCEDataArray);
438
439
        let TCO2EDataArray = [];
440
        json['reporting_period']['names'].forEach((currentValue, index) => {
441
          let TCO2EDataItem = {}
442
          TCO2EDataItem['id'] = index;
443
          TCO2EDataItem['name'] = currentValue;
444
          TCO2EDataItem['value'] = json['reporting_period']['subtotals_in_kgco2e'][index] / 1000; // convert from kg to t
445
          TCO2EDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
446
          TCO2EDataArray.push(TCO2EDataItem);
447
        });
448
        setTCO2EShareData(TCO2EDataArray);
449
450
        let base_timestamps = {}
451
        json['base_period']['timestamps'].forEach((currentValue, index) => {
452
          base_timestamps['a' + index] = currentValue;
453
        });
454
        setTenantBaseLabels(base_timestamps)
455
456
        let base_values = {}
457
        json['base_period']['values'].forEach((currentValue, index) => {
458
          base_values['a' + index] = currentValue;
459
        });
460
        setTenantBaseData(base_values)
461
462
        /*
463
        * Tip:
464
        *     base_names === reporting_names
465
        *     base_units === reporting_units
466
        * */
467
468
        let base_and_reporting_names = {}
469
        json['reporting_period']['names'].forEach((currentValue, index) => {
470
          base_and_reporting_names['a' + index] = currentValue;
471
        });
472
        setTenantBaseAndReportingNames(base_and_reporting_names)
473
474
        let base_and_reporting_units = {}
475
        json['reporting_period']['units'].forEach((currentValue, index) => {
476
          base_and_reporting_units['a' + index] = "("+currentValue+")";
477
        });
478
        setTenantBaseAndReportingUnits(base_and_reporting_units)
479
480
        let base_subtotals = {}
481
        json['base_period']['subtotals'].forEach((currentValue, index) => {
482
          base_subtotals['a' + index] = currentValue.toFixed(2);
483
        });
484
        setTenantBaseSubtotals(base_subtotals)
485
486
        let reporting_timestamps = {}
487
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
488
          reporting_timestamps['a' + index] = currentValue;
489
        });
490
        setTenantReportingLabels(reporting_timestamps);
491
492
        let reporting_values = {}
493
        json['reporting_period']['values'].forEach((currentValue, index) => {
494
          reporting_values['a' + index] = currentValue;
495
        });
496
        setTenantReportingData(reporting_values);
497
498
        let reporting_subtotals = {}
499
        json['reporting_period']['subtotals'].forEach((currentValue, index) => {
500
          reporting_subtotals['a' + index] = currentValue.toFixed(2);
501
        });
502
        setTenantReportingSubtotals(reporting_subtotals);
503
504
        let rates = {}
505
        json['reporting_period']['rates'].forEach((currentValue, index) => {
506
          let currentRate = Array();
507
          currentValue.forEach((rate) => {
508
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
509
          });
510
          rates['a' + index] = currentRate;
511
        });
512
        setTenantReportingRates(rates)
513
514
        let options = Array();
515
        json['reporting_period']['names'].forEach((currentValue, index) => {
516
          let unit = json['reporting_period']['units'][index];
517
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
518
        });
519
        setTenantReportingOptions(options);
520
521
        let timestamps = {}
522
        json['parameters']['timestamps'].forEach((currentValue, index) => {
523
          timestamps['a' + index] = currentValue;
524
        });
525
        setParameterLineChartLabels(timestamps);
526
527
        let values = {}
528
        json['parameters']['values'].forEach((currentValue, index) => {
529
          values['a' + index] = currentValue;
530
        });
531
        setParameterLineChartData(values);
532
      
533
        let names = Array();
534
        json['parameters']['names'].forEach((currentValue, index) => {
535
          
536
          names.push({ 'value': 'a' + index, 'label': currentValue });
537
        });
538
        setParameterLineChartOptions(names);
539
540
        if(!isBasePeriodTimestampExists(json['base_period'])) {
541
          let detailed_value_list = [];
542
          if (json['reporting_period']['timestamps'].length > 0) {
543
            json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
544
              let detailed_value = {};
545
              detailed_value['id'] = timestampIndex;
546
              detailed_value['startdatetime'] = currentTimestamp;
547
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
548
                detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values'][energyCategoryIndex][timestampIndex];
549
              });
550
              detailed_value_list.push(detailed_value);
551
            });
552
          }
553
          ;
554
555
          let detailed_value = {};
556
          detailed_value['id'] = detailed_value_list.length;
557
          detailed_value['startdatetime'] = t('Subtotal');
558
          json['reporting_period']['subtotals'].forEach((currentValue, index) => {
559
            detailed_value['a' + index] = currentValue;
560
          });
561
          detailed_value_list.push(detailed_value);
562
          setTimeout(() => {
563
            setDetailedDataTableData(detailed_value_list);
564
          }, 0)
565
566
          let detailed_column_list = [];
567
          detailed_column_list.push({
568
            dataField: 'startdatetime',
569
            text: t('Datetime'),
570
            sort: true
571
          })
572
          json['reporting_period']['names'].forEach((currentValue, index) => {
573
            let unit = json['reporting_period']['units'][index];
574
            detailed_column_list.push({
575
              dataField: 'a' + index,
576
              text: currentValue + ' (' + unit + ')',
577
              sort: true,
578
              formatter: function (decimalValue) {
579
                if (typeof decimalValue === 'number') {
580
                  return decimalValue.toFixed(2);
581
                } else {
582
                  return null;
583
                }
584
              }
585
            });
586
          });
587
          setDetailedDataTableColumns(detailed_column_list);
588
        }else {
589
          /*
590
          * Tip:
591
          *     json['base_period']['names'] ===  json['reporting_period']['names']
592
          *     json['base_period']['units'] ===  json['reporting_period']['units']
593
          * */
594
          let detailed_column_list = [];
595
          detailed_column_list.push({
596
            dataField: 'basePeriodDatetime',
597
            text: t('Base Period') + ' - ' + t('Datetime'),
598
            sort: true
599
          })
600
601
          json['base_period']['names'].forEach((currentValue, index) => {
602
            let unit = json['base_period']['units'][index];
603
            detailed_column_list.push({
604
              dataField: 'a' + index,
605
              text: t('Base Period') + ' - ' + currentValue + ' (' + unit + ')',
606
              sort: true,
607
              formatter: function (decimalValue) {
608
                if (typeof decimalValue === 'number') {
609
                  return decimalValue.toFixed(2);
610
                } else {
611
                  return null;
612
                }
613
              }
614
            })
615
          });
616
617
          detailed_column_list.push({
618
            dataField: 'reportingPeriodDatetime',
619
            text: t('Reporting Period') + ' - ' + t('Datetime'),
620
            sort: true
621
          })
622
623
          json['reporting_period']['names'].forEach((currentValue, index) => {
624
            let unit = json['reporting_period']['units'][index];
625
            detailed_column_list.push({
626
              dataField: 'b' + index,
627
              text: t('Reporting Period') + ' - ' + currentValue + ' (' + unit + ')',
628
              sort: true,
629
              formatter: function (decimalValue) {
630
                if (typeof decimalValue === 'number') {
631
                  return decimalValue.toFixed(2);
632
                } else {
633
                  return null;
634
                }
635
              }
636
            })
637
          });
638
          setDetailedDataTableColumns(detailed_column_list);
639
640
          let detailed_value_list = [];
641
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
642
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
643
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
644
            for (let index = 0; index < max_timestamps_length; index++) {
645
              let detailed_value = {};
646
              detailed_value['id'] = index;
647
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
648
              json['base_period']['values'].forEach((currentValue, energyCategoryIndex) => {
649
                detailed_value['a' + energyCategoryIndex] = index < json['base_period']['values'][energyCategoryIndex].length? json['base_period']['values'][energyCategoryIndex][index] : null;
650
              });
651
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
652
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
653
                detailed_value['b' + energyCategoryIndex] = index < json['reporting_period']['values'][energyCategoryIndex].length? json['reporting_period']['values'][energyCategoryIndex][index] : null;
654
              });
655
              detailed_value_list.push(detailed_value);
656
            }
657
658
            let detailed_value = {};
659
            detailed_value['id'] = detailed_value_list.length;
660
            detailed_value['basePeriodDatetime'] = t('Subtotal');
661
            json['base_period']['subtotals'].forEach((currentValue, index) => {
662
              detailed_value['a' + index] = currentValue;
663
            });
664
            detailed_value['reportingPeriodDatetime'] = t('Subtotal');
665
            json['reporting_period']['subtotals'].forEach((currentValue, index) => {
666
              detailed_value['b' + index] = currentValue;
667
            });
668
            detailed_value_list.push(detailed_value);
669
            setTimeout( () => {
670
              setDetailedDataTableData(detailed_value_list);
671
            }, 0)
672
          }
673
674
        }
675
        
676
        setExcelBytesBase64(json['excel_bytes_base64']);
677
678
        // enable submit button
679
        setSubmitButtonDisabled(false);
680
        // hide spinner
681
        setSpinnerHidden(true);
682
        // show export button
683
        setExportButtonHidden(false);
684
685
      } else {
686
        toast.error(t(json.description))
687
      }
688
    }).catch(err => {
689
      console.log(err);
690
    });
691
  };
692
693
  const handleExport = e => {
694
    e.preventDefault();
695
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
696
    const fileName = 'tenantenergycategory.xlsx'
697
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
698
    fetch(fileUrl)
699
        .then(response => response.blob())
700
        .then(blob => {
701
            var link = window.document.createElement("a");
702
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
703
            link.download = fileName;
704
            document.body.appendChild(link);
705
            link.click();
706
            document.body.removeChild(link);
707
        });
708
  };
709
710
  return (
711
    <Fragment>
712
      <div>
713
        <Breadcrumb>
714
          <BreadcrumbItem>{t('Tenant Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Energy Category Data')}</BreadcrumbItem>
715
        </Breadcrumb>
716
      </div>
717
      <Card className="bg-light mb-3">
718
        <CardBody className="p-3">
719
          <Form onSubmit={handleSubmit}>
720
            <Row form>
721
              <Col xs={6} sm={3}>
722
                <FormGroup className="form-group">
723
                  <Label className={labelClasses} for="space">
724
                    {t('Space')}
725
                  </Label>
726
                  <br />
727
                  <Cascader options={cascaderOptions}
728
                    onChange={onSpaceCascaderChange}
729
                    changeOnSelect
730
                    expandTrigger="hover">
731
                    <Input value={selectedSpaceName || ''} readOnly />
732
                  </Cascader>
733
                </FormGroup>
734
              </Col>
735
              <Col xs="auto">
736
                <FormGroup>
737
                  <Label className={labelClasses} for="tenantSelect">
738
                    {t('Tenant')}
739
                  </Label>
740
                  <CustomInput type="select" id="tenantSelect" name="tenantSelect" onChange={({ target }) => setSelectedTenant(target.value)}
741
                  >
742
                    {tenantList.map((tenant, index) => (
743
                      <option value={tenant.value} key={tenant.value}>
744
                        {tenant.label}
745
                      </option>
746
                    ))}
747
                  </CustomInput>
748
                </FormGroup>
749
              </Col>
750
              <Col xs="auto">
751
                <FormGroup>
752
                  <Label className={labelClasses} for="comparisonType">
753
                    {t('Comparison Types')}
754
                  </Label>
755
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
756
                    defaultValue="month-on-month"
757
                    onChange={onComparisonTypeChange}
758
                  >
759
                    {comparisonTypeOptions.map((comparisonType, index) => (
760
                      <option value={comparisonType.value} key={comparisonType.value} >
761
                        {t(comparisonType.label)}
762
                      </option>
763
                    ))}
764
                  </CustomInput>
765
                </FormGroup>
766
              </Col>
767
              <Col xs="auto">
768
                <FormGroup>
769
                  <Label className={labelClasses} for="periodType">
770
                    {t('Period Types')}
771
                  </Label>
772
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
773
                  >
774
                    {periodTypeOptions.map((periodType, index) => (
775
                      <option value={periodType.value} key={periodType.value} >
776
                        {t(periodType.label)}
777
                      </option>
778
                    ))}
779
                  </CustomInput>
780
                </FormGroup>
781
              </Col>
782
              <Col xs={6} sm={3}>
783
                <FormGroup className="form-group">
784
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
785
                  <DateRangePickerWrapper 
786
                    id='basePeriodDateRangePicker'
787
                    disabled={basePeriodDateRangePickerDisabled}
788
                    format="yyyy-MM-dd HH:mm:ss"
789
                    value={basePeriodDateRange}
790
                    onChange={onBasePeriodChange}
791
                    size="md"
792
                    style={dateRangePickerStyle}
793
                    onClean={onBasePeriodClean}
794
                    locale={dateRangePickerLocale}
795
                    placeholder={t("Select Date Range")}
796
                   />
797
                </FormGroup>
798
              </Col>
799
              <Col xs={6} sm={3}>
800
                <FormGroup className="form-group">
801
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
802
                  <br/>
803
                  <DateRangePickerWrapper
804
                    id='reportingPeriodDateRangePicker'
805
                    format="yyyy-MM-dd HH:mm:ss"
806
                    value={reportingPeriodDateRange}
807
                    onChange={onReportingPeriodChange}
808
                    size="md"
809
                    style={dateRangePickerStyle}
810
                    onClean={onReportingPeriodClean}
811
                    locale={dateRangePickerLocale}
812
                    placeholder={t("Select Date Range")}
813
                  />
814
                </FormGroup>
815
              </Col>
816
              <Col xs="auto">
817
                <FormGroup>
818
                  <br></br>
819
                  <ButtonGroup id="submit">
820
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
821
                  </ButtonGroup>
822
                </FormGroup>
823
              </Col>
824
              <Col xs="auto">
825
                <FormGroup>
826
                  <br></br>
827
                  <Spinner color="primary" hidden={spinnerHidden}  />
828
                </FormGroup>
829
              </Col>
830
              <Col xs="auto">
831
                  <br></br>
832
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
833
                  hidden={exportButtonHidden}
834
                  onClick={handleExport} >
835
                    {t('Export')}
836
                  </ButtonIcon>
837
              </Col>
838
            </Row>
839
          </Form>
840
        </CardBody>
841
      </Card>
842
      <div className="card-deck">
843
        {cardSummaryList.map(cardSummaryItem => (
844
          <CardSummary key={cardSummaryItem['name']}
845
            rate={cardSummaryItem['increment_rate']}
846
            title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
847
            color="success" 
848
            footnote={t('Per Unit Area')} 
849
            footvalue={cardSummaryItem['subtotal_per_unit_area']}
850
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
851
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
852
          </CardSummary>
853
        ))}
854
       
855
        <CardSummary 
856
          rate={totalInTCE['increment_rate'] || ''} 
857
          title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': t('Ton of Standard Coal'), 'UNIT': '(TCE)' })}
858
          color="warning" 
859
          footnote={t('Per Unit Area')} 
860
          footvalue={totalInTCE['value_per_unit_area']} 
861
          footunit="(TCE/M²)">
862
          {totalInTCE['value'] && <CountUp end={totalInTCE['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
863
        </CardSummary>
864
        <CardSummary 
865
          rate={totalInTCO2E['increment_rate'] || ''} 
866
          title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': t('Ton of Carbon Dioxide Emissions'), 'UNIT': '(TCO2E)' })}
867
          color="warning" 
868
          footnote={t('Per Unit Area')} 
869
          footvalue={totalInTCO2E['value_per_unit_area']} 
870
          footunit="(TCO2E/M²)">
871
          {totalInTCO2E['value'] && <CountUp end={totalInTCO2E['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
872
        </CardSummary>
873
      </div>
874
      <Row noGutters>
875
        <Col className="mb-3 pr-lg-2 mb-3">
876
          <SharePie data={timeOfUseShareData} title={t('Electricity Consumption by Time-Of-Use')} />
877
        </Col>
878
        <Col className="mb-3 pr-lg-2 mb-3">
879
          <SharePie data={TCEShareData} title={t('Ton of Standard Coal by Energy Category')} />
880
        </Col>
881
        <Col className="mb-3 pr-lg-2 mb-3">
882
          <SharePie data={TCO2EShareData} title={t('Ton of Carbon Dioxide Emissions by Energy Category')} />
883
        </Col>
884
      </Row>
885
886
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": tenantBaseAndReportingNames, "VALUE": tenantReportingSubtotals, "UNIT": tenantBaseAndReportingUnits}}
887
        baseTitle = {{"name": "Base Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": tenantBaseAndReportingNames, "VALUE": tenantBaseSubtotals, "UNIT": tenantBaseAndReportingUnits}}
888
        reportingTooltipTitle = {{"name": "Reporting Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": tenantBaseAndReportingNames, "VALUE": null, "UNIT": tenantBaseAndReportingUnits}}
889
        baseTooltipTitle = {{"name": "Base Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": tenantBaseAndReportingNames, "VALUE": null, "UNIT": tenantBaseAndReportingUnits}}
890
        reportingLabels={tenantReportingLabels}
891
        reportingData={tenantReportingData}
892
        baseLabels={tenantBaseLabels}
893
        baseData={tenantBaseData}
894
        rates={tenantReportingRates}
895
        options={tenantReportingOptions}>
896
      </MultiTrendChart>
897
898
      <MultipleLineChart reportingTitle={t('Related Parameters')}
899
        baseTitle=''
900
        labels={parameterLineChartLabels}
901
        data={parameterLineChartData}
902
        options={parameterLineChartOptions}>
903
      </MultipleLineChart>
904
      <br />
905
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
906
      </DetailedDataTable>
907
908
    </Fragment>
909
  );
910
};
911
912
export default withTranslation()(withRedirect(TenantEnergyCategory));
913