Passed
Push — master ( 95cb66...99bc21 )
by Guangyu
04:14 queued 11s
created

src/components/MyEMS/Store/StoreSaving.js   A

Complexity

Total Complexity 24
Complexity/F 0

Size

Lines of Code 634
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 24
eloc 562
mnd 24
bc 24
fnc 0
dl 0
loc 634
rs 10
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
} from 'reactstrap';
17
import CountUp from 'react-countup';
18
import Datetime from 'react-datetime';
19
import moment from 'moment';
20
import loadable from '@loadable/component';
21
import Cascader from 'rc-cascader';
22
import CardSummary from '../common/CardSummary';
23
import LineChart from '../common/LineChart';
24
import SharePie from '../common/SharePie';
25
import { getCookieValue, createCookie } from '../../../helpers/utils';
26
import withRedirect from '../../../hoc/withRedirect';
27
import { withTranslation } from 'react-i18next';
28
import { toast } from 'react-toastify';
29
import { APIBaseURL } from '../../../config';
30
import { periodTypeOptions } from '../common/PeriodTypeOptions';
31
import { comparisonTypeOptions } from '../common/ComparisonTypeOptions';
32
33
34
const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
35
36
const StoreSaving = ({ setRedirect, setRedirectUrl, t }) => {
37
  let current_moment = moment();
38
  useEffect(() => {
39
    let is_logged_in = getCookieValue('is_logged_in');
40
    let user_name = getCookieValue('user_name');
41
    let user_display_name = getCookieValue('user_display_name');
42
    let user_uuid = getCookieValue('user_uuid');
43
    let token = getCookieValue('token');
44
    if (is_logged_in === null || !is_logged_in) {
45
      setRedirectUrl(`/authentication/basic/login`);
46
      setRedirect(true);
47
    } else {
48
      //update expires time of cookies
49
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
50
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
51
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
52
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
53
      createCookie('token', token, 1000 * 60 * 60 * 8);
54
    }
55
  });
56
  // State
57
  // Query Parameters
58
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
59
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
60
  const [storeList, setStoreList] = useState([]);
61
  const [selectedStore, setSelectedStore] = useState(undefined);
62
  const [comparisonType, setComparisonType] = useState('month-on-month');
63
  const [periodType, setPeriodType] = useState('daily');
64
  const [basePeriodBeginsDatetime, setBasePeriodBeginsDatetime] = useState(current_moment.clone().subtract(1, 'months').startOf('month'));
65
  const [basePeriodEndsDatetime, setBasePeriodEndsDatetime] = useState(current_moment.clone().subtract(1, 'months'));
66
  const [basePeriodBeginsDatetimeDisabled, setBasePeriodBeginsDatetimeDisabled] = useState(true);
67
  const [basePeriodEndsDatetimeDisabled, setBasePeriodEndsDatetimeDisabled] = useState(true);
68
  const [reportingPeriodBeginsDatetime, setReportingPeriodBeginsDatetime] = useState(current_moment.clone().startOf('month'));
69
  const [reportingPeriodEndsDatetime, setReportingPeriodEndsDatetime] = useState(current_moment);
70
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
71
  const [isDisabled, setIsDisabled] = useState(true);
72
  //Results
73
  const [TCEShareData, setTCEShareData] = useState([]);
74
  const [TCO2EShareData, setTCO2EShareData] = useState([]);
75
76
  const [cardSummaryList, setCardSummaryList] = useState([]);
77
  const [totalInTCE, setTotalInTCE] = useState({});
78
  const [totalInTCO2E, setTotalInTCO2E] = useState({});
79
  const [storeLineChartLabels, setStoreLineChartLabels] = useState([]);
80
  const [storeLineChartData, setStoreLineChartData] = useState({});
81
  const [storeLineChartOptions, setStoreLineChartOptions] = useState([]);
82
83
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
84
  const [parameterLineChartData, setParameterLineChartData] = useState({});
85
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
86
87
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
88
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
89
90
  useEffect(() => {
91
    let isResponseOK = false;
92
    fetch(APIBaseURL + '/spaces/tree', {
93
      method: 'GET',
94
      headers: {
95
        "Content-type": "application/json",
96
        "User-UUID": getCookieValue('user_uuid'),
97
        "Token": getCookieValue('token')
98
      },
99
      body: null,
100
101
    }).then(response => {
102
      console.log(response);
103
      if (response.ok) {
104
        isResponseOK = true;
105
      }
106
      return response.json();
107
    }).then(json => {
108
      console.log(json);
109
      if (isResponseOK) {
110
        // rename keys 
111
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
112
        setCascaderOptions(json);
113
        setSelectedSpaceName([json[0]].map(o => o.label));
114
        setSelectedSpaceID([json[0]].map(o => o.value));
115
        // get Stores by root Space ID
116
        let isResponseOK = false;
117
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/stores', {
118
          method: 'GET',
119
          headers: {
120
            "Content-type": "application/json",
121
            "User-UUID": getCookieValue('user_uuid'),
122
            "Token": getCookieValue('token')
123
          },
124
          body: null,
125
126
        }).then(response => {
127
          if (response.ok) {
128
            isResponseOK = true;
129
          }
130
          return response.json();
131
        }).then(json => {
132
          if (isResponseOK) {
133
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
134
            console.log(json);
135
            setStoreList(json[0]);
136
            if (json[0].length > 0) {
137
              setSelectedStore(json[0][0].value);
138
              setIsDisabled(false);
139
            } else {
140
              setSelectedStore(undefined);
141
              setIsDisabled(true);
142
            }
143
          } else {
144
            toast.error(json.description)
145
          }
146
        }).catch(err => {
147
          console.log(err);
148
        });
149
        // end of get Stores by root Space ID
150
      } else {
151
        toast.error(json.description);
152
      }
153
    }).catch(err => {
154
      console.log(err);
155
    });
156
157
  }, []);
