Passed
Push — master ( 7c0f16...acabf6 )
by Guangyu
10:19 queued 42s
created

myems-web/src/components/MyEMS/Shopfloor/ShopfloorEnergyItem.js   B

Complexity

Total Complexity 44
Complexity/F 0

Size

Lines of Code 852
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 44
eloc 720
dl 0
loc 852
rs 8.76
c 0
b 0
f 0
mnd 44
bc 44
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/Shopfloor/ShopfloorEnergyItem.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import React, { Fragment, useEffect, useState, useContext } 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 moment from 'moment';
20
import loadable from '@loadable/component';
21
import Cascader from 'rc-cascader';
22
import CardSummary from '../common/CardSummary';
23
import MultiTrendChart from '../common/MultiTrendChart';
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 ButtonIcon from '../../common/ButtonIcon';
30
import { APIBaseURL } from '../../../config';
31
import { periodTypeOptions } from '../common/PeriodTypeOptions';
32
import { comparisonTypeOptions } from '../common/ComparisonTypeOptions';
33
import DateRangePickerWrapper from '../common/DateRangePickerWrapper';
34
import { endOfDay} from 'date-fns';
35
import AppContext from '../../../context/Context';
36
import MultipleLineChart from '../common/MultipleLineChart';
37
38
const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
39
40
const ShopfloorEnergyItem = ({ setRedirect, setRedirectUrl, t }) => {
41
  let current_moment = moment();
42
  useEffect(() => {
43
    let is_logged_in = getCookieValue('is_logged_in');
44
    let user_name = getCookieValue('user_name');
45
    let user_display_name = getCookieValue('user_display_name');
46
    let user_uuid = getCookieValue('user_uuid');
47
    let token = getCookieValue('token');
48
    if (is_logged_in === null || !is_logged_in) {
49
      setRedirectUrl(`/authentication/basic/login`);
50
      setRedirect(true);
51
    } else {
52
      //update expires time of cookies
53
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
54
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
55
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
56
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
57
      createCookie('token', token, 1000 * 60 * 60 * 8);
58
    }
59
  });
60
61
62
  // State
63
  // Query Parameters
64
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
65
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
66
  const [shopfloorList, setShopfloorList] = useState([]);
67
  const [selectedShopfloor, setSelectedShopfloor] = useState(undefined);
68
  const [comparisonType, setComparisonType] = useState('month-on-month');
69
  const [periodType, setPeriodType] = useState('daily');
70
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
71
  const [basePeriodDateRange, setBasePeriodDateRange] = useState([current_moment.clone().subtract(1, 'months').startOf('month').toDate(), current_moment.clone().subtract(1, 'months').toDate()]);
72
  const [basePeriodDateRangePickerDisabled, setBasePeriodDateRangePickerDisabled] = useState(true);
73
  const [reportingPeriodDateRange, setReportingPeriodDateRange] = useState([current_moment.clone().startOf('month').toDate(), current_moment.toDate()]);
74
  const dateRangePickerLocale = {
75
    sunday: t('sunday'),
76
    monday: t('monday'),
77
    tuesday: t('tuesday'),
78
    wednesday: t('wednesday'),
79
    thursday: t('thursday'),
80
    friday: t('friday'),
81
    saturday: t('saturday'),
82
    ok: t('ok'),
83
    today: t('today'),
84
    yesterday: t('yesterday'),
85
    hours: t('hours'),
86
    minutes: t('minutes'),
87
    seconds: t('seconds'),
88
    last7Days: t('last7Days'),
89
    formattedMonthPattern: 'yyyy-MM-dd'
90
  };
91
  const dateRangePickerStyle = { display: 'block', zIndex: 10};
92
  const { language } = useContext(AppContext);
93
94
  // buttons
95
  const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
96
  const [spinnerHidden, setSpinnerHidden] = useState(true);
97
  const [exportButtonHidden, setExportButtonHidden] = useState(true);
98
99
  //Results
100
  const [cardSummaryList, setCardSummaryList] = useState([]);
101
  const [sharePieList, setSharePieList] = useState([]);
102
103
  const [shopfloorBaseAndReportingNames, setShopfloorBaseAndReportingNames] = useState({"a0":""});
104
  const [shopfloorBaseAndReportingUnits, setShopfloorBaseAndReportingUnits] = useState({"a0":"()"});
105
106
  const [shopfloorBaseLabels, setShopfloorBaseLabels] = useState({"a0": []});
107
  const [shopfloorBaseData, setShopfloorBaseData] = useState({"a0": []});
108
  const [shopfloorBaseSubtotals, setShopfloorBaseSubtotals] = useState({"a0": (0).toFixed(2)});
109
110
  const [shopfloorReportingLabels, setShopfloorReportingLabels] = useState({"a0": []});
111
  const [shopfloorReportingData, setShopfloorReportingData] = useState({"a0": []});
112
  const [shopfloorReportingSubtotals, setShopfloorReportingSubtotals] = useState({"a0": (0).toFixed(2)});
113
114
  const [shopfloorReportingRates, setShopfloorReportingRates] = useState({"a0": []});
115
  const [shopfloorReportingOptions, setShopfloorReportingOptions] = useState([]);
116
117
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
118
  const [parameterLineChartData, setParameterLineChartData] = useState({});
119
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
120
121
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
122
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
123
  const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
124
  
125
  useEffect(() => {
126
    let isResponseOK = false;
127
    fetch(APIBaseURL + '/spaces/tree', {
128
      method: 'GET',
129
      headers: {
130
        "Content-type": "application/json",
131
        "User-UUID": getCookieValue('user_uuid'),
132
        "Token": getCookieValue('token')
133
      },
134
      body: null,
135
136
    }).then(response => {
137
      console.log(response);
138
      if (response.ok) {
139
        isResponseOK = true;
140
      }
141
      return response.json();
142
    }).then(json => {
143
      console.log(json);
144
      if (isResponseOK) {
145
        // rename keys 
146
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
147
        setCascaderOptions(json);
148
        setSelectedSpaceName([json[0]].map(o => o.label));
149
        setSelectedSpaceID([json[0]].map(o => o.value));
150
        // get Shopfloors by root Space ID
151
        let isResponseOK = false;
152
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/shopfloors', {
153
          method: 'GET',
154
          headers: {
155
            "Content-type": "application/json",
156
            "User-UUID": getCookieValue('user_uuid'),
157
            "Token": getCookieValue('token')
158
          },
159
          body: null,
160
161
        }).then(response => {
162
          if (response.ok) {
163
            isResponseOK = true;
164
          }
165
          return response.json();
166
        }).then(json => {
167
          if (isResponseOK) {
168
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
169
            console.log(json);
170
            setShopfloorList(json[0]);
171
            if (json[0].length > 0) {
172
              setSelectedShopfloor(json[0][0].value);
173
              // enable submit button
174
              setSubmitButtonDisabled(false);
175
            } else {
176
              setSelectedShopfloor(undefined);
177
              // disable submit button
178
              setSubmitButtonDisabled(true);
179
            }
180
          } else {
181
            toast.error(t(json.description))
182
          }
183
        }).catch(err => {
184
          console.log(err);
185
        });
186
        // end of get Shopfloors by root Space ID
187
      } else {
188
        toast.error(t(json.description));
189
      }
190
    }).catch(err => {
191
      console.log(err);
192
    });
193
194
  }, []);
