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

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

Complexity

Total Complexity 48
Complexity/F 0

Size

Lines of Code 861
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

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