158
159
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
160
161
  let onSpaceCascaderChange = (value, selectedOptions) => {
162
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
163
    setSelectedSpaceID(value[value.length - 1]);
164
165
    let isResponseOK = false;
166
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/stores', {
167
      method: 'GET',
168
      headers: {
169
        "Content-type": "application/json",
170
        "User-UUID": getCookieValue('user_uuid'),
171
        "Token": getCookieValue('token')
172
      },
173
      body: null,
174
175
    }).then(response => {
176
      if (response.ok) {
177
        isResponseOK = true;
178
      }
179
      return response.json();
180
    }).then(json => {
181
      if (isResponseOK) {
182
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
183
        console.log(json)
184
        setStoreList(json[0]);
185
        if (json[0].length > 0) {
186
          setSelectedStore(json[0][0].value);
187
          setIsDisabled(false);
188
        } else {
189
          setSelectedStore(undefined);
190
          setIsDisabled(true);
191
        }
192
      } else {
193
        toast.error(json.description)
194
      }
195
    }).catch(err => {
196
      console.log(err);
197
    });
198
  }
199
200
201
  let onComparisonTypeChange = ({ target }) => {
202
    console.log(target.value);
203
    setComparisonType(target.value);
204
    if (target.value === 'year-over-year') {
205
      setBasePeriodBeginsDatetimeDisabled(true);
206
      setBasePeriodEndsDatetimeDisabled(true);
207
      setBasePeriodBeginsDatetime(moment(reportingPeriodBeginsDatetime).subtract(1, 'years'));
208
      setBasePeriodEndsDatetime(moment(reportingPeriodEndsDatetime).subtract(1, 'years'));
209
    } else if (target.value === 'month-on-month') {
210
      setBasePeriodBeginsDatetimeDisabled(true);
211
      setBasePeriodEndsDatetimeDisabled(true);
212
      setBasePeriodBeginsDatetime(moment(reportingPeriodBeginsDatetime).subtract(1, 'months'));
213
      setBasePeriodEndsDatetime(moment(reportingPeriodEndsDatetime).subtract(1, 'months'));
214
    } else if (target.value === 'free-comparison') {
215
      setBasePeriodBeginsDatetimeDisabled(false);
216
      setBasePeriodEndsDatetimeDisabled(false);
217
    } else if (target.value === 'none-comparison') {
218
      setBasePeriodBeginsDatetime(undefined);
219
      setBasePeriodEndsDatetime(undefined);
220
      setBasePeriodBeginsDatetimeDisabled(true);
221
      setBasePeriodEndsDatetimeDisabled(true);
222
    }
223
  }
