src/components/MyEMS/CombinedEquipment/CombinedEquipmentEnergyCategory.js   A
last analyzed

Complexity

Total Complexity 26
Complexity/F 0

Size

Lines of Code 725
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 26
eloc 643
mnd 26
bc 26
fnc 0
dl 0
loc 725
rs 9.957
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import React, { Fragment, useEffect, useState } 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 Datetime from 'react-datetime';
20
import moment from 'moment';
21
import loadable from '@loadable/component';
22
import Cascader from 'rc-cascader';
23
import CardSummary from '../common/CardSummary';
24
import LineChart from '../common/LineChart';
25
import SharePie from '../common/SharePie';
26
import { getCookieValue, createCookie } from '../../../helpers/utils';
27
import withRedirect from '../../../hoc/withRedirect';
28
import { withTranslation } from 'react-i18next';
29
import { periodTypeOptions } from '../common/PeriodTypeOptions';
30
import { comparisonTypeOptions } from '../common/ComparisonTypeOptions';
31
import { toast } from 'react-toastify';
32
import ButtonIcon from '../../common/ButtonIcon';
33
import { APIBaseURL } from '../../../config';
34
35
36
const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
37
38
const CombinedEquipmentEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
39
  let current_moment = moment();
40
  useEffect(() => {
41
    let is_logged_in = getCookieValue('is_logged_in');
42
    let user_name = getCookieValue('user_name');
43
    let user_display_name = getCookieValue('user_display_name');
44
    let user_uuid = getCookieValue('user_uuid');
45
    let token = getCookieValue('token');
46
    if (is_logged_in === null || !is_logged_in) {
47
      setRedirectUrl(`/authentication/basic/login`);
48
      setRedirect(true);
49
    } else {
50
      //update expires time of cookies
51
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
52
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
53
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
54
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
55
      createCookie('token', token, 1000 * 60 * 60 * 8);
56
    }
57
  });
58
  // State
59
  // Query Parameters
60
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
61
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
62
  const [combinedEquipmentList, setCombinedEquipmentList] = useState([]);
63
  const [selectedCombinedEquipment, setSelectedCombinedEquipment] = useState(undefined);
64
  const [comparisonType, setComparisonType] = useState('month-on-month');
65
  const [periodType, setPeriodType] = useState('daily');
66
  const [basePeriodBeginsDatetime, setBasePeriodBeginsDatetime] = useState(current_moment.clone().subtract(1, 'months').startOf('month'));
67
  const [basePeriodEndsDatetime, setBasePeriodEndsDatetime] = useState(current_moment.clone().subtract(1, 'months'));
68
  const [basePeriodBeginsDatetimeDisabled, setBasePeriodBeginsDatetimeDisabled] = useState(true);
69
  const [basePeriodEndsDatetimeDisabled, setBasePeriodEndsDatetimeDisabled] = useState(true);
70
  const [reportingPeriodBeginsDatetime, setReportingPeriodBeginsDatetime] = useState(current_moment.clone().startOf('month'));
71
  const [reportingPeriodEndsDatetime, setReportingPeriodEndsDatetime] = useState(current_moment);
72
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
73
74
  // buttons
75
  const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
76
  const [spinnerHidden, setSpinnerHidden] = useState(true);
77
  const [exportButtonHidden, setExportButtonHidden] = useState(true);
78
  
79
  //Results
80
  const [timeOfUseShareData, setTimeOfUseShareData] = useState([]);
81
  const [TCEShareData, setTCEShareData] = useState([]);
82
  const [TCO2EShareData, setTCO2EShareData] = useState([]);
83
84
  const [cardSummaryList, setCardSummaryList] = useState([]);
85
  const [totalInTCE, setTotalInTCE] = useState({});
86
  const [totalInTCO2E, setTotalInTCO2E] = useState({});
87
  const [combinedEquipmentLineChartLabels, setCombinedEquipmentLineChartLabels] = useState([]);
88
  const [combinedEquipmentLineChartData, setCombinedEquipmentLineChartData] = useState({});
89
  const [combinedEquipmentLineChartOptions, setCombinedEquipmentLineChartOptions] = useState([]);
