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

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

Complexity

Total Complexity 41
Complexity/F 0

Size

Lines of Code 872
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 41
eloc 746
dl 0
loc 872
rs 8.974
c 0
b 0
f 0
mnd 41
bc 41
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/Tenant/TenantSaving.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
41
const TenantSaving = ({ setRedirect, setRedirectUrl, t }) => {
42
  let current_moment = moment();
43
  useEffect(() => {
44
    let is_logged_in = getCookieValue('is_logged_in');
45
    let user_name = getCookieValue('user_name');
46
    let user_display_name = getCookieValue('user_display_name');
47
    let user_uuid = getCookieValue('user_uuid');
48
    let token = getCookieValue('token');
49
    if (is_logged_in === null || !is_logged_in) {
50
      setRedirectUrl(`/authentication/basic/login`);
51
      setRedirect(true);
52
    } else {
53
      //update expires time of cookies
54
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
55
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
56
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
57
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
58
      createCookie('token', token, 1000 * 60 * 60 * 8);
59
    }
60
  });
61
62
63
  // State
64
  // Query Parameters
65
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
66
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
67
  const [tenantList, setTenantList] = useState([]);
68
  const [selectedTenant, setSelectedTenant] = useState(undefined);
69
  const [comparisonType, setComparisonType] = useState('month-on-month');
70
  const [periodType, setPeriodType] = useState('daily');
71
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
72
  const [basePeriodDateRange, setBasePeriodDateRange] = useState([current_moment.clone().subtract(1, 'months').startOf('month').toDate(), current_moment.clone().subtract(1, 'months').toDate()]);
73
  const [basePeriodDateRangePickerDisabled, setBasePeriodDateRangePickerDisabled] = useState(true);
74
  const [reportingPeriodDateRange, setReportingPeriodDateRange] = useState([current_moment.clone().startOf('month').toDate(), current_moment.toDate()]);
75
  const dateRangePickerLocale = {
76
    sunday: t('sunday'),
77
    monday: t('monday'),
78
    tuesday: t('tuesday'),
79
    wednesday: t('wednesday'),
80
    thursday: t('thursday'),
81
    friday: t('friday'),
82
    saturday: t('saturday'),
83
    ok: t('ok'),
84
    today: t('today'),
85
    yesterday: t('yesterday'),
86
    hours: t('hours'),
87
    minutes: t('minutes'),
88
    seconds: t('seconds'),
89
    last7Days: t('last7Days'),
90
    formattedMonthPattern: 'yyyy-MM-dd'
91
  };
92
  const dateRangePickerStyle = { display: 'block', zIndex: 10};
93
  const { language } = useContext(AppContext);
94
95
  // buttons
96
  const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
97
  const [spinnerHidden, setSpinnerHidden] = useState(true);
98
  const [exportButtonHidden, setExportButtonHidden] = useState(true);
99
100
  //Results
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/tenantsaving?' +
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_saving'][index];
374
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates_saving'][index] * 100).toFixed(2) + "%";
375
          cardSummaryItem['subtotal_per_unit_area'] = json['reporting_period']['subtotals_per_unit_area_saving'][index];
376
          cardSummaryArray.push(cardSummaryItem);
377
        });
378
        setCardSummaryList(cardSummaryArray);
379
380
        let totalInTCE = {}; 
381
        totalInTCE['value'] = json['reporting_period']['total_in_kgce_saving'] / 1000; // convert from kg to t
382
        totalInTCE['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgce_saving'] * 100).toFixed(2) + "%";
383
        totalInTCE['value_per_unit_area'] = json['reporting_period']['total_in_kgce_per_unit_area_saving'] / 1000; // convert from kg to t
384
        setTotalInTCE(totalInTCE);
385
386
        let totalInTCO2E = {}; 
387
        totalInTCO2E['value'] = json['reporting_period']['total_in_kgco2e_saving'] / 1000; // convert from kg to t
388
        totalInTCO2E['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgco2e_saving'] * 100).toFixed(2) + "%";
389
        totalInTCO2E['value_per_unit_area'] = json['reporting_period']['total_in_kgco2e_per_unit_area_saving'] / 1000; // convert from kg to t
390
        setTotalInTCO2E(totalInTCO2E);