195
196
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
197
198
199
  let onSpaceCascaderChange = (value, selectedOptions) => {
200
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
201
    setSelectedSpaceID(value[value.length - 1]);
202
203
    let isResponseOK = false;
204
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/shopfloors', {
205
      method: 'GET',
206
      headers: {
207
        "Content-type": "application/json",
208
        "User-UUID": getCookieValue('user_uuid'),
209
        "Token": getCookieValue('token')
210
      },
211
      body: null,
212
213
    }).then(response => {
214
      if (response.ok) {
215
        isResponseOK = true;
216
      }
217
      return response.json();
218
    }).then(json => {
219
      if (isResponseOK) {
220
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
221
        console.log(json)
222
        setShopfloorList(json[0]);
223
        if (json[0].length > 0) {
224
          setSelectedShopfloor(json[0][0].value);
225
          // enable submit button
226
          setSubmitButtonDisabled(false);
227
        } else {
228
          setSelectedShopfloor(undefined);
229
          // disable submit button
230
          setSubmitButtonDisabled(true);
231
        }
232
      } else {
233
        toast.error(t(json.description))
234
      }
235
    }).catch(err => {
236
      console.log(err);
237
    });
238
  }
239
240
241
  let onComparisonTypeChange = ({ target }) => {
242
    console.log(target.value);
243
    setComparisonType(target.value);
244
    if (target.value === 'year-over-year') {
245
      setBasePeriodDateRangePickerDisabled(true);
246
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'years').toDate(),
247
        moment(reportingPeriodDateRange[1]).subtract(1, 'years').toDate()]);
