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

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

Complexity

Total Complexity 44
Complexity/F 0

Size

Lines of Code 853
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 44
eloc 721
dl 0
loc 853
rs 8.759
c 0
b 0
f 0
mnd 44
bc 44
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

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