391
392
        let TCEDataArray = [];
393
        json['reporting_period']['names'].forEach((currentValue, index) => {
394
          let TCEDataItem = {}
395
          TCEDataItem['id'] = index;
396
          TCEDataItem['name'] = currentValue;
397
          TCEDataItem['value'] = json['reporting_period']['subtotals_in_kgce_saving'][index] / 1000; // convert from kg to t
398
          TCEDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
399
          TCEDataArray.push(TCEDataItem);
400
        });
401
        setTCEShareData(TCEDataArray);
402
403
        let TCO2EDataArray = [];
404
        json['reporting_period']['names'].forEach((currentValue, index) => {
405
          let TCO2EDataItem = {}
406
          TCO2EDataItem['id'] = index;
407
          TCO2EDataItem['name'] = currentValue;
408
          TCO2EDataItem['value'] = json['reporting_period']['subtotals_in_kgco2e_saving'][index] / 1000; // convert from kg to t
409
          TCO2EDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
410
          TCO2EDataArray.push(TCO2EDataItem);
411
        });
412
        setTCO2EShareData(TCO2EDataArray);
413
414
        let base_timestamps = {}
415
        json['base_period']['timestamps'].forEach((currentValue, index) => {
416
          base_timestamps['a' + index] = currentValue;
417
        });
418
        setTenantBaseLabels(base_timestamps)
419
420
        let base_values = {}
421
        json['base_period']['values_saving'].forEach((currentValue, index) => {
422
          base_values['a' + index] = currentValue;
423
        });
424
        setTenantBaseData(base_values)
425
426
        /*
427
        * Tip:
428
        *     base_names === reporting_names
429
        *     base_units === reporting_units
430
        * */
431
432
        let base_and_reporting_names = {}
433
        json['reporting_period']['names'].forEach((currentValue, index) => {
434
          base_and_reporting_names['a' + index] = currentValue;
435
        });
436
        setTenantBaseAndReportingNames(base_and_reporting_names)
437
438
        let base_and_reporting_units = {}
439
        json['reporting_period']['units'].forEach((currentValue, index) => {
440
          base_and_reporting_units['a' + index] = "("+currentValue+")";
441
        });
442
        setTenantBaseAndReportingUnits(base_and_reporting_units)
443
444
        let base_subtotals = {}
445
        json['base_period']['subtotals_saving'].forEach((currentValue, index) => {
446
          base_subtotals['a' + index] = currentValue.toFixed(2);
447
        });
448
        setTenantBaseSubtotals(base_subtotals)
449
450
        let reporting_timestamps = {}
451
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
452
          reporting_timestamps['a' + index] = currentValue;
453
        });
454
        setTenantReportingLabels(reporting_timestamps);
455
456
        let reporting_values = {}
457
        json['reporting_period']['values_saving'].forEach((currentValue, index) => {
458
          reporting_values['a' + index] = currentValue;
459
        });
460
        setTenantReportingData(reporting_values);
461
462
        let reporting_subtotals = {}
463
        json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
464
          reporting_subtotals['a' + index] = currentValue.toFixed(2);
465
        });
466
        setTenantReportingSubtotals(reporting_subtotals);
467
468
        let rates = {}
469
        json['reporting_period']['rates_saving'].forEach((currentValue, index) => {
470
          let currentRate = Array();
471
          currentValue.forEach((rate) => {
472
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
473
          });
474
          rates['a' + index] = currentRate;
475
        });
476
        setTenantReportingRates(rates)
477
478
        let options = Array();
479
        json['reporting_period']['names'].forEach((currentValue, index) => {
480
          let unit = json['reporting_period']['units'][index];
481
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
482
        });
483
        setTenantReportingOptions(options);
484
       
485
        let timestamps = {}
486
        json['parameters']['timestamps'].forEach((currentValue, index) => {
487
          timestamps['a' + index] = currentValue;
488
        });
489
        setParameterLineChartLabels(timestamps);
490
491
        let values = {}
492
        json['parameters']['values'].forEach((currentValue, index) => {
493
          values['a' + index] = currentValue;
494
        });
495
        setParameterLineChartData(values);
496
      
497
        let names = Array();
498
        json['parameters']['names'].forEach((currentValue, index) => {
499
          
500
          names.push({ 'value': 'a' + index, 'label': currentValue });
501
        });