248
    } else if (target.value === 'month-on-month') {
249
      setBasePeriodDateRangePickerDisabled(true);
250
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'months').toDate(),
251
        moment(reportingPeriodDateRange[1]).subtract(1, 'months').toDate()]);
252
    } else if (target.value === 'free-comparison') {
253
      setBasePeriodDateRangePickerDisabled(false);
254
    } else if (target.value === 'none-comparison') {
255
      setBasePeriodDateRange([null, null]);
256
      setBasePeriodDateRangePickerDisabled(true);
257
    }
258
  };
259
260
  // Callback fired when value changed
261
  let onBasePeriodChange = (DateRange) => {
262
    if(DateRange == null) {
263
      setBasePeriodDateRange([null, null]);
264
    } else {
265
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
266
        // if the user did not change time value, set the default time to the end of day
267
        DateRange[1] = endOfDay(DateRange[1]);
268
      }
269
      setBasePeriodDateRange([DateRange[0], DateRange[1]]);
270
    }
271
  };
272
273
  // Callback fired when value changed
274
  let onReportingPeriodChange = (DateRange) => {
275
    if(DateRange == null) {
276
      setReportingPeriodDateRange([null, null]);
277
    } else {
278
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
279
        // if the user did not change time value, set the default time to the end of day
280
        DateRange[1] = endOfDay(DateRange[1]);
281
      }
282
      setReportingPeriodDateRange([DateRange[0], DateRange[1]]);
283
      if (comparisonType === 'year-over-year') {
284
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'years').toDate(), moment(DateRange[1]).clone().subtract(1, 'years').toDate()]);
285
      } else if (comparisonType === 'month-on-month') {
286
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'months').toDate(), moment(DateRange[1]).clone().subtract(1, 'months').toDate()]);
287
      }
288
    }
289
  };
290
291
  // Callback fired when value clean
292
  let onBasePeriodClean = event => {
293
    setBasePeriodDateRange([null, null]);
294
  };
295
296
  // Callback fired when value clean
297
  let onReportingPeriodClean = event => {
298
    setReportingPeriodDateRange([null, null]);
299
  };
300
301
  const isBasePeriodTimestampExists = (base_period_data) => {
302
    const timestamps = base_period_data['timestamps'];
303
304
    if (timestamps.length === 0) {
305
      return false;
306
    }
307
308
    for (let i = 0; i < timestamps.length; i++) {
309
      if (timestamps[i].length > 0) {
310
        return true;
311
      }
312
    }
313
    return false
314
  }
315
316
  // Handler