90
91
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
92
  const [parameterLineChartData, setParameterLineChartData] = useState({});
93
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
94
95
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
96
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
97
  const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
98
  
99
  useEffect(() => {
100
    let isResponseOK = false;
101
    fetch(APIBaseURL + '/spaces/tree', {
102
      method: 'GET',
103
      headers: {
104
        "Content-type": "application/json",
105
        "User-UUID": getCookieValue('user_uuid'),
106
        "Token": getCookieValue('token')
107
      },
108
      body: null,
109
110
    }).then(response => {
111
      console.log(response)
112
      if (response.ok) {
113
        isResponseOK = true;
114
      }
115
      return response.json();
116
    }).then(json => {
117
      console.log(json)
118
      if (isResponseOK) {
119
        // rename keys 
120
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
121
        setCascaderOptions(json);
122
        setSelectedSpaceName([json[0]].map(o => o.label));
123
        setSelectedSpaceID([json[0]].map(o => o.value));
124
        // get Combined Equipments by root Space ID
125
        let isResponseOK = false;
126
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/combinedequipments', {
127
          method: 'GET',
128
          headers: {
129
            "Content-type": "application/json",
130
            "User-UUID": getCookieValue('user_uuid'),
131
            "Token": getCookieValue('token')
132
          },
133
          body: null,
134
135
        }).then(response => {
136
          if (response.ok) {
137
            isResponseOK = true;
138
          }
139
          return response.json();
140
        }).then(json => {
141
          if (isResponseOK) {
142
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
143
            console.log(json);
144
            setCombinedEquipmentList(json[0]);
145
            if (json[0].length > 0) {
146
              setSelectedCombinedEquipment(json[0][0].value);
147
              // enable submit button
148
              setSubmitButtonDisabled(false);
149
            } else {
150
              setSelectedCombinedEquipment(undefined);
151
              // disable submit button
152
              setSubmitButtonDisabled(true);
153
            }
154
          } else {
155
            toast.error(json.description)
156
          }
157
        }).catch(err => {
158
          console.log(err);
159
        });
160
        // end of get Combined Equipments by root Space ID
161
      } else {
162
        toast.error(json.description)
163
      }
164
    }).catch(err => {
165
      console.log(err);
166
    });
167
168
  }, []);
169
170
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
171
172
  let onSpaceCascaderChange = (value, selectedOptions) => {
173
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
174
    setSelectedSpaceID(value[value.length - 1]);
175
176
    let isResponseOK = false;
177
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/combinedequipments', {
178
      method: 'GET',
179
      headers: {
180
        "Content-type": "application/json",
181
        "User-UUID": getCookieValue('user_uuid'),
182
        "Token": getCookieValue('token')
183
      },
184
      body: null,
185
186
    }).then(response => {
187
      if (response.ok) {
188
        isResponseOK = true;
189
      }
190
      return response.json();
191
    }).then(json => {
192
      if (isResponseOK) {
193
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
194
        console.log(json)
195
        setCombinedEquipmentList(json[0]);
196
        if (json[0].length > 0) {
197
          setSelectedCombinedEquipment(json[0][0].value);
198
          // enable submit button
199
          setSubmitButtonDisabled(false);
200
        } else {
201
          setSelectedCombinedEquipment(undefined);
202
          // disable submit button
203
          setSubmitButtonDisabled(true);
204
        }
205
      } else {
206
        toast.error(json.description)
207
      }
208
    }).catch(err => {
209
      console.log(err);
210
    });
211
  }
212
213
214
  let onComparisonTypeChange = ({ target }) => {
215
    console.log(target.value);
216
    setComparisonType(target.value);
217
    if (target.value === 'year-over-year') {
218
      setBasePeriodBeginsDatetimeDisabled(true);
219
      setBasePeriodEndsDatetimeDisabled(true);
220
      setBasePeriodBeginsDatetime(moment(reportingPeriodBeginsDatetime).subtract(1, 'years'));
221
      setBasePeriodEndsDatetime(moment(reportingPeriodEndsDatetime).subtract(1, 'years'));
222
    } else if (target.value === 'month-on-month') {
223
      setBasePeriodBeginsDatetimeDisabled(true);
224
      setBasePeriodEndsDatetimeDisabled(true);
225
      setBasePeriodBeginsDatetime(moment(reportingPeriodBeginsDatetime).subtract(1, 'months'));
226
      setBasePeriodEndsDatetime(moment(reportingPeriodEndsDatetime).subtract(1, 'months'));
227
    } else if (target.value === 'free-comparison') {
228
      setBasePeriodBeginsDatetimeDisabled(false);
229
      setBasePeriodEndsDatetimeDisabled(false);
230
    } else if (target.value === 'none-comparison') {
231
      setBasePeriodBeginsDatetime(undefined);
232
      setBasePeriodEndsDatetime(undefined);
233
      setBasePeriodBeginsDatetimeDisabled(true);
234
      setBasePeriodEndsDatetimeDisabled(true);
235
    }
236
  }
237
238
  let onBasePeriodBeginsDatetimeChange = (newDateTime) => {
239
    setBasePeriodBeginsDatetime(newDateTime);
240
  }
241
242
  let onBasePeriodEndsDatetimeChange = (newDateTime) => {
243
    setBasePeriodEndsDatetime(newDateTime);
244
  }
245
246
  let onReportingPeriodBeginsDatetimeChange = (newDateTime) => {
247
    setReportingPeriodBeginsDatetime(newDateTime);
248
    if (comparisonType === 'year-over-year') {
249
      setBasePeriodBeginsDatetime(newDateTime.clone().subtract(1, 'years'));
250
    } else if (comparisonType === 'month-on-month') {
251
      setBasePeriodBeginsDatetime(newDateTime.clone().subtract(1, 'months'));
252
    }
253
  }
254
255
  let onReportingPeriodEndsDatetimeChange = (newDateTime) => {
256
    setReportingPeriodEndsDatetime(newDateTime);
257
    if (comparisonType === 'year-over-year') {
258
      setBasePeriodEndsDatetime(newDateTime.clone().subtract(1, 'years'));
259
    } else if (comparisonType === 'month-on-month') {
260
      setBasePeriodEndsDatetime(newDateTime.clone().subtract(1, 'months'));
261
    }
262
  }
263
264
  var getValidBasePeriodBeginsDatetimes = function (currentDate) {
265
    return currentDate.isBefore(moment(basePeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
266
  }
267
268
  var getValidBasePeriodEndsDatetimes = function (currentDate) {
269
    return currentDate.isAfter(moment(basePeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
270
  }
271
272
  var getValidReportingPeriodBeginsDatetimes = function (currentDate) {
273
    return currentDate.isBefore(moment(reportingPeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
274
  }
275
276
  var getValidReportingPeriodEndsDatetimes = function (currentDate) {
277
    return currentDate.isAfter(moment(reportingPeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
278
  }
279
280
  // Handler
281
  const handleSubmit = e => {
282
    e.preventDefault();
283
    console.log('handleSubmit');
284
    console.log(selectedSpaceID);
285
    console.log(selectedCombinedEquipment);
286
    console.log(periodType);
287
    console.log(basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
288
    console.log(basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
289
    console.log(reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
290
    console.log(reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
291
292
    // disable submit button
293
    setSubmitButtonDisabled(true);
294
    // show spinner
295
    setSpinnerHidden(false);
296
    // hide export buttion
297
    setExportButtonHidden(true)
298
299
    // Reinitialize tables
300
    setDetailedDataTableData([]);
301
    
302
    let isResponseOK = false;
303
    fetch(APIBaseURL + '/reports/combinedequipmentenergycategory?' +
304
      'combinedequipmentid=' + selectedCombinedEquipment +
305
      '&periodtype=' + periodType +
306
      '&baseperiodstartdatetime=' + (basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
307
      '&baseperiodenddatetime=' + (basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
308
      '&reportingperiodstartdatetime=' + reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') +
309
      '&reportingperiodenddatetime=' + reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'), {
310
      method: 'GET',
311
      headers: {
312
        "Content-type": "application/json",
313
        "User-UUID": getCookieValue('user_uuid'),
314
        "Token": getCookieValue('token')
315
      },
316
      body: null,
317
318
    }).then(response => {
319
      if (response.ok) {
320
        isResponseOK = true;
321
      };
322
      return response.json();
323
    }).then(json => {
324
      if (isResponseOK) {
325
        console.log(json)
326
              
327
        let cardSummaryArray = []
328
        json['reporting_period']['names'].forEach((currentValue, index) => {
329
          let cardSummaryItem = {}
330
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
331
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
332
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals'][index];
333
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates'][index] * 100).toFixed(2) + "%";
334
          cardSummaryArray.push(cardSummaryItem);
335
        });
336
        setCardSummaryList(cardSummaryArray);
337
        
338
        let timeOfUseArray = [];
339
        json['reporting_period']['energy_category_ids'].forEach((currentValue, index) => {
340
          if(currentValue == 1) {
341
            // energy_category_id 1 electricity
342
            let timeOfUseItem = {}
343
            timeOfUseItem['id'] = 1;
344
            timeOfUseItem['name'] =  t('Top-Peak');
345
            timeOfUseItem['value'] = json['reporting_period']['toppeaks'][index];
346
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
347
            timeOfUseArray.push(timeOfUseItem);
348
            
349
            timeOfUseItem = {}
350
            timeOfUseItem['id'] = 2;
351
            timeOfUseItem['name'] =  t('On-Peak');
352
            timeOfUseItem['value'] = json['reporting_period']['onpeaks'][index];
353
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
354
            timeOfUseArray.push(timeOfUseItem);
355
356
            timeOfUseItem = {}
357
            timeOfUseItem['id'] = 3;
358
            timeOfUseItem['name'] =  t('Mid-Peak');
359
            timeOfUseItem['value'] = json['reporting_period']['midpeaks'][index];
360
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
361
            timeOfUseArray.push(timeOfUseItem);
362
363
            timeOfUseItem = {}
364
            timeOfUseItem['id'] = 4;
365
            timeOfUseItem['name'] =  t('Off-Peak');
366
            timeOfUseItem['value'] = json['reporting_period']['offpeaks'][index];
367
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
368
            timeOfUseArray.push(timeOfUseItem);
369
          }
370
        });
371
        setTimeOfUseShareData(timeOfUseArray);
372
373
        
374
        let totalInTCE = {}; 
375
        totalInTCE['value'] = json['reporting_period']['total_in_kgce'] / 1000; // convert from kg to t
376
        totalInTCE['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgce'] * 100).toFixed(2) + "%";
377
        setTotalInTCE(totalInTCE);
378
379
        let totalInTCO2E = {}; 
380
        totalInTCO2E['value'] = json['reporting_period']['total_in_kgco2e'] / 1000; // convert from kg to t
381
        totalInTCO2E['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgco2e'] * 100).toFixed(2) + "%";
382
        setTotalInTCO2E(totalInTCO2E);
383
384
        let TCEDataArray = [];
385
        json['reporting_period']['names'].forEach((currentValue, index) => {
386
          let TCEDataItem = {}
387
          TCEDataItem['id'] = index;
388
          TCEDataItem['name'] = currentValue;
389
          TCEDataItem['value'] = json['reporting_period']['subtotals_in_kgce'][index] / 1000; // convert from kg to t
390
          TCEDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
391
          TCEDataArray.push(TCEDataItem);
392
        });
393
        setTCEShareData(TCEDataArray);
394
395
        let TCO2EDataArray = [];
396
        json['reporting_period']['names'].forEach((currentValue, index) => {
397
          let TCO2EDataItem = {}
398
          TCO2EDataItem['id'] = index;
399
          TCO2EDataItem['name'] = currentValue;
400
          TCO2EDataItem['value'] = json['reporting_period']['subtotals_in_kgco2e'][index] / 1000; // convert from kg to t
401
          TCO2EDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
402
          TCO2EDataArray.push(TCO2EDataItem);
403
        });
404
        setTCO2EShareData(TCO2EDataArray);
405
406
        let timestamps = {}
407
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
408
          timestamps['a' + index] = currentValue;
409
        });
410
        setCombinedEquipmentLineChartLabels(timestamps);
411
        
412
        let values = {}
413
        json['reporting_period']['values'].forEach((currentValue, index) => {
414
          values['a' + index] = currentValue;
415
        });
416
        setCombinedEquipmentLineChartData(values);
417
        
418
        let names = Array();
419
        json['reporting_period']['names'].forEach((currentValue, index) => {
420
          let unit = json['reporting_period']['units'][index];
421
          names.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
422
        });
423
        setCombinedEquipmentLineChartOptions(names);
424
       
425
        timestamps = {}
426
        json['parameters']['timestamps'].forEach((currentValue, index) => {
427
          timestamps['a' + index] = currentValue;
428
        });
429
        setParameterLineChartLabels(timestamps);
430
431
        values = {}
432
        json['parameters']['values'].forEach((currentValue, index) => {
433
          values['a' + index] = currentValue;
434
        });
435
        setParameterLineChartData(values);
436
      
437
        names = Array();
438
        json['parameters']['names'].forEach((currentValue, index) => {
439
          if (currentValue.startsWith('TARIFF-')) {
440
            currentValue = t('Tariff') + currentValue.replace('TARIFF-', '-');
441
          }
442
          
443
          names.push({ 'value': 'a' + index, 'label': currentValue });
444
        });
445
        setParameterLineChartOptions(names);
446
        
447
        let detailed_value_list = [];
448
        if (json['reporting_period']['timestamps'].length > 0) {
449
          json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
450
            let detailed_value = {};
451
            detailed_value['id'] = timestampIndex;
452
            detailed_value['startdatetime'] = currentTimestamp;
453
            json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
454
              detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values'][energyCategoryIndex][timestampIndex].toFixed(2);
455
            });
456
            detailed_value_list.push(detailed_value);
457
          });
458
        }
459
460
        let detailed_value = {};
461
        detailed_value['id'] = detailed_value_list.length;
462
        detailed_value['startdatetime'] = t('Subtotal');
463
        json['reporting_period']['subtotals'].forEach((currentValue, index) => {
464
            detailed_value['a' + index] = currentValue.toFixed(2);
465
          });
466
        detailed_value_list.push(detailed_value);
467
        setDetailedDataTableData(detailed_value_list);
468
        
469
        let detailed_column_list = [];
470
        detailed_column_list.push({
471
          dataField: 'startdatetime',
472
          text: t('Datetime'),
473
          sort: true
474
        })
475
        json['reporting_period']['names'].forEach((currentValue, index) => {
476
          let unit = json['reporting_period']['units'][index];
477
          detailed_column_list.push({
478
            dataField: 'a' + index,
479
            text: currentValue + ' (' + unit + ')',
480
            sort: true
481
          })
482
        });
483
        setDetailedDataTableColumns(detailed_column_list);
484
        
485
        setExcelBytesBase64(json['excel_bytes_base64']);
486
487
        // enable submit button
488
        setSubmitButtonDisabled(false);
489
        // hide spinner
490
        setSpinnerHidden(true);
491
        // show export buttion
492
        setExportButtonHidden(false);
493
          
494
      } else {
495
        toast.error(json.description)
496
      }
497
    }).catch(err => {
498
      console.log(err);
499
    });
500
  };
501
502
  const handleExport = e => {
503
    e.preventDefault();
504
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
505
    const fileName = 'combinedequipmentenergycategory.xlsx'
506
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
507
    fetch(fileUrl)
508
        .then(response => response.blob())
509
        .then(blob => {
510
            var link = window.document.createElement("a");
511
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
512
            link.download = fileName;
513
            document.body.appendChild(link);
514
            link.click();
515
            document.body.removeChild(link);
516
        });
517
  };
518
  
519
520
  return (
521
    <Fragment>
522
      <div>
523
        <Breadcrumb>
524
          <BreadcrumbItem>{t('Combined Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Energy Category Data')}</BreadcrumbItem>
525
        </Breadcrumb>
526
      </div>
527
      <Card className="bg-light mb-3">
528
        <CardBody className="p-3">
529
          <Form onSubmit={handleSubmit}>
530
            <Row form>
531
              <Col xs="auto">
532
                <FormGroup className="form-group">
533
                  <Label className={labelClasses} for="space">
534
                    {t('Space')}
535
                  </Label>
536
                  <br />
537
                  <Cascader options={cascaderOptions}
538
                    onChange={onSpaceCascaderChange}
539
                    changeOnSelect
540
                    expandTrigger="hover">
541
                    <Input value={selectedSpaceName || ''} readOnly />
542
                  </Cascader>
543
                </FormGroup>
544
              </Col>
545
              <Col xs="auto">
546
                <FormGroup>
547
                  <Label className={labelClasses} for="combinedEquipmentSelect">
548
                    {t('Combined Equipment')}
549
                  </Label>
550
                  <CustomInput type="select" id="combinedEquipmentSelect" name="combinedEquipmentSelect" onChange={({ target }) => setSelectedCombinedEquipment(target.value)}
551
                  >
552
                    {combinedEquipmentList.map((combinedEquipment, index) => (
553
                      <option value={combinedEquipment.value} key={combinedEquipment.value}>
554
                        {combinedEquipment.label}
555
                      </option>
556
                    ))}
557
                  </CustomInput>
558
                </FormGroup>
559
              </Col>
560
              <Col xs="auto">
561
                <FormGroup>
562
                  <Label className={labelClasses} for="comparisonType">
563
                    {t('Comparison Types')}
564
                  </Label>
565
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
566
                    defaultValue="month-on-month"
567
                    onChange={onComparisonTypeChange}
568
                  >
569
                    {comparisonTypeOptions.map((comparisonType, index) => (
570
                      <option value={comparisonType.value} key={comparisonType.value} >
571
                        {t(comparisonType.label)}
572
                      </option>
573
                    ))}
574
                  </CustomInput>
575
                </FormGroup>
576
              </Col>
577
              <Col xs="auto">
578
                <FormGroup>
579
                  <Label className={labelClasses} for="periodType">
580
                    {t('Period Types')}
581
                  </Label>
582
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
583
                  >
584
                    {periodTypeOptions.map((periodType, index) => (
585
                      <option value={periodType.value} key={periodType.value} >
586
                        {t(periodType.label)}
587
                      </option>
588
                    ))}
589
                  </CustomInput>
590
                </FormGroup>
591
              </Col>
592
              <Col xs="auto">
593
                <FormGroup className="form-group">
594
                  <Label className={labelClasses} for="basePeriodBeginsDatetime">
595
                    {t('Base Period Begins')}{t('(Optional)')}
596
                  </Label>
597
                  <Datetime id='basePeriodBeginsDatetime'
598
                    value={basePeriodBeginsDatetime}
599
                    inputProps={{ disabled: basePeriodBeginsDatetimeDisabled }}
600
                    onChange={onBasePeriodBeginsDatetimeChange}
601
                    isValidDate={getValidBasePeriodBeginsDatetimes}
602
                    closeOnSelect={true} />
603
                </FormGroup>
604
              </Col>
605
              <Col xs="auto">
606
                <FormGroup className="form-group">
607
                  <Label className={labelClasses} for="basePeriodEndsDatetime">
608
                    {t('Base Period Ends')}{t('(Optional)')}
609
                  </Label>
610
                  <Datetime id='basePeriodEndsDatetime'
611
                    value={basePeriodEndsDatetime}
612
                    inputProps={{ disabled: basePeriodEndsDatetimeDisabled }}
613
                    onChange={onBasePeriodEndsDatetimeChange}
614
                    isValidDate={getValidBasePeriodEndsDatetimes}
615
                    closeOnSelect={true} />
616
                </FormGroup>
617
              </Col>
618
              <Col xs="auto">
619
                <FormGroup className="form-group">
620
                  <Label className={labelClasses} for="reportingPeriodBeginsDatetime">
621
                    {t('Reporting Period Begins')}
622
                  </Label>
623
                  <Datetime id='reportingPeriodBeginsDatetime'
624
                    value={reportingPeriodBeginsDatetime}
625
                    onChange={onReportingPeriodBeginsDatetimeChange}
626
                    isValidDate={getValidReportingPeriodBeginsDatetimes}
627
                    closeOnSelect={true} />
628
                </FormGroup>
629
              </Col>
630
              <Col xs="auto">
631
                <FormGroup className="form-group">
632
                  <Label className={labelClasses} for="reportingPeriodEndsDatetime">
633
                    {t('Reporting Period Ends')}
634
                  </Label>
635
                  <Datetime id='reportingPeriodEndsDatetime'
636
                    value={reportingPeriodEndsDatetime}
637
                    onChange={onReportingPeriodEndsDatetimeChange}
638
                    isValidDate={getValidReportingPeriodEndsDatetimes}
639
                    closeOnSelect={true} />
640
                </FormGroup>
641
              </Col>
642
              <Col xs="auto">
643
                <FormGroup>
644
                  <br></br>
645
                  <ButtonGroup id="submit">
646
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
647
                  </ButtonGroup>
648
                </FormGroup>
649
              </Col>
650
              <Col xs="auto">
651
                <FormGroup>
652
                  <br></br>
653
                  <Spinner color="primary" hidden={spinnerHidden}  />
654
                </FormGroup>
655
              </Col>
656
              <Col xs="auto">
657
                  <br></br>
658
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
659
                  hidden={exportButtonHidden}
660
                  onClick={handleExport} >
661
                    {t('Export')}
662
                  </ButtonIcon>
663
              </Col>
664
            </Row>
665
          </Form>
666
        </CardBody>
667
      </Card>
668
      <div className="card-deck">
669
        {cardSummaryList.map(cardSummaryItem => (
670
          <CardSummary key={cardSummaryItem['name']}
671
            rate={cardSummaryItem['increment_rate']}
672
            title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
673
            color="success" >
674
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
675
          </CardSummary>
676
        ))}
677
       
678
        <CardSummary 
679
          rate={totalInTCE['increment_rate'] || ''} 
680
          title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': t('Ton of Standard Coal'), 'UNIT': '(TCE)' })}
681
          color="warning" >
682
          {totalInTCE['value'] && <CountUp end={totalInTCE['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
683
        </CardSummary>
684
        <CardSummary 
685
          rate={totalInTCO2E['increment_rate'] || ''} 
686
          title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': t('Ton of Carbon Dioxide Emissions'), 'UNIT': '(TCO2E)' })}
687
          color="warning" >
688
          {totalInTCO2E['value'] && <CountUp end={totalInTCO2E['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
689
        </CardSummary>
690
      </div>
691
692
      <Row noGutters>
693
        <Col className="mb-3 pr-lg-2 mb-3">
694
          <SharePie data={timeOfUseShareData} title={t('Electricity Consumption by Time-Of-Use')} />
695
        </Col>
696
        <Col className="mb-3 pr-lg-2 mb-3">
697
          <SharePie data={TCEShareData} title={t('Ton of Standard Coal by Energy Category')} />
698
        </Col>
699
        <Col className="mb-3 pr-lg-2 mb-3">
700
          <SharePie data={TCO2EShareData} title={t('Ton of Carbon Dioxide Emissions by Energy Category')} />
701
        </Col>
702
      </Row>
703
      <LineChart reportingTitle={t('Reporting Period Consumption CATEGORY VALUE UNIT', { 'CATEGORY': null, 'VALUE': null, 'UNIT': null })}
704
        baseTitle=''
705
        labels={combinedEquipmentLineChartLabels}
706
        data={combinedEquipmentLineChartData}
707
        options={combinedEquipmentLineChartOptions}>
708
      </LineChart>
709
710
      <LineChart reportingTitle={t('Related Parameters')}
711
        baseTitle=''
712
        labels={parameterLineChartLabels}
713
        data={parameterLineChartData}
714
        options={parameterLineChartOptions}>
715
      </LineChart>
716
      <br />
717
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
718
      </DetailedDataTable>
719
720
    </Fragment>
721
  );
722
};
723
724
export default withTranslation()(withRedirect(CombinedEquipmentEnergyCategory));
725