224
225
  let onBasePeriodBeginsDatetimeChange = (newDateTime) => {
226
    setBasePeriodBeginsDatetime(newDateTime);
227
  }
228
229
  let onBasePeriodEndsDatetimeChange = (newDateTime) => {
230
    setBasePeriodEndsDatetime(newDateTime);
231
  }
232
233
  let onReportingPeriodBeginsDatetimeChange = (newDateTime) => {
234
    setReportingPeriodBeginsDatetime(newDateTime);
235
    if (comparisonType === 'year-over-year') {
236
      setBasePeriodBeginsDatetime(newDateTime.clone().subtract(1, 'years'));
237
    } else if (comparisonType === 'month-on-month') {
238
      setBasePeriodBeginsDatetime(newDateTime.clone().subtract(1, 'months'));
239
    }
240
  }
241
242
  let onReportingPeriodEndsDatetimeChange = (newDateTime) => {
243
    setReportingPeriodEndsDatetime(newDateTime);
244
    if (comparisonType === 'year-over-year') {
245
      setBasePeriodEndsDatetime(newDateTime.clone().subtract(1, 'years'));
246
    } else if (comparisonType === 'month-on-month') {
247
      setBasePeriodEndsDatetime(newDateTime.clone().subtract(1, 'months'));
248
    }
249
  }