317
  const handleSubmit = e => {
318
    e.preventDefault();
319
    console.log('handleSubmit');
320
    console.log(selectedSpaceID);
321
    console.log(selectedShopfloor);
322
    console.log(comparisonType);
323
    console.log(periodType);
324
    console.log(basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : null)
325
    console.log(basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : null)
326
    console.log(moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss'))
327
    console.log(moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss'));
328
329
    // disable submit button
330
    setSubmitButtonDisabled(true);
331
    // show spinner
332
    setSpinnerHidden(false);
333
    // hide export button
334
    setExportButtonHidden(true)
335
336
    // Reinitialize tables
337
    setDetailedDataTableData([]);
338
    
339
    let isResponseOK = false;
340
    fetch(APIBaseURL + '/reports/shopfloorenergyitem?' +
341
      'shopfloorid=' + selectedShopfloor +
342
      '&periodtype=' + periodType +
343
      '&baseperiodstartdatetime=' + (basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : '') +
344
      '&baseperiodenddatetime=' + (basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : '') +
345
      '&reportingperiodstartdatetime=' + moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') +
346
      '&reportingperiodenddatetime=' + moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') + 
347
      '&language=' + language, {
348
      method: 'GET',
349
      headers: {
350
        "Content-type": "application/json",
351
        "User-UUID": getCookieValue('user_uuid'),
352
        "Token": getCookieValue('token')
353
      },
354
      body: null,
355
356
    }).then(response => {
357
      if (response.ok) {
358
        isResponseOK = true;
359
      };
360
      return response.json();
361
    }).then(json => {
362
      if (isResponseOK) {
363
        console.log(json)
364
365
        let cardSummaryArray = []
366
        json['reporting_period']['names'].forEach((currentValue, index) => {
367
          let cardSummaryItem = {}
368
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
369
          cardSummaryItem['energy_category_name'] = json['reporting_period']['energy_category_names'][index];
370
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
371
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals'][index];
372
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates'][index] * 100).toFixed(2) + "%";
373
          cardSummaryItem['subtotal_per_unit_area'] = json['reporting_period']['subtotals_per_unit_area'][index];
374
          cardSummaryArray.push(cardSummaryItem);
375
        });
376
        setCardSummaryList(cardSummaryArray);
377
        
378
        let sharePieDict = {}
379
        let energyCategoryDict = {};
380
        json['reporting_period']['names'].forEach((currentValue, index) => {
381
          let sharePieSubItem = {}
382
          sharePieSubItem['id'] = index;
383
          sharePieSubItem['name'] = json['reporting_period']['names'][index];
384
          sharePieSubItem['value'] = json['reporting_period']['subtotals'][index];
385
          sharePieSubItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
386
          
387
          let current_energy_category_id = json['reporting_period']['energy_category_ids'][index]
388
          if (current_energy_category_id in sharePieDict) {
389
            sharePieDict[current_energy_category_id].push(sharePieSubItem);
390
          } else {
391
            sharePieDict[current_energy_category_id] = [];
392
            sharePieDict[current_energy_category_id].push(sharePieSubItem);
393
          }
394
395
          if (!(current_energy_category_id in energyCategoryDict)) {
396
            energyCategoryDict[current_energy_category_id] = 
397
            {'name': json['reporting_period']['energy_category_names'][index],
398
             'unit': json['reporting_period']['units'][index],
399
            }
400
          }
401
        });
402
        let sharePieArray = [];
403
        for (let current_energy_category_id in sharePieDict) {
404
          let sharePieItem = {}
405
          sharePieItem['data'] = sharePieDict[current_energy_category_id];
406
          sharePieItem['energy_category_name'] = energyCategoryDict[current_energy_category_id]['name'];
407
          sharePieItem['unit'] = energyCategoryDict[current_energy_category_id]['unit'];
408
          sharePieArray.push(sharePieItem);
409
        }
410
411
        setSharePieList(sharePieArray);
412
413
        let base_timestamps = {}
414
        json['base_period']['timestamps'].forEach((currentValue, index) => {
415
          base_timestamps['a' + index] = currentValue;
416
        });
417
        setShopfloorBaseLabels(base_timestamps)
418
419
        let base_values = {}
420
        json['base_period']['values'].forEach((currentValue, index) => {
421
          base_values['a' + index] = currentValue;
422
        });
423
        setShopfloorBaseData(base_values)
424
425
        /*
426
        * Tip:
427
        *     base_names === reporting_names
428
        *     base_units === reporting_units
429
        * */
430
431
        let base_and_reporting_names = {}
432
        json['reporting_period']['names'].forEach((currentValue, index) => {
433
          base_and_reporting_names['a' + index] = currentValue;
434
        });
435
        setShopfloorBaseAndReportingNames(base_and_reporting_names)
436
437
        let base_and_reporting_units = {}
438
        json['reporting_period']['units'].forEach((currentValue, index) => {
439
          base_and_reporting_units['a' + index] = "("+currentValue+")";
440
        });
441
        setShopfloorBaseAndReportingUnits(base_and_reporting_units)
442
443
        let base_subtotals = {}
444
        json['base_period']['subtotals'].forEach((currentValue, index) => {
445
          base_subtotals['a' + index] = currentValue.toFixed(2);
446
        });
447
        setShopfloorBaseSubtotals(base_subtotals)
448
449
        let reporting_timestamps = {}
450
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
451
          reporting_timestamps['a' + index] = currentValue;
452
        });
453
        setShopfloorReportingLabels(reporting_timestamps);
454
455
        let reporting_values = {}
456
        json['reporting_period']['values'].forEach((currentValue, index) => {
457
          reporting_values['a' + index] = currentValue;
458
        });
459
        setShopfloorReportingData(reporting_values);
460
461
        let reporting_subtotals = {}
462
        json['reporting_period']['subtotals'].forEach((currentValue, index) => {
463
          reporting_subtotals['a' + index] = currentValue.toFixed(2);
464
        });
465
        setShopfloorReportingSubtotals(reporting_subtotals);
466
467
        let rates = {}
468
        json['reporting_period']['rates'].forEach((currentValue, index) => {
469
          let currentRate = Array();
470
          currentValue.forEach((rate) => {
471
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
472
          });
473
          rates['a' + index] = currentRate;
474
        });
475
        setShopfloorReportingRates(rates)
476
477
        let options = Array();
478
        json['reporting_period']['names'].forEach((currentValue, index) => {
479
          let unit = json['reporting_period']['units'][index];
480
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
481
        });
482
        setShopfloorReportingOptions(options);
483
       
484
        let timestamps = {}
485
        json['parameters']['timestamps'].forEach((currentValue, index) => {
486
          timestamps['a' + index] = currentValue;
487
        });
488
        setParameterLineChartLabels(timestamps);
489
490
        let values = {}
491
        json['parameters']['values'].forEach((currentValue, index) => {
492
          values['a' + index] = currentValue;
493
        });
494
        setParameterLineChartData(values);
495
      
496
        let names = Array();
497
        json['parameters']['names'].forEach((currentValue, index) => {
498
          
499
          names.push({ 'value': 'a' + index, 'label': currentValue });
500
        });
501
        setParameterLineChartOptions(names);
502
503
        let detailed_value_list = [];
504
        if (json['reporting_period']['timestamps'].length > 0) {
505
          json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
506
            let detailed_value = {};
507
            detailed_value['id'] = timestampIndex;
508
            detailed_value['startdatetime'] = currentTimestamp;
509
            json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
510
              detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values'][energyCategoryIndex][timestampIndex];
511
            });
512
            detailed_value_list.push(detailed_value);
513
          });
514
        };
