Passed
Push — master ( 92451b...a1dfdd )
by Guangyu
05:18 queued 11s
created

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

Complexity

Total Complexity 25
Complexity/F 0

Size

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