Passed
Push — master ( 9a2876...4f3f28 )
by Guangyu
04:12 queued 14s
created

src/components/MyEMS/Space/SpaceOutput.js   A

Complexity

Total Complexity 18
Complexity/F 0

Size

Lines of Code 520
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 18
eloc 458
mnd 18
bc 18
fnc 0
dl 0
loc 520
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 { getCookieValue, createCookie } from '../../../helpers/utils';
25
import withRedirect from '../../../hoc/withRedirect';
26
import { withTranslation } from 'react-i18next';
27
import { toast } from 'react-toastify';
28
import { APIBaseURL } from '../../../config';
29
import { periodTypeOptions } from '../common/PeriodTypeOptions';
30
import { comparisonTypeOptions } from '../common/ComparisonTypeOptions';
31
32
33
const ChildSpacesTable = loadable(() => import('../common/ChildSpacesTable'));
34
const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
35
36
const SpaceOutput = ({ 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
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
58
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
59
  const [comparisonType, setComparisonType] = useState('month-on-month');
60
  const [periodType, setPeriodType] = useState('daily');
61
  const [basePeriodBeginsDatetime, setBasePeriodBeginsDatetime] = useState(current_moment.clone().subtract(1, 'months').startOf('month'));
62
  const [basePeriodEndsDatetime, setBasePeriodEndsDatetime] = useState(current_moment.clone().subtract(1, 'months'));
63
  const [basePeriodBeginsDatetimeDisabled, setBasePeriodBeginsDatetimeDisabled] = useState(true);
64
  const [basePeriodEndsDatetimeDisabled, setBasePeriodEndsDatetimeDisabled] = useState(true);
65
  const [reportingPeriodBeginsDatetime, setReportingPeriodBeginsDatetime] = useState(current_moment.clone().startOf('month'));
66
  const [reportingPeriodEndsDatetime, setReportingPeriodEndsDatetime] = useState(current_moment);
67
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
68
  
69
  //Results
70
  const [cardSummaryList, setCardSummaryList] = useState([]);
71
  const [spaceLineChartLabels, setSpaceLineChartLabels] = useState([]);
72
  const [spaceLineChartData, setSpaceLineChartData] = useState({});
73
  const [spaceLineChartOptions, setSpaceLineChartOptions] = useState([]);
74
  
75
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
76
  const [parameterLineChartData, setParameterLineChartData] = useState({});
77
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
78
  
79
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
80
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
81
  
82
  const [childSpacesTableData, setChildSpacesTableData] = useState([]);
83
  const [childSpacesTableColumns, setChildSpacesTableColumns] = useState([{dataField: 'name', text: t('Child Spaces'), sort: true }]);
84
  
85
86
87
  useEffect(() => {
88
    let isResponseOK = false;
89
    fetch(APIBaseURL + '/spaces/tree', {
90
      method: 'GET',
91
      headers: {
92
        "Content-type": "application/json",
93
        "User-UUID": getCookieValue('user_uuid'),
94
        "Token": getCookieValue('token')
95
      },
96
      body: null,
97
98
    }).then(response => {
99
      console.log(response);
100
      if (response.ok) {
101
        isResponseOK = true;
102
      }
103
      return response.json();
104
    }).then(json => {
105
      console.log(json);
106
      if (isResponseOK) {
107
        // rename keys 
108
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
109
        setCascaderOptions(json);
110
        setSelectedSpaceName([json[0]].map(o => o.label));
111
        setSelectedSpaceID([json[0]].map(o => o.value));
112
      } else {
113
        toast.error(json.description);
114
      }
115
    }).catch(err => {
116
      console.log(err);
117
    });
118
119
  }, []);
120
  
121
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
122
  
123
  let onSpaceCascaderChange = (value, selectedOptions) => {
124
    console.log(value, selectedOptions);
125
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
126
    setSelectedSpaceID(value[value.length - 1]);
127
  }
128
129
130
  let onComparisonTypeChange = ({ target }) => {
131
    console.log(target.value);
132
    setComparisonType(target.value);
133
    if (target.value === 'year-over-year') {
134
      setBasePeriodBeginsDatetimeDisabled(true);
135
      setBasePeriodEndsDatetimeDisabled(true);
136
      setBasePeriodBeginsDatetime(moment(reportingPeriodBeginsDatetime).subtract(1, 'years'));
137
      setBasePeriodEndsDatetime(moment(reportingPeriodEndsDatetime).subtract(1, 'years'));
138
    } else if (target.value === 'month-on-month') {
139
      setBasePeriodBeginsDatetimeDisabled(true);
140
      setBasePeriodEndsDatetimeDisabled(true);
141
      setBasePeriodBeginsDatetime(moment(reportingPeriodBeginsDatetime).subtract(1, 'months'));
142
      setBasePeriodEndsDatetime(moment(reportingPeriodEndsDatetime).subtract(1, 'months'));
143
    } else if (target.value === 'free-comparison') {
144
      setBasePeriodBeginsDatetimeDisabled(false);
145
      setBasePeriodEndsDatetimeDisabled(false);
146
    } else if (target.value === 'none-comparison') {
147
      setBasePeriodBeginsDatetime(undefined);
148
      setBasePeriodEndsDatetime(undefined);
149
      setBasePeriodBeginsDatetimeDisabled(true);
150
      setBasePeriodEndsDatetimeDisabled(true);
151
    }
152
  }
153
154
  let onBasePeriodBeginsDatetimeChange = (newDateTime) => {
155
    setBasePeriodBeginsDatetime(newDateTime);
156
  }
157
158
  let onBasePeriodEndsDatetimeChange = (newDateTime) => {
159
    setBasePeriodEndsDatetime(newDateTime);
160
  }
161
162
  let onReportingPeriodBeginsDatetimeChange = (newDateTime) => {
163
    setReportingPeriodBeginsDatetime(newDateTime);
164
    if (comparisonType === 'year-over-year') {
165
      setBasePeriodBeginsDatetime(newDateTime.clone().subtract(1, 'years'));
166
    } else if (comparisonType === 'month-on-month') {
167
      setBasePeriodBeginsDatetime(newDateTime.clone().subtract(1, 'months'));
168
    }
169
  }
170
171
  let onReportingPeriodEndsDatetimeChange = (newDateTime) => {
172
    setReportingPeriodEndsDatetime(newDateTime);
173
    if (comparisonType === 'year-over-year') {
174
      setBasePeriodEndsDatetime(newDateTime.clone().subtract(1, 'years'));
175
    } else if (comparisonType === 'month-on-month') {
176
      setBasePeriodEndsDatetime(newDateTime.clone().subtract(1, 'months'));
177
    }
178
  }
179
180
  var getValidBasePeriodBeginsDatetimes = function (currentDate) {
181
    return currentDate.isBefore(moment(basePeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
182
  }
183
184
  var getValidBasePeriodEndsDatetimes = function (currentDate) {
185
    return currentDate.isAfter(moment(basePeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
186
  }
187
188
  var getValidReportingPeriodBeginsDatetimes = function (currentDate) {
189
    return currentDate.isBefore(moment(reportingPeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
190
  }
191
192
  var getValidReportingPeriodEndsDatetimes = function (currentDate) {
193
    return currentDate.isAfter(moment(reportingPeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
194
  }
195
196
  // Handler
197
  const handleSubmit = e => {
198
    e.preventDefault();
199
    console.log('handleSubmit');
200
    console.log(selectedSpaceID);
201
    console.log(comparisonType);
202
    console.log(periodType);
203
    console.log(basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
204
    console.log(basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
205
    console.log(reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
206
    console.log(reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
207
    
208
    // Reinitialize tables
209
    setDetailedDataTableData([]);
210
    setChildSpacesTableData([]);
211
212
    let isResponseOK = false;
213
    fetch(APIBaseURL + '/reports/spaceoutput?' +
214
      'spaceid=' + selectedSpaceID +
215
      '&periodtype=' + periodType +
216
      '&baseperiodstartdatetime=' + (basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
217
      '&baseperiodenddatetime=' + (basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
218
      '&reportingperiodstartdatetime=' + reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') +
219
      '&reportingperiodenddatetime=' + reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'), {
220
      method: 'GET',
221
      headers: {
222
        "Content-type": "application/json",
223
        "User-UUID": getCookieValue('user_uuid'),
224
        "Token": getCookieValue('token')
225
      },
226
      body: null,
227
228
    }).then(response => {
229
      if (response.ok) {
230
        isResponseOK = true;
231
      }
232
      return response.json();
233
    }).then(json => {
234
      if (isResponseOK) {
235
        console.log(json)
236
        let cardSummaryArray = []
237
        json['reporting_period']['names'].forEach((currentValue, index) => {
238
          let cardSummaryItem = {}
239
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
240
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
241
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals'][index];
242
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates'][index] * 100).toFixed(2) + "%";
243
          cardSummaryItem['subtotal_per_unit_area'] = json['reporting_period']['subtotals_per_unit_area'][index];
244
          cardSummaryArray.push(cardSummaryItem);
245
        });
246
        setCardSummaryList(cardSummaryArray);
247
248
        let timestamps = {}
249
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
250
          timestamps['a' + index] = currentValue;
251
        });
252
        setSpaceLineChartLabels(timestamps);
253
        
254
        let values = {}
255
        json['reporting_period']['values'].forEach((currentValue, index) => {
256
          values['a' + index] = currentValue;
257
        });
258
        setSpaceLineChartData(values);
259
        
260
        let names = Array();
261
        json['reporting_period']['names'].forEach((currentValue, index) => {
262
          let unit = json['reporting_period']['units'][index];
263
          names.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
264
        });
265
        setSpaceLineChartOptions(names);
266
       
267
        timestamps = {}
268
        json['parameters']['timestamps'].forEach((currentValue, index) => {
269
          timestamps['a' + index] = currentValue;
270
        });
271
        setParameterLineChartLabels(timestamps);
272
273
        values = {}
274
        json['parameters']['values'].forEach((currentValue, index) => {
275
          values['a' + index] = currentValue;
276
        });
277
        setParameterLineChartData(values);
278
      
279
        names = Array();
280
        json['parameters']['names'].forEach((currentValue, index) => {
281
          if (currentValue.startsWith('TARIFF-')) {
282
            currentValue = t('Tariff') + currentValue.replace('TARIFF-', '-');
283
          }
284
          
285
          names.push({ 'value': 'a' + index, 'label': currentValue });
286
        });
287
        setParameterLineChartOptions(names);
288
      
289
        let detailed_value_list = [];
290
        json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
291
          let detailed_value = {};
292
          detailed_value['id'] = timestampIndex;
293
          detailed_value['startdatetime'] = currentTimestamp;
294
          json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
295
            detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values'][energyCategoryIndex][timestampIndex].toFixed(2);
296
          });
297
          detailed_value_list.push(detailed_value);
298
        });
299
300
        let detailed_value = {};
301
        detailed_value['id'] = detailed_value_list.length;
302
        detailed_value['startdatetime'] = t('Subtotal');
303
        json['reporting_period']['subtotals'].forEach((currentValue, index) => {
304
            detailed_value['a' + index] = currentValue.toFixed(2);
305
          });
306
        detailed_value_list.push(detailed_value);
307
        setDetailedDataTableData(detailed_value_list);
308
        
309
        let detailed_column_list = [];
310
        detailed_column_list.push({
311
          dataField: 'startdatetime',
312
          text: t('Datetime'),
313
          sort: true
314
        })
315
        json['reporting_period']['names'].forEach((currentValue, index) => {
316
          let unit = json['reporting_period']['units'][index];
317
          detailed_column_list.push({
318
            dataField: 'a' + index,
319
            text: currentValue + ' (' + unit + ')',
320
            sort: true
321
          })
322
        });
323
        setDetailedDataTableColumns(detailed_column_list);
324
        
325
        let child_space_value_list = [];
326
        json['child_space']['child_space_names_array'][0].forEach((currentSpaceName, spaceIndex) => {
327
          let child_space_value = {};
328
          child_space_value['id'] = spaceIndex;
329
          child_space_value['name'] = currentSpaceName;
330
          json['child_space']['energy_category_names'].forEach((currentValue, energyCategoryIndex) => {
331
            child_space_value['a' + energyCategoryIndex] = json['child_space']['subtotals_array'][energyCategoryIndex][spaceIndex].toFixed(2);
332
          });
333
          child_space_value_list.push(child_space_value);
334
        });
335
336
        setChildSpacesTableData(child_space_value_list);
337
338
        let child_space_column_list = [];
339
        child_space_column_list.push({
340
          dataField: 'name',
341
          text: t('Child Spaces'),
342
          sort: true
343
        });
344
        json['child_space']['energy_category_names'].forEach((currentValue, index) => {
345
          let unit = json['child_space']['units'][index];
346
          child_space_column_list.push({
347
            dataField: 'a' + index,
348
            text: currentValue + ' (' + unit + ')',
349
            sort: true
350
          });
351
        });
352
353
        setChildSpacesTableColumns(child_space_column_list);
354
      
355
      } else {
356
        toast.error(json.description)
357
      }
358
    }).catch(err => {
359
      console.log(err);
360
    });
361
  };
362
363
  return (
364
    <Fragment>
365
      <div>
366
        <Breadcrumb>
367
          <BreadcrumbItem>{t('Space Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Output')}</BreadcrumbItem>
368
        </Breadcrumb>
369
      </div>
370
      <Card className="bg-light mb-3">
371
        <CardBody className="p-3">
372
          <Form onSubmit={handleSubmit}>
373
            <Row form>
374
              <Col xs="auto">
375
                <FormGroup className="form-group">
376
                  <Label className={labelClasses} for="space">
377
                    {t('Space')}
378
                  </Label>
379
                  <br />
380
                  <Cascader options={cascaderOptions}
381
                    onChange={onSpaceCascaderChange}
382
                    changeOnSelect
383
                    expandTrigger="hover">
384
                    <Input value={selectedSpaceName || ''} readOnly />
385
                  </Cascader>
386
                </FormGroup>
387
              </Col>
388
              <Col xs="auto">
389
                <FormGroup>
390
                  <Label className={labelClasses} for="comparisonType">
391
                    {t('Comparison Types')}
392
                  </Label>
393
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
394
                    defaultValue="month-on-month"
395
                    onChange={onComparisonTypeChange}
396
                  >
397
                    {comparisonTypeOptions.map((comparisonType, index) => (
398
                      <option value={comparisonType.value} key={comparisonType.value} >
399
                        {t(comparisonType.label)}
400
                      </option>
401
                    ))}
402
                  </CustomInput>
403
                </FormGroup>
404
              </Col>
405
              <Col xs="auto">
406
                <FormGroup>
407
                  <Label className={labelClasses} for="periodType">
408
                    {t('Period Types')}
409
                  </Label>
410
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
411
                  >
412
                    {periodTypeOptions.map((periodType, index) => (
413
                      <option value={periodType.value} key={periodType.value} >
414
                        {t(periodType.label)}
415
                      </option>
416
                    ))}
417
                  </CustomInput>
418
                </FormGroup>
419
              </Col>
420
              <Col xs="auto">
421
                <FormGroup className="form-group">
422
                  <Label className={labelClasses} for="basePeriodBeginsDatetime">
423
                    {t('Base Period Begins')}{t('(Optional)')}
424
                  </Label>
425
                  <Datetime id='basePeriodBeginsDatetime'
426
                    value={basePeriodBeginsDatetime}
427
                    inputProps={{ disabled: basePeriodBeginsDatetimeDisabled }}
428
                    onChange={onBasePeriodBeginsDatetimeChange}
429
                    isValidDate={getValidBasePeriodBeginsDatetimes}
430
                    closeOnSelect={true} />
431
                </FormGroup>
432
              </Col>
433
              <Col xs="auto">
434
                <FormGroup className="form-group">
435
                  <Label className={labelClasses} for="basePeriodEndsDatetime">
436
                    {t('Base Period Ends')}{t('(Optional)')}
437
                  </Label>
438
                  <Datetime id='basePeriodEndsDatetime'
439
                    value={basePeriodEndsDatetime}
440
                    inputProps={{ disabled: basePeriodEndsDatetimeDisabled }}
441
                    onChange={onBasePeriodEndsDatetimeChange}
442
                    isValidDate={getValidBasePeriodEndsDatetimes}
443
                    closeOnSelect={true} />
444
                </FormGroup>
445
              </Col>
446
              <Col xs="auto">
447
                <FormGroup className="form-group">
448
                  <Label className={labelClasses} for="reportingPeriodBeginsDatetime">
449
                    {t('Reporting Period Begins')}
450
                  </Label>
451
                  <Datetime id='reportingPeriodBeginsDatetime'
452
                    value={reportingPeriodBeginsDatetime}
453
                    onChange={onReportingPeriodBeginsDatetimeChange}
454
                    isValidDate={getValidReportingPeriodBeginsDatetimes}
455
                    closeOnSelect={true} />
456
                </FormGroup>
457
              </Col>
458
              <Col xs="auto">
459
                <FormGroup className="form-group">
460
                  <Label className={labelClasses} for="reportingPeriodEndsDatetime">
461
                    {t('Reporting Period Ends')}
462
                  </Label>
463
                  <Datetime id='reportingPeriodEndsDatetime'
464
                    value={reportingPeriodEndsDatetime}
465
                    onChange={onReportingPeriodEndsDatetimeChange}
466
                    isValidDate={getValidReportingPeriodEndsDatetimes}
467
                    closeOnSelect={true} />
468
                </FormGroup>
469
              </Col>
470
              <Col xs="auto">
471
                <FormGroup>
472
                  <br></br>
473
                  <ButtonGroup id="submit">
474
                    <Button color="success" >{t('Submit')}</Button>
475
                  </ButtonGroup>
476
                </FormGroup>
477
              </Col>
478
            </Row>
479
          </Form>
480
        </CardBody>
481
      </Card>
482
      <div className="card-deck">
483
        {cardSummaryList.map(cardSummaryItem => (
484
          <CardSummary key={cardSummaryItem['name']}
485
            rate={cardSummaryItem['increment_rate']}
486
            title={t('Reporting Period Output CATEGORY UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
487
            color="success" 
488
            footnote={t('Per Unit Area')} 
489
            footvalue={cardSummaryItem['subtotal_per_unit_area']}
490
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
491
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
492
          </CardSummary>
493
        ))}
494
      </div>
495
      <LineChart reportingTitle={t('Reporting Period Output CATEGORY VALUE UNIT', { 'CATEGORY': null, 'VALUE': null, 'UNIT': null })}
496
         baseTitle=''
497
        labels={spaceLineChartLabels}
498
        data={spaceLineChartData}
499
        options={spaceLineChartOptions}>
500
      </LineChart>
501
502
      <LineChart reportingTitle={t('Related Parameters')}
503
        baseTitle=''
504
        labels={parameterLineChartLabels}
505
        data={parameterLineChartData}
506
        options={parameterLineChartOptions}>
507
      </LineChart>
508
509
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
510
      </DetailedDataTable>
511
      <br />
512
      <ChildSpacesTable data={childSpacesTableData} title={t('Child Spaces Data')} columns={childSpacesTableColumns}>
513
      </ChildSpacesTable>
514
515
    </Fragment>
516
  );
517
};
518
519
export default withTranslation()(withRedirect(SpaceOutput));
520