515
516
        if(!isBasePeriodTimestampExists(json['base_period'])) {
517
          let detailed_value = {};
518
          detailed_value['id'] = detailed_value_list.length;
519
          detailed_value['startdatetime'] = t('Subtotal');
520
          json['reporting_period']['subtotals'].forEach((currentValue, index) => {
521
            detailed_value['a' + index] = currentValue;
522
          });
523
          detailed_value_list.push(detailed_value);
524
          setTimeout(() => {
525
            setDetailedDataTableData(detailed_value_list);
526
          }, 0)
527
528
          let detailed_column_list = [];
529
          detailed_column_list.push({
530
            dataField: 'startdatetime',
531
            text: t('Datetime'),
532
            sort: true
533
          });
534
          json['reporting_period']['names'].forEach((currentValue, index) => {
535
            let unit = json['reporting_period']['units'][index];
536
            detailed_column_list.push({
537
              dataField: 'a' + index,
538
              text: currentValue + ' (' + unit + ')',
539
              sort: true,
540
              formatter: function (decimalValue) {
541
                if (typeof decimalValue === 'number') {
542
                  return decimalValue.toFixed(2);
543
                } else {
544
                  return null;
545
                }
546
              }
547
            });
548
          });
549
          setDetailedDataTableColumns(detailed_column_list);
550
        }else {
551
          /*
552
          * Tip:
553
          *     json['base_period']['names'] ===  json['reporting_period']['names']
554
          *     json['base_period']['units'] ===  json['reporting_period']['units']
555
          * */
556
          let detailed_column_list = [];
557
          detailed_column_list.push({
558
            dataField: 'basePeriodDatetime',
559
            text: t('Base Period') + ' - ' + t('Datetime'),
560
            sort: true
561
          })
562
563
          json['base_period']['names'].forEach((currentValue, index) => {
564
            let unit = json['base_period']['units'][index];
565
            detailed_column_list.push({
566
              dataField: 'a' + index,
567
              text: t('Base Period') + ' - ' + currentValue + ' (' + unit + ')',
568
              sort: true,
569
              formatter: function (decimalValue) {
570
                if (typeof decimalValue === 'number') {
571
                  return decimalValue.toFixed(2);
572
                } else {
573
                  return null;
574
                }
575
              }
576
            })
577
          });
578
579
          detailed_column_list.push({
580
            dataField: 'reportingPeriodDatetime',
581
            text: t('Reporting Period') + ' - ' + t('Datetime'),
582
            sort: true
583
          })
584
585
          json['reporting_period']['names'].forEach((currentValue, index) => {
586
            let unit = json['reporting_period']['units'][index];
587
            detailed_column_list.push({
588
              dataField: 'b' + index,
589
              text: t('Reporting Period') + ' - ' + currentValue + ' (' + unit + ')',
590
              sort: true,
591
              formatter: function (decimalValue) {
592
                if (typeof decimalValue === 'number') {
593
                  return decimalValue.toFixed(2);
594
                } else {
595
                  return null;
596
                }
597
              }
598
            })
599
          });
600
          setDetailedDataTableColumns(detailed_column_list);
601
602
          let detailed_value_list = [];
603
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
604
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
605
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
606
            for (let index = 0; index < max_timestamps_length; index++) {
607
              let detailed_value = {};
608
              detailed_value['id'] = index;
609
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
610
              json['base_period']['values'].forEach((currentValue, energyCategoryIndex) => {
611
                detailed_value['a' + energyCategoryIndex] = index < json['base_period']['values'][energyCategoryIndex].length? json['base_period']['values'][energyCategoryIndex][index] : null;
612
              });
613
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
614
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
615
                detailed_value['b' + energyCategoryIndex] = index < json['reporting_period']['values'][energyCategoryIndex].length? json['reporting_period']['values'][energyCategoryIndex][index] : null;
616
              });