502
        setParameterLineChartOptions(names);
503
504
        let detailed_value_list = [];
505
        if (json['reporting_period']['timestamps'].length > 0) {
506
          json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
507
            let detailed_value = {};
508
            detailed_value['id'] = timestampIndex;
509
            detailed_value['startdatetime'] = currentTimestamp;
510
            json['reporting_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
511
              detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values_saving'][energyCategoryIndex][timestampIndex];
512
            });
513
            detailed_value_list.push(detailed_value);
514
          });
515
        };
516
517
        if(!isBasePeriodTimestampExists(json['base_period'])) {
518
          let detailed_value = {};
519
          detailed_value['id'] = detailed_value_list.length;
520
          detailed_value['startdatetime'] = t('Subtotal');
521
          json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
522
            detailed_value['a' + index] = currentValue;
523
          });
524
          detailed_value_list.push(detailed_value);
525
          setTimeout(() => {
526
            setDetailedDataTableData(detailed_value_list);
527
          }, 0)
528
529
          let detailed_column_list = [];
530
          detailed_column_list.push({
531
            dataField: 'startdatetime',
532
            text: t('Datetime'),
533
            sort: true
534
          })
535
          json['reporting_period']['names'].forEach((currentValue, index) => {
536
            let unit = json['reporting_period']['units'][index];
537
            detailed_column_list.push({
538
              dataField: 'a' + index,
539
              text: currentValue + ' (' + unit + ')',
540
              sort: true,
541
              formatter: function (decimalValue) {
542
                if (typeof decimalValue === 'number') {
543
                  return decimalValue.toFixed(2);
544
                } else {
545
                  return null;
546
                }
547
              }
548
            });
549
          });
550
          setDetailedDataTableColumns(detailed_column_list);
551
        }else {
552
          /*
553
          * Tip:
554
          *     json['base_period']['names'] ===  json['reporting_period']['names']
555
          *     json['base_period']['units'] ===  json['reporting_period']['units']
556
          * */
557
          let detailed_column_list = [];
558
          detailed_column_list.push({
559
            dataField: 'basePeriodDatetime',
560
            text: t('Base Period') + ' - ' + t('Datetime'),
561
            sort: true
562
          })
563
564
          json['base_period']['names'].forEach((currentValue, index) => {
565
            let unit = json['base_period']['units'][index];
566
            detailed_column_list.push({
567
              dataField: 'a' + index,
568
              text: t('Base Period') + ' - ' + currentValue + ' (' + unit + ')',
569
              sort: true,
570
              formatter: function (decimalValue) {
571
                if (typeof decimalValue === 'number') {
572
                  return decimalValue.toFixed(2);
573
                } else {
574
                  return null;
575
                }
576
              }
577
            })
578
          });
579
580
          detailed_column_list.push({
581
            dataField: 'reportingPeriodDatetime',
582
            text: t('Reporting Period') + ' - ' + t('Datetime'),
583
            sort: true
584
          })
585
586
          json['reporting_period']['names'].forEach((currentValue, index) => {
587
            let unit = json['reporting_period']['units'][index];
588
            detailed_column_list.push({
589
              dataField: 'b' + index,
590
              text: t('Reporting Period') + ' - ' + currentValue + ' (' + unit + ')',
591
              sort: true,
592
              formatter: function (decimalValue) {
593
                if (typeof decimalValue === 'number') {
594
                  return decimalValue.toFixed(2);
595
                } else {
596
                  return null;
597
                }
598
              }
599
            })
600
          });
601
          setDetailedDataTableColumns(detailed_column_list);
602
603
          let detailed_value_list = [];
604
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
605
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
606
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
607
            for (let index = 0; index < max_timestamps_length; index++) {
608
              let detailed_value = {};
609
              detailed_value['id'] = index;
610
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
611
              json['base_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
612
                detailed_value['a' + energyCategoryIndex] = index < json['base_period']['values_saving'][energyCategoryIndex].length? json['base_period']['values_saving'][energyCategoryIndex][index] : null;
613
              });
614
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
615
              json['reporting_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
616
                detailed_value['b' + energyCategoryIndex] = index < json['reporting_period']['values_saving'][energyCategoryIndex].length? json['reporting_period']['values_saving'][energyCategoryIndex][index] : null;
617
              });
