Passed
Push — master ( cfe6bd...bdceca )
by Guangyu
04:33 queued 12s
created

src/components/MyEMS/Equipment/EquipmentSaving.js   A

Complexity

Total Complexity 25
Complexity/F 0

Size

Lines of Code 687
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 25
eloc 607
mnd 25
bc 25
fnc 0
dl 0
loc 687
rs 9.993
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 EquipmentSaving = ({ 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 [equipmentList, setEquipmentList] = useState([]);
63
  const [selectedEquipment, setSelectedEquipment] = 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 [equipmentLineChartLabels, setEquipmentLineChartLabels] = useState([]);
87
  const [equipmentLineChartData, setEquipmentLineChartData] = useState({});
88
  const [equipmentLineChartOptions, setEquipmentLineChartOptions] = 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 Equipments by root Space ID
124
        let isResponseOK = false;
125
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/equipments', {
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
            setEquipmentList(json[0]);
144
            if (json[0].length > 0) {
145
              setSelectedEquipment(json[0][0].value);
146
              // enable submit button
147
              setSubmitButtonDisabled(false);
148
            } else {
149
              setSelectedEquipment(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 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
  
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] + '/equipments', {
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
        setEquipmentList(json[0]);
196
        if (json[0].length > 0) {
197
          setSelectedEquipment(json[0][0].value);
198
          // enable submit button
199
          setSubmitButtonDisabled(false);
200
        } else {
201
          setSelectedEquipment(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(selectedEquipment);
286
    console.log(comparisonType);
287
    console.log(periodType);
288
    console.log(basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
289
    console.log(basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
290
    console.log(reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
291
    console.log(reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
292
293
    // disable submit button
294
    setSubmitButtonDisabled(true);
295
    // show spinner
296
    setSpinnerHidden(false);
297
    // hide export buttion
298
    setExportButtonHidden(true)
299
300
    // Reinitialize tables
301
    setDetailedDataTableData([]);
302
    
303
    let isResponseOK = false;
304
    fetch(APIBaseURL + '/reports/equipmentsaving?' +
305
      'equipmentid=' + selectedEquipment +
306
      '&periodtype=' + periodType +
307
      '&baseperiodstartdatetime=' + (basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
308
      '&baseperiodenddatetime=' + (basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
309
      '&reportingperiodstartdatetime=' + reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') +
310
      '&reportingperiodenddatetime=' + reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'), {
311
      method: 'GET',
312
      headers: {
313
        "Content-type": "application/json",
314
        "User-UUID": getCookieValue('user_uuid'),
315
        "Token": getCookieValue('token')
316
      },
317
      body: null,
318
319
    }).then(response => {
320
      if (response.ok) {
321
        isResponseOK = true;
322
      };
323
      return response.json();
324
    }).then(json => {
325
      if (isResponseOK) {
326
        console.log(json)
327
        
328
        let cardSummaryArray = []
329
        json['reporting_period']['names'].forEach((currentValue, index) => {
330
          let cardSummaryItem = {}
331
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
332
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
333
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals_saving'][index];
334
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates_saving'][index] * 100).toFixed(2) + "%";
335
          cardSummaryArray.push(cardSummaryItem);
336
        });
337
        setCardSummaryList(cardSummaryArray);
338
339
        let totalInTCE = {}; 
340
        totalInTCE['value'] = json['reporting_period']['total_in_kgce_saving'] / 1000; // convert from kg to t
341
        totalInTCE['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgce_saving'] * 100).toFixed(2) + "%";
342
        setTotalInTCE(totalInTCE);
343
344
        let totalInTCO2E = {}; 
345
        totalInTCO2E['value'] = json['reporting_period']['total_in_kgco2e_saving'] / 1000; // convert from kg to t
346
        totalInTCO2E['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgco2e_saving'] * 100).toFixed(2) + "%";
347
        setTotalInTCO2E(totalInTCO2E);
348
349
        let TCEDataArray = [];
350
        json['reporting_period']['names'].forEach((currentValue, index) => {
351
          let TCEDataItem = {}
352
          TCEDataItem['id'] = index;
353
          TCEDataItem['name'] = currentValue;
354
          TCEDataItem['value'] = json['reporting_period']['subtotals_in_kgce_saving'][index] / 1000; // convert from kg to t
355
          TCEDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
356
          TCEDataArray.push(TCEDataItem);
357
        });
358
        setTCEShareData(TCEDataArray);
359
360
        let TCO2EDataArray = [];
361
        json['reporting_period']['names'].forEach((currentValue, index) => {
362
          let TCO2EDataItem = {}
363
          TCO2EDataItem['id'] = index;
364
          TCO2EDataItem['name'] = currentValue;
365
          TCO2EDataItem['value'] = json['reporting_period']['subtotals_in_kgco2e_saving'][index] / 1000; // convert from kg to t
366
          TCO2EDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
367
          TCO2EDataArray.push(TCO2EDataItem);
368
        });
369
        setTCO2EShareData(TCO2EDataArray);
370
371
        let timestamps = {}
372
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
373
          timestamps['a' + index] = currentValue;
374
        });
375
        setEquipmentLineChartLabels(timestamps);
376
        
377
        let values = {}
378
        json['reporting_period']['values_saving'].forEach((currentValue, index) => {
379
          values['a' + index] = currentValue;
380
        });
381
        setEquipmentLineChartData(values);
382
        
383
        let names = Array();
384
        json['reporting_period']['names'].forEach((currentValue, index) => {
385
          let unit = json['reporting_period']['units'][index];
386
          names.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
387
        });
388
        setEquipmentLineChartOptions(names);
389
       
390
        timestamps = {}
391
        json['parameters']['timestamps'].forEach((currentValue, index) => {
392
          timestamps['a' + index] = currentValue;
393
        });
394
        setParameterLineChartLabels(timestamps);
395
396
        values = {}
397
        json['parameters']['values'].forEach((currentValue, index) => {
398
          values['a' + index] = currentValue;
399
        });
400
        setParameterLineChartData(values);
401
      
402
        names = Array();
403
        json['parameters']['names'].forEach((currentValue, index) => {
404
          if (currentValue.startsWith('TARIFF-')) {
405
            currentValue = t('Tariff') + currentValue.replace('TARIFF-', '-');
406
          }
407
          
408
          names.push({ 'value': 'a' + index, 'label': currentValue });
409
        });
410
        setParameterLineChartOptions(names);
411
        
412
        let detailed_value_list = [];
413
        if (json['reporting_period']['timestamps'].length > 0) {
414
          json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
415
            let detailed_value = {};
416
            detailed_value['id'] = timestampIndex;
417
            detailed_value['startdatetime'] = currentTimestamp;
418
            json['reporting_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
419
              detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values_saving'][energyCategoryIndex][timestampIndex].toFixed(2);
420
            });
421
            detailed_value_list.push(detailed_value);
422
          });
423
        };
424
425
        let detailed_value = {};
426
        detailed_value['id'] = detailed_value_list.length;
427
        detailed_value['startdatetime'] = t('Subtotal');
428
        json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
429
            detailed_value['a' + index] = currentValue.toFixed(2);
430
          });
431
        detailed_value_list.push(detailed_value);
432
        setDetailedDataTableData(detailed_value_list);
433
        
434
        let detailed_column_list = [];
435
        detailed_column_list.push({
436
          dataField: 'startdatetime',
437
          text: t('Datetime'),
438
          sort: true
439
        });
440
        json['reporting_period']['names'].forEach((currentValue, index) => {
441
          let unit = json['reporting_period']['units'][index];
442
          detailed_column_list.push({
443
            dataField: 'a' + index,
444
            text: currentValue + ' (' + unit + ')',
445
            sort: true
446
          });
447
        });
448
        setDetailedDataTableColumns(detailed_column_list);
449
        
450
        setExcelBytesBase64(json['excel_bytes_base64']);
451
452
        // enable submit button
453
        setSubmitButtonDisabled(false);
454
        // hide spinner
455
        setSpinnerHidden(true);
456
        // show export buttion
457
        setExportButtonHidden(false);
458
        
459
      } else {
460
        toast.error(json.description)
461
      }
462
    }).catch(err => {
463
      console.log(err);
464
    });
465
  };
466
  
467
  const handleExport = e => {
468
    e.preventDefault();
469
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
470
    const fileName = 'equipmentsaving.xlsx'
471
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
472
    fetch(fileUrl)
473
        .then(response => response.blob())
474
        .then(blob => {
475
            var link = window.document.createElement("a");
476
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
477
            link.download = fileName;
478
            document.body.appendChild(link);
479
            link.click();
480
            document.body.removeChild(link);
481
        });
482
  };
483
  
484
485
486
  return (
487
    <Fragment>
488
      <div>
489
        <Breadcrumb>
490
          <BreadcrumbItem>{t('Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Saving')}</BreadcrumbItem>
491
        </Breadcrumb>
492
      </div>
493
      <Card className="bg-light mb-3">
494
        <CardBody className="p-3">
495
          <Form onSubmit={handleSubmit}>
496
            <Row form>
497
              <Col xs="auto">
498
                <FormGroup className="form-group">
499
                  <Label className={labelClasses} for="space">
500
                    {t('Space')}
501
                  </Label>
502
                  <br />
503
                  <Cascader options={cascaderOptions}
504
                    onChange={onSpaceCascaderChange}
505
                    changeOnSelect
506
                    expandTrigger="hover">
507
                    <Input value={selectedSpaceName || ''} readOnly />
508
                  </Cascader>
509
                </FormGroup>
510
              </Col>
511
              <Col xs="auto">
512
                <FormGroup>
513
                  <Label className={labelClasses} for="equipmentSelect">
514
                    {t('Equipment')}
515
                  </Label>
516
                  <CustomInput type="select" id="equipmentSelect" name="equipmentSelect" onChange={({ target }) => setSelectedEquipment(target.value)}
517
                  >
518
                    {equipmentList.map((equipment, index) => (
519
                      <option value={equipment.value} key={equipment.value}>
520
                        {equipment.label}
521
                      </option>
522
                    ))}
523
                  </CustomInput>
524
                </FormGroup>
525
              </Col>
526
              <Col xs="auto">
527
                <FormGroup>
528
                  <Label className={labelClasses} for="comparisonType">
529
                    {t('Comparison Types')}
530
                  </Label>
531
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
532
                    defaultValue="month-on-month"
533
                    onChange={onComparisonTypeChange}
534
                  >
535
                    {comparisonTypeOptions.map((comparisonType, index) => (
536
                      <option value={comparisonType.value} key={comparisonType.value} >
537
                        {t(comparisonType.label)}
538
                      </option>
539
                    ))}
540
                  </CustomInput>
541
                </FormGroup>
542
              </Col>
543
              <Col xs="auto">
544
                <FormGroup>
545
                  <Label className={labelClasses} for="periodType">
546
                    {t('Period Types')}
547
                  </Label>
548
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
549
                  >
550
                    {periodTypeOptions.map((periodType, index) => (
551
                      <option value={periodType.value} key={periodType.value} >
552
                        {t(periodType.label)}
553
                      </option>
554
                    ))}
555
                  </CustomInput>
556
                </FormGroup>
557
              </Col>
558
              <Col xs="auto">
559
                <FormGroup className="form-group">
560
                  <Label className={labelClasses} for="basePeriodBeginsDatetime">
561
                    {t('Base Period Begins')}{t('(Optional)')}
562
                  </Label>
563
                  <Datetime id='basePeriodBeginsDatetime'
564
                    value={basePeriodBeginsDatetime}
565
                    inputProps={{ disabled: basePeriodBeginsDatetimeDisabled }}
566
                    onChange={onBasePeriodBeginsDatetimeChange}
567
                    isValidDate={getValidBasePeriodBeginsDatetimes}
568
                    closeOnSelect={true} />
569
                </FormGroup>
570
              </Col>
571
              <Col xs="auto">
572
                <FormGroup className="form-group">
573
                  <Label className={labelClasses} for="basePeriodEndsDatetime">
574
                    {t('Base Period Ends')}{t('(Optional)')}
575
                  </Label>
576
                  <Datetime id='basePeriodEndsDatetime'
577
                    value={basePeriodEndsDatetime}
578
                    inputProps={{ disabled: basePeriodEndsDatetimeDisabled }}
579
                    onChange={onBasePeriodEndsDatetimeChange}
580
                    isValidDate={getValidBasePeriodEndsDatetimes}
581
                    closeOnSelect={true} />
582
                </FormGroup>
583
              </Col>
584
              <Col xs="auto">
585
                <FormGroup className="form-group">
586
                  <Label className={labelClasses} for="reportingPeriodBeginsDatetime">
587
                    {t('Reporting Period Begins')}
588
                  </Label>
589
                  <Datetime id='reportingPeriodBeginsDatetime'
590
                    value={reportingPeriodBeginsDatetime}
591
                    onChange={onReportingPeriodBeginsDatetimeChange}
592
                    isValidDate={getValidReportingPeriodBeginsDatetimes}
593
                    closeOnSelect={true} />
594
                </FormGroup>
595
              </Col>
596
              <Col xs="auto">
597
                <FormGroup className="form-group">
598
                  <Label className={labelClasses} for="reportingPeriodEndsDatetime">
599
                    {t('Reporting Period Ends')}
600
                  </Label>
601
                  <Datetime id='reportingPeriodEndsDatetime'
602
                    value={reportingPeriodEndsDatetime}
603
                    onChange={onReportingPeriodEndsDatetimeChange}
604
                    isValidDate={getValidReportingPeriodEndsDatetimes}
605
                    closeOnSelect={true} />
606
                </FormGroup>
607
              </Col>
608
              <Col xs="auto">
609
                <FormGroup>
610
                  <br></br>
611
                  <ButtonGroup id="submit">
612
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
613
                  </ButtonGroup>
614
                </FormGroup>
615
              </Col>
616
              <Col xs="auto">
617
                <FormGroup>
618
                  <br></br>
619
                  <Spinner color="primary" hidden={spinnerHidden}  />
620
                </FormGroup>
621
              </Col>
622
              <Col xs="auto">
623
                  <br></br>
624
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
625
                  hidden={exportButtonHidden}
626
                  onClick={handleExport} >
627
                    {t('Export')}
628
                  </ButtonIcon>
629
              </Col>
630
            </Row>
631
          </Form>
632
        </CardBody>
633
      </Card>
634
      <div className="card-deck">
635
        {cardSummaryList.map(cardSummaryItem => (
636
          <CardSummary key={cardSummaryItem['name']}
637
            rate={cardSummaryItem['increment_rate']}
638
            title={t('Reporting Period Savings CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
639
            color="success" >
640
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
641
          </CardSummary>
642
        ))}
643
       
644
        <CardSummary 
645
          rate={totalInTCE['increment_rate'] || ''} 
646
          title={t('Reporting Period Savings CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Standard Coal'), 'UNIT': '(TCE)' })}
647
          color="warning" >
648
          {totalInTCE['value'] && <CountUp end={totalInTCE['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
649
        </CardSummary>
650
        <CardSummary 
651
          rate={totalInTCO2E['increment_rate'] || ''} 
652
          title={t('Reporting Period Decreased CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Carbon Dioxide Emissions'), 'UNIT': '(TCO2E)' })}
653
          color="warning" >
654
          {totalInTCO2E['value'] && <CountUp end={totalInTCO2E['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
655
        </CardSummary>
656
      </div>
657
      <Row noGutters>
658
        <Col className="mb-3 pr-lg-2 mb-3">
659
          <SharePie data={TCEShareData} title={t('Ton of Standard Coal by Energy Category')} />
660
        </Col>
661
        <Col className="mb-3 pr-lg-2 mb-3">
662
          <SharePie data={TCO2EShareData} title={t('Ton of Carbon Dioxide Emissions by Energy Category')} />
663
        </Col>
664
      </Row>
665
      <LineChart reportingTitle={t('Reporting Period Savings CATEGORY VALUE UNIT', { 'CATEGORY': null, 'VALUE': null, 'UNIT': null })}
666
        baseTitle=''
667
        labels={equipmentLineChartLabels}
668
        data={equipmentLineChartData}
669
        options={equipmentLineChartOptions}>
670
      </LineChart>
671
672
      <LineChart reportingTitle={t('Related Parameters')}
673
        baseTitle=''
674
        labels={parameterLineChartLabels}
675
        data={parameterLineChartData}
676
        options={parameterLineChartOptions}>
677
      </LineChart>
678
      <br />
679
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
680
      </DetailedDataTable>
681
682
    </Fragment>
683
  );
684
};
685
686
export default withTranslation()(withRedirect(EquipmentSaving));
687