617
              detailed_value_list.push(detailed_value);
618
            }
619
620
            let detailed_value = {};
621
            detailed_value['id'] = detailed_value_list.length;
622
            detailed_value['basePeriodDatetime'] = t('Subtotal');
623
            json['base_period']['subtotals'].forEach((currentValue, index) => {
624
              detailed_value['a' + index] = currentValue;
625
            });
626
            detailed_value['reportingPeriodDatetime'] = t('Subtotal');
627
            json['reporting_period']['subtotals'].forEach((currentValue, index) => {
628
              detailed_value['b' + index] = currentValue;
629
            });
630
            detailed_value_list.push(detailed_value);
631
            setTimeout( () => {
632
              setDetailedDataTableData(detailed_value_list);
633
            }, 0)
634
          }
635
        }
636
        
637
        setExcelBytesBase64(json['excel_bytes_base64']);
638
639
        // enable submit button
640
        setSubmitButtonDisabled(false);
641
        // hide spinner
642
        setSpinnerHidden(true);
643
        // show export button
644
        setExportButtonHidden(false);
645
        
646
      } else {
647
        toast.error(t(json.description))
648
      }
649
    }).catch(err => {
650
      console.log(err);
651
    });
652
  };
653
654
  const handleExport = e => {
655
    e.preventDefault();
656
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
657
    const fileName = 'shopfloorenergyitem.xlsx'
658
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
659
    fetch(fileUrl)
660
        .then(response => response.blob())
661
        .then(blob => {
662
            var link = window.document.createElement("a");
663
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
664
            link.download = fileName;
665
            document.body.appendChild(link);
666
            link.click();
667
            document.body.removeChild(link);
668
        });
669
  };