618
              detailed_value_list.push(detailed_value);
619
            }
620
621
            let detailed_value = {};
622
            detailed_value['id'] = detailed_value_list.length;
623
            detailed_value['basePeriodDatetime'] = t('Subtotal');
624
            json['base_period']['subtotals_saving'].forEach((currentValue, index) => {
625
              detailed_value['a' + index] = currentValue;
626
            });
627
            detailed_value['reportingPeriodDatetime'] = t('Subtotal');
628
            json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
629
              detailed_value['b' + index] = currentValue;
630
            });
631
            detailed_value_list.push(detailed_value);
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 = 'tenantsaving.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('Saving')}</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
      <div className="card-deck">
805
        {cardSummaryList.map(cardSummaryItem => (
806
          <CardSummary key={cardSummaryItem['name']}
807
            rate={cardSummaryItem['increment_rate']}
808
            title={t('Reporting Period Saving CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
809
            color="success" 
810
            footnote={t('Per Unit Area')} 
811
            footvalue={cardSummaryItem['subtotal_per_unit_area']}
812
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
813
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
814
          </CardSummary>
815
        ))}
816
       
817
        <CardSummary 
818
          rate={totalInTCE['increment_rate'] || ''} 
819
          title={t('Reporting Period Saving CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Standard Coal'), 'UNIT': '(TCE)' })}
820
          color="warning" 
821
          footnote={t('Per Unit Area')} 
822
          footvalue={totalInTCE['value_per_unit_area']} 
823
          footunit="(TCE/M²)">
824
          {totalInTCE['value'] && <CountUp end={totalInTCE['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
825
        </CardSummary>
826
        <CardSummary 
827
          rate={totalInTCO2E['increment_rate'] || ''} 
828
          title={t('Reporting Period Decreased CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Carbon Dioxide Emissions'), 'UNIT': '(TCO2E)' })}
829
          color="warning" 
830
          footnote={t('Per Unit Area')} 
831
          footvalue={totalInTCO2E['value_per_unit_area']} 
832
          footunit="(TCO2E/M²)">
833
          {totalInTCO2E['value'] && <CountUp end={totalInTCO2E['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
834
        </CardSummary>
835
      </div>
836
      <Row noGutters>
837
        <Col className="mb-3 pr-lg-2 mb-3">
838
          <SharePie data={TCEShareData} title={t('Ton of Standard Coal by Energy Category')} />
839
        </Col>
840
        <Col className="mb-3 pr-lg-2 mb-3">
841
          <SharePie data={TCO2EShareData} title={t('Ton of Carbon Dioxide Emissions by Energy Category')} />
842
        </Col>
843
      </Row>
844
845
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": tenantBaseAndReportingNames, "VALUE": tenantReportingSubtotals, "UNIT": tenantBaseAndReportingUnits}}
846
        baseTitle = {{"name": "Base Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": tenantBaseAndReportingNames, "VALUE": tenantBaseSubtotals, "UNIT": tenantBaseAndReportingUnits}}
847
        reportingTooltipTitle = {{"name": "Reporting Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": tenantBaseAndReportingNames, "VALUE": null, "UNIT": tenantBaseAndReportingUnits}}
848
        baseTooltipTitle = {{"name": "Base Period Saving CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": tenantBaseAndReportingNames, "VALUE": null, "UNIT": tenantBaseAndReportingUnits}}
849
        reportingLabels={tenantReportingLabels}
850
        reportingData={tenantReportingData}
851
        baseLabels={tenantBaseLabels}
852
        baseData={tenantBaseData}
853
        rates={tenantReportingRates}
854
        options={tenantReportingOptions}>
855
      </MultiTrendChart>
856
857
      <MultipleLineChart reportingTitle={t('Related Parameters')}
858
        baseTitle=''
859
        labels={parameterLineChartLabels}
860
        data={parameterLineChartData}
861
        options={parameterLineChartOptions}>
862
      </MultipleLineChart>
863
      <br />
864
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
865
      </DetailedDataTable>
866
867
    </Fragment>
868
  );
869
};
870
871
export default withTranslation()(withRedirect(TenantSaving));
872