250
251
  var getValidBasePeriodBeginsDatetimes = function (currentDate) {
252
    return currentDate.isBefore(moment(basePeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
253
  }
254
255
  var getValidBasePeriodEndsDatetimes = function (currentDate) {
256
    return currentDate.isAfter(moment(basePeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
257
  }
258
259
  var getValidReportingPeriodBeginsDatetimes = function (currentDate) {
260
    return currentDate.isBefore(moment(reportingPeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
261
  }
262
263
  var getValidReportingPeriodEndsDatetimes = function (currentDate) {
264
    return currentDate.isAfter(moment(reportingPeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
265
  }
266
267
  // Handler
268
  const handleSubmit = e => {
269
    e.preventDefault();
270
    console.log('handleSubmit');
271
    console.log(selectedSpaceID);
272
    console.log(selectedStore);
273
    console.log(periodType);
274
    console.log(basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
275
    console.log(basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
276
    console.log(reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
277
    console.log(reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
278
279
    // Reinitialize tables
280
    setDetailedDataTableData([]);
281
    
282
    let isResponseOK = false;
283
    fetch(APIBaseURL + '/reports/storesaving?' +
284
      'storeid=' + selectedStore +
285
      '&periodtype=' + periodType +
286
      '&baseperiodstartdatetime=' + (basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
287
      '&baseperiodenddatetime=' + (basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
288
      '&reportingperiodstartdatetime=' + reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') +
289
      '&reportingperiodenddatetime=' + reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'), {
290
      method: 'GET',
291
      headers: {
292
        "Content-type": "application/json",
293
        "User-UUID": getCookieValue('user_uuid'),
294
        "Token": getCookieValue('token')
295
      },
296
      body: null,
297
298
    }).then(response => {
299
      if (response.ok) {
300
        isResponseOK = true;
301
      }
302
      return response.json();
303
    }).then(json => {
304
      if (isResponseOK) {
305
        console.log(json)
306
              
307
        let cardSummaryArray = []
308
        json['reporting_period']['names'].forEach((currentValue, index) => {
309
          let cardSummaryItem = {}
310
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
311
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
312
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals_saving'][index];
313
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates_saving'][index] * 100).toFixed(2) + "%";
314
          cardSummaryItem['subtotal_per_unit_area'] = json['reporting_period']['subtotals_per_unit_area_saving'][index];
315
          cardSummaryArray.push(cardSummaryItem);
316
        });
317
        setCardSummaryList(cardSummaryArray);
318
319
        let totalInTCE = {}; 
320
        totalInTCE['value'] = json['reporting_period']['total_in_kgce_saving'];
321
        totalInTCE['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgce_saving'] * 100).toFixed(2) + "%";
322
        totalInTCE['value_per_unit_area'] = json['reporting_period']['total_in_kgce_per_unit_area_saving'];
323
        setTotalInTCE(totalInTCE);
324
325
        let totalInTCO2E = {}; 
326
        totalInTCO2E['value'] = json['reporting_period']['total_in_kgco2e_saving'];
327
        totalInTCO2E['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgco2e_saving'] * 100).toFixed(2) + "%";
328
        totalInTCO2E['value_per_unit_area'] = json['reporting_period']['total_in_kgco2e_per_unit_area_saving'];
329
        setTotalInTCO2E(totalInTCO2E);
330
331
        let TCEDataArray = [];
332
        json['reporting_period']['names'].forEach((currentValue, index) => {
333
          let TCEDataItem = {}
334
          TCEDataItem['id'] = index;
335
          TCEDataItem['name'] = currentValue;
336
          TCEDataItem['value'] = json['reporting_period']['subtotals_in_kgce_saving'][index] / 1000;
337
          TCEDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
338
          TCEDataArray.push(TCEDataItem);
339
        });
340
        setTCEShareData(TCEDataArray);
341
342
        let TCO2EDataArray = [];
343
        json['reporting_period']['names'].forEach((currentValue, index) => {
344
          let TCO2EDataItem = {}
345
          TCO2EDataItem['id'] = index;
346
          TCO2EDataItem['name'] = currentValue;
347
          TCO2EDataItem['value'] = json['reporting_period']['subtotals_in_kgco2e_saving'][index] / 1000;
348
          TCO2EDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
349
          TCO2EDataArray.push(TCO2EDataItem);
350
        });
351
        setTCO2EShareData(TCO2EDataArray);
352
353
        let timestamps = {}
354
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
355
          timestamps['a' + index] = currentValue;
356
        });
357
        setStoreLineChartLabels(timestamps);
358
        
359
        let values = {}
360
        json['reporting_period']['values_saving'].forEach((currentValue, index) => {
361
          values['a' + index] = currentValue;
362
        });
363
        setStoreLineChartData(values);
364
        
365
        let names = Array();
366
        json['reporting_period']['names'].forEach((currentValue, index) => {
367
          let unit = json['reporting_period']['units'][index];
368
          names.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
369
        });
370
        setStoreLineChartOptions(names);
371
       
372
        timestamps = {}
373
        json['parameters']['timestamps'].forEach((currentValue, index) => {
374
          timestamps['a' + index] = currentValue;
375
        });
376
        setParameterLineChartLabels(timestamps);
377
378
        values = {}
379
        json['parameters']['values'].forEach((currentValue, index) => {
380
          values['a' + index] = currentValue;
381
        });
382
        setParameterLineChartData(values);
383
      
384
        names = Array();
385
        json['parameters']['names'].forEach((currentValue, index) => {
386
          if (currentValue.startsWith('TARIFF-')) {
387
            currentValue = t('Tariff') + currentValue.replace('TARIFF-', '-');
388
          }
389
          
390
          names.push({ 'value': 'a' + index, 'label': currentValue });
391
        });
392
        setParameterLineChartOptions(names);
393
        
394
        let detailed_value_list = [];
395
        json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
396
          let detailed_value = {};
397
          detailed_value['id'] = timestampIndex;
398
          detailed_value['startdatetime'] = currentTimestamp;
399
          json['reporting_period']['values_saving'].forEach((currentValue, energyCategoryIndex) => {
400
            detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values_saving'][energyCategoryIndex][timestampIndex].toFixed(2);
401
          });
402
          detailed_value_list.push(detailed_value);
403
        });
404
405
        let detailed_value = {};
406
        detailed_value['id'] = detailed_value_list.length;
407
        detailed_value['startdatetime'] = t('Subtotal');
408
        json['reporting_period']['subtotals_saving'].forEach((currentValue, index) => {
409
            detailed_value['a' + index] = currentValue.toFixed(2);
410
          });
411
        detailed_value_list.push(detailed_value);
412
        setDetailedDataTableData(detailed_value_list);
413
        
414
        let detailed_column_list = [];
415
        detailed_column_list.push({
416
          dataField: 'startdatetime',
417
          text: t('Datetime'),
418
          sort: true
419
        })
420
        json['reporting_period']['names'].forEach((currentValue, index) => {
421
          let unit = json['reporting_period']['units'][index];
422
          detailed_column_list.push({
423
            dataField: 'a' + index,
424
            text: currentValue + ' (' + unit + ')',
425
            sort: true
426
          })
427
        });
428
        setDetailedDataTableColumns(detailed_column_list);
429
      } else {
430
        toast.error(json.description)
431
      }
432
    }).catch(err => {
433
      console.log(err);
434
    });
435
  };
436
437
438
  return (
439
    <Fragment>
440
      <div>
441
        <Breadcrumb>
442
          <BreadcrumbItem>{t('Store Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Saving')}</BreadcrumbItem>
443
        </Breadcrumb>
444
      </div>
445
      <Card className="bg-light mb-3">
446
        <CardBody className="p-3">
447
          <Form onSubmit={handleSubmit}>
448
            <Row form>
449
              <Col xs="auto">
450
                <FormGroup className="form-group">
451
                  <Label className={labelClasses} for="space">
452
                    {t('Space')}
453
                  </Label>
454
                  <br />
455
                  <Cascader options={cascaderOptions}
456
                    onChange={onSpaceCascaderChange}
457
                    changeOnSelect
458
                    expandTrigger="hover">
459
                    <Input value={selectedSpaceName || ''} readOnly />
460
                  </Cascader>
461
                </FormGroup>
462
              </Col>
463
              <Col xs="auto">
464
                <FormGroup>
465
                  <Label className={labelClasses} for="storeSelect">
466
                    {t('Store')}
467
                  </Label>
468
                  <CustomInput type="select" id="storeSelect" name="storeSelect" onChange={({ target }) => setSelectedStore(target.value)}
469
                  >
470
                    {storeList.map((store, index) => (
471
                      <option value={store.value} key={store.value}>
472
                        {store.label}
473
                      </option>
474
                    ))}
475
                  </CustomInput>
476
                </FormGroup>
477
              </Col>
478
              <Col xs="auto">
479
                <FormGroup>
480
                  <Label className={labelClasses} for="comparisonType">
481
                    {t('Comparison Types')}
482
                  </Label>
483
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
484
                    defaultValue="month-on-month"
485
                    onChange={onComparisonTypeChange}
486
                  >
487
                    {comparisonTypeOptions.map((comparisonType, index) => (
488
                      <option value={comparisonType.value} key={comparisonType.value} >
489
                        {t(comparisonType.label)}
490
                      </option>
491
                    ))}
492
                  </CustomInput>
493
                </FormGroup>
494
              </Col>
495
              <Col xs="auto">
496
                <FormGroup>
497
                  <Label className={labelClasses} for="periodType">
498
                    {t('Period Types')}
499
                  </Label>
500
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
501
                  >
502
                    {periodTypeOptions.map((periodType, index) => (
503
                      <option value={periodType.value} key={periodType.value} >
504
                        {t(periodType.label)}
505
                      </option>
506
                    ))}
507
                  </CustomInput>
508
                </FormGroup>
509
              </Col>
510
              <Col xs="auto">
511
                <FormGroup className="form-group">
512
                  <Label className={labelClasses} for="basePeriodBeginsDatetime">
513
                    {t('Base Period Begins')}{t('(Optional)')}
514
                  </Label>
515
                  <Datetime id='basePeriodBeginsDatetime'
516
                    value={basePeriodBeginsDatetime}
517
                    inputProps={{ disabled: basePeriodBeginsDatetimeDisabled }}
518
                    onChange={onBasePeriodBeginsDatetimeChange}
519
                    isValidDate={getValidBasePeriodBeginsDatetimes}
520
                    closeOnSelect={true} />
521
                </FormGroup>
522
              </Col>
523
              <Col xs="auto">
524
                <FormGroup className="form-group">
525
                  <Label className={labelClasses} for="basePeriodEndsDatetime">
526
                    {t('Base Period Ends')}{t('(Optional)')}
527
                  </Label>
528
                  <Datetime id='basePeriodEndsDatetime'
529
                    value={basePeriodEndsDatetime}
530
                    inputProps={{ disabled: basePeriodEndsDatetimeDisabled }}
531
                    onChange={onBasePeriodEndsDatetimeChange}
532
                    isValidDate={getValidBasePeriodEndsDatetimes}
533
                    closeOnSelect={true} />
534
                </FormGroup>
535
              </Col>
536
              <Col xs="auto">
537
                <FormGroup className="form-group">
538
                  <Label className={labelClasses} for="reportingPeriodBeginsDatetime">
539
                    {t('Reporting Period Begins')}
540
                  </Label>
541
                  <Datetime id='reportingPeriodBeginsDatetime'
542
                    value={reportingPeriodBeginsDatetime}
543
                    onChange={onReportingPeriodBeginsDatetimeChange}
544
                    isValidDate={getValidReportingPeriodBeginsDatetimes}
545
                    closeOnSelect={true} />
546
                </FormGroup>
547
              </Col>
548
              <Col xs="auto">
549
                <FormGroup className="form-group">
550
                  <Label className={labelClasses} for="reportingPeriodEndsDatetime">
551
                    {t('Reporting Period Ends')}
552
                  </Label>
553
                  <Datetime id='reportingPeriodEndsDatetime'
554
                    value={reportingPeriodEndsDatetime}
555
                    onChange={onReportingPeriodEndsDatetimeChange}
556
                    isValidDate={getValidReportingPeriodEndsDatetimes}
557
                    closeOnSelect={true} />
558
                </FormGroup>
559
              </Col>
560
              <Col xs="auto">
561
                <FormGroup>
562
                  <br></br>
563
                  <ButtonGroup id="submit">
564
                    <Button color="success" disabled={isDisabled} >{t('Submit')}</Button>
565
                  </ButtonGroup>
566
                </FormGroup>
567
              </Col>
568
            </Row>
569
          </Form>
570
        </CardBody>
571
      </Card>
572
      <div className="card-deck">
573
        {cardSummaryList.map(cardSummaryItem => (
574
          <CardSummary key={cardSummaryItem['name']}
575
            rate={cardSummaryItem['increment_rate']}
576
            title={t('Reporting Period Savings CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
577
            color="success" 
578
            footnote={t('Per Unit Area')} 
579
            footvalue={cardSummaryItem['subtotal_per_unit_area']}
580
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
581
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
582
          </CardSummary>
583
        ))}
584
       
585
        <CardSummary 
586
          rate={totalInTCE['increment_rate'] || ''} 
587
          title={t('Reporting Period Savings CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Standard Coal'), 'UNIT': '(TCE)' })}
588
          color="warning" 
589
          footnote={t('Per Unit Area')} 
590
          footvalue={totalInTCE['value_per_unit_area']} 
591
          footunit="(TCE/M²)">
592
          {totalInTCE['value'] && <CountUp end={totalInTCE['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
593
        </CardSummary>
594
        <CardSummary 
595
          rate={totalInTCO2E['increment_rate'] || ''} 
596
          title={t('Reporting Period Decreased CATEGORY (Baseline - Actual) UNIT', { 'CATEGORY': t('Ton of Carbon Dioxide Emissions'), 'UNIT': '(TCO2E)' })}
597
          color="warning" 
598
          footnote={t('Per Unit Area')} 
599
          footvalue={totalInTCO2E['value_per_unit_area']} 
600
          footunit="(TCO2E/M²)">
601
          {totalInTCO2E['value'] && <CountUp end={totalInTCO2E['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
602
        </CardSummary>
603
      </div>
604
      <Row noGutters>
605
        <Col className="mb-3 pr-lg-2 mb-3">
606
          <SharePie data={TCEShareData} title={t('Ton of Standard Coal by Energy Category')} />
607
        </Col>
608
        <Col className="mb-3 pr-lg-2 mb-3">
609
          <SharePie data={TCO2EShareData} title={t('Carbon Dioxide Emissions by Energy Category')} />
610
        </Col>
611
      </Row>
612
      <LineChart reportingTitle={t('Reporting Period Savings CATEGORY VALUE UNIT', { 'CATEGORY': null, 'VALUE': null, 'UNIT': null })}
613
        baseTitle=''
614
        labels={storeLineChartLabels}
615
        data={storeLineChartData}
616
        options={storeLineChartOptions}>
617
      </LineChart>
618
619
      <LineChart reportingTitle={t('Related Parameters')}
620
        baseTitle=''
621
        labels={parameterLineChartLabels}
622
        data={parameterLineChartData}
623
        options={parameterLineChartOptions}>
624
      </LineChart>
625
      <br />
626
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={31} >
627
      </DetailedDataTable>
628
629
    </Fragment>
630
  );
631
};
632
633
export default withTranslation()(withRedirect(StoreSaving));
634