670
  
671
672
  return (
673
    <Fragment>
674
      <div>
675
        <Breadcrumb>
676
          <BreadcrumbItem>{t('Shopfloor Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Energy Item Data')}</BreadcrumbItem>
677
        </Breadcrumb>
678
      </div>
679
      <Card className="bg-light mb-3">
680
        <CardBody className="p-3">
681
          <Form onSubmit={handleSubmit}>
682
            <Row form>
683
              <Col xs={6} sm={3}>
684
                <FormGroup className="form-group">
685
                  <Label className={labelClasses} for="space">
686
                    {t('Space')}
687
                  </Label>
688
                  <br />
689
                  <Cascader options={cascaderOptions}
690
                    onChange={onSpaceCascaderChange}
691
                    changeOnSelect
692
                    expandTrigger="hover">
693
                    <Input value={selectedSpaceName || ''} readOnly />
694
                  </Cascader>
695
                </FormGroup>
696
              </Col>
697
              <Col xs="auto">
698
                <FormGroup>
699
                  <Label className={labelClasses} for="shopfloorSelect">
700
                    {t('Shopfloor')}
701
                  </Label>
702
                  <CustomInput type="select" id="shopfloorSelect" name="shopfloorSelect" onChange={({ target }) => setSelectedShopfloor(target.value)}
703
                  >
704
                    {shopfloorList.map((shopfloor, index) => (
705
                      <option value={shopfloor.value} key={shopfloor.value}>
706
                        {shopfloor.label}
707
                      </option>
708
                    ))}
709
                  </CustomInput>
710
                </FormGroup>
711
              </Col>
712
              <Col xs="auto">
713
                <FormGroup>
714
                  <Label className={labelClasses} for="comparisonType">
715
                    {t('Comparison Types')}
716
                  </Label>
717
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
718
                    defaultValue="month-on-month"
719
                    onChange={onComparisonTypeChange}
720
                  >
721
                    {comparisonTypeOptions.map((comparisonType, index) => (
722
                      <option value={comparisonType.value} key={comparisonType.value} >
723
                        {t(comparisonType.label)}
724
                      </option>
725
                    ))}
726
                  </CustomInput>
727
                </FormGroup>
728
              </Col>
729
              <Col xs="auto">
730
                <FormGroup>
731
                  <Label className={labelClasses} for="periodType">
732
                    {t('Period Types')}
733
                  </Label>
734
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
735
                  >
736
                    {periodTypeOptions.map((periodType, index) => (
737
                      <option value={periodType.value} key={periodType.value} >
738
                        {t(periodType.label)}
739
                      </option>
740
                    ))}
741
                  </CustomInput>
742
                </FormGroup>
743
              </Col>
744
              <Col xs={6} sm={3}>
745
                <FormGroup className="form-group">
746
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
747
                  <DateRangePickerWrapper 
748
                    id='basePeriodDateRangePicker'
749
                    disabled={basePeriodDateRangePickerDisabled}
750
                    format="yyyy-MM-dd HH:mm:ss"
751
                    value={basePeriodDateRange}
752
                    onChange={onBasePeriodChange}
753
                    size="md"
754
                    style={dateRangePickerStyle}
755
                    onClean={onBasePeriodClean}
756
                    locale={dateRangePickerLocale}
757
                    placeholder={t("Select Date Range")}
758
                   />
759
                </FormGroup>
760
              </Col>
761
              <Col xs={6} sm={3}>
762
                <FormGroup className="form-group">
763
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
764
                  <br/>
765
                  <DateRangePickerWrapper
766
                    id='reportingPeriodDateRangePicker'
767
                    format="yyyy-MM-dd HH:mm:ss"
768
                    value={reportingPeriodDateRange}
769
                    onChange={onReportingPeriodChange}
770
                    size="md"
771
                    style={dateRangePickerStyle}
772
                    onClean={onReportingPeriodClean}
773
                    locale={dateRangePickerLocale}
774
                    placeholder={t("Select Date Range")}
775
                  />
776
                </FormGroup>
777
              </Col>
778
              <Col xs="auto">
779
                <FormGroup>
780
                  <br></br>
781
                  <ButtonGroup id="submit">
782
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
783
                  </ButtonGroup>
784
                </FormGroup>
785
              </Col>
786
              <Col xs="auto">
787
                <FormGroup>
788
                  <br></br>
789
                  <Spinner color="primary" hidden={spinnerHidden}  />
790
                </FormGroup>
791
              </Col>
792
              <Col xs="auto">
793
                  <br></br>
794
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
795
                  hidden={exportButtonHidden}
796
                  onClick={handleExport} >
797
                    {t('Export')}
798
                  </ButtonIcon>
799
              </Col>
800
            </Row>
801
          </Form>
802
        </CardBody>
803
      </Card>
804
      <div className="card-deck">
805
        {cardSummaryList.map(cardSummaryItem => (
806
          <CardSummary key={cardSummaryItem['name']}
807
            rate={cardSummaryItem['increment_rate']}
808
            title={t('Reporting Period Consumption ITEM CATEGORY UNIT', { 'ITEM': cardSummaryItem['name'], 'CATEGORY': cardSummaryItem['energy_category_name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
809
            color="success" 
810
            footnote={t('Per Unit Area')} 
811
            footvalue={cardSummaryItem['subtotal_per_unit_area']}
812
            footunit={"(" + cardSummaryItem['unit'] + "/M²)"} >
813
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
814
          </CardSummary>
815
        ))}
816
      </div>
817
      <Row noGutters>
818
        {sharePieList.map(sharePieItem => (
819
          <Col key={sharePieItem['energy_category_name']} className="mb-3 pr-lg-2 mb-3">
820
            <SharePie key={sharePieItem['energy_category_name']}
821
              data={sharePieItem['data']} 
822
              title={t('CATEGORY UNIT Consumption by Energy Items', { 'CATEGORY': sharePieItem['energy_category_name'], 'UNIT': '(' + sharePieItem['unit'] + ')' })} />
823
          </Col>
824
        ))}
825
      </Row>
826
827
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": shopfloorBaseAndReportingNames, "VALUE": shopfloorReportingSubtotals, "UNIT": shopfloorBaseAndReportingUnits}}
828
        baseTitle = {{"name": "Base Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": shopfloorBaseAndReportingNames, "VALUE": shopfloorBaseSubtotals, "UNIT": shopfloorBaseAndReportingUnits}}
829
        reportingTooltipTitle = {{"name": "Reporting Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": shopfloorBaseAndReportingNames, "VALUE": null, "UNIT": shopfloorBaseAndReportingUnits}}
830
        baseTooltipTitle = {{"name": "Base Period Consumption CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": shopfloorBaseAndReportingNames, "VALUE": null, "UNIT": shopfloorBaseAndReportingUnits}}
831
        reportingLabels={shopfloorReportingLabels}
832
        reportingData={shopfloorReportingData}
833
        baseLabels={shopfloorBaseLabels}
834
        baseData={shopfloorBaseData}
835
        rates={shopfloorReportingRates}
836
        options={shopfloorReportingOptions}>
837
      </MultiTrendChart>
838
839
      <MultipleLineChart reportingTitle={t('Related Parameters')}
840
        baseTitle=''
841
        labels={parameterLineChartLabels}
842
        data={parameterLineChartData}
843
        options={parameterLineChartOptions}>
844
      </MultipleLineChart>
845
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
846
      </DetailedDataTable>
847
    </Fragment>
848
  );
849
};
850
851
export default withTranslation()(withRedirect(ShopfloorEnergyItem));
852