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

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

Complexity

Total Complexity 48
Complexity/F 0

Size

Lines of Code 864
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 48
eloc 717
dl 0
loc 864
rs 8.443
c 0
b 0
f 0
mnd 48
bc 48
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

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