Passed
Push — master ( c04ae7...0fa5b5 )
by Guangyu
08:11 queued 03:39
created

src/components/MyEMS/CombinedEquipment/CombinedEquipmentSaving.js   A

Complexity

Total Complexity 25
Complexity/F 0

Size

Lines of Code 685
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

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