Passed
Push — master ( c8b356...ca4867 )
by Guangyu
09:12 queued 13s
created

myems-web/src/components/MyEMS/Equipment/EquipmentIncome.js   B

Complexity

Total Complexity 48
Complexity/F 0

Size

Lines of Code 892
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 48
eloc 754
dl 0
loc 892
rs 8.4059
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/Equipment/EquipmentIncome.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 EquipmentIncome = ({ 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 [equipmentList, setEquipmentList] = useState([]);
67
  const [selectedEquipment, setSelectedEquipment] = 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 [incomeShareData, setIncomeShareData] = useState([]);
101
102
  const [cardSummaryList, setCardSummaryList] = useState([]);
103
104
  const [equipmentBaseAndReportingNames, setEquipmentBaseAndReportingNames] = useState({"a0":""});
105
  const [equipmentBaseAndReportingUnits, setEquipmentBaseAndReportingUnits] = useState({"a0":"()"});
106
107
  const [equipmentBaseLabels, setEquipmentBaseLabels] = useState({"a0": []});
108
  const [equipmentBaseData, setEquipmentBaseData] = useState({"a0": []});
109
  const [equipmentBaseSubtotals, setEquipmentBaseSubtotals] = useState({"a0": (0).toFixed(2)});
110
111
  const [equipmentReportingLabels, setEquipmentReportingLabels] = useState({"a0": []});
112
  const [equipmentReportingData, setEquipmentReportingData] = useState({"a0": []});
113
  const [equipmentReportingSubtotals, setEquipmentReportingSubtotals] = useState({"a0": (0).toFixed(2)});
114
115
  const [equipmentReportingRates, setEquipmentReportingRates] = useState({"a0": []});
116
  const [equipmentReportingOptions, setEquipmentReportingOptions] = useState([]);
117
118
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
119
  const [parameterLineChartData, setParameterLineChartData] = useState({});
120
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
121
122
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
123
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
124
  const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
125
126
  useEffect(() => {
127
    let isResponseOK = false;
128
    fetch(APIBaseURL + '/spaces/tree', {
129
      method: 'GET',
130
      headers: {
131
        "Content-type": "application/json",
132
        "User-UUID": getCookieValue('user_uuid'),
133
        "Token": getCookieValue('token')
134
      },
135
      body: null,
136
137
    }).then(response => {
138
      console.log(response);
139
      if (response.ok) {
140
        isResponseOK = true;
141
      }
142
      return response.json();
143
    }).then(json => {
144
      console.log(json);
145
      if (isResponseOK) {
146
        // rename keys 
147
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
148
        setCascaderOptions(json);
149
        setSelectedSpaceName([json[0]].map(o => o.label));
150
        setSelectedSpaceID([json[0]].map(o => o.value));
151
        // get Equipments by root Space ID
152
        let isResponseOK = false;
153
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/equipments', {
154
          method: 'GET',
155
          headers: {
156
            "Content-type": "application/json",
157
            "User-UUID": getCookieValue('user_uuid'),
158
            "Token": getCookieValue('token')
159
          },
160
          body: null,
161
162
        }).then(response => {
163
          if (response.ok) {
164
            isResponseOK = true;
165
          }
166
          return response.json();
167
        }).then(json => {
168
          if (isResponseOK) {
169
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
170
            console.log(json);
171
            setEquipmentList(json[0]);
172
            if (json[0].length > 0) {
173
              setSelectedEquipment(json[0][0].value);
174
              // enable submit button
175
              setSubmitButtonDisabled(false);
176
            } else {
177
              setSelectedEquipment(undefined);
178
              // disable submit button
179
              setSubmitButtonDisabled(true);
180
            }
181
          } else {
182
            toast.error(t(json.description))
183
          }
184
        }).catch(err => {
185
          console.log(err);
186
        });
187
        // end of get Equipments by root Space ID
188
      } else {
189
        toast.error(t(json.description));
190
      }
191
    }).catch(err => {
192
      console.log(err);
193
    });
194
195
  }, []);
196
197
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
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] + '/equipments', {
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
        setEquipmentList(json[0]);
223
        if (json[0].length > 0) {
224
          setSelectedEquipment(json[0][0].value);
225
          // enable submit button
226
          setSubmitButtonDisabled(false);
227
        } else {
228
          setSelectedEquipment(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
  let onComparisonTypeChange = ({ target }) => {
241
    console.log(target.value);
242
    setComparisonType(target.value);
243
    if (target.value === 'year-over-year') {
244
      setBasePeriodDateRangePickerDisabled(true);
245
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'years').toDate(),
246
        moment(reportingPeriodDateRange[1]).subtract(1, 'years').toDate()]);
247
    } else if (target.value === 'month-on-month') {
248
      setBasePeriodDateRangePickerDisabled(true);
249
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'months').toDate(),
250
        moment(reportingPeriodDateRange[1]).subtract(1, 'months').toDate()]);
251
    } else if (target.value === 'free-comparison') {
252
      setBasePeriodDateRangePickerDisabled(false);
253
    } else if (target.value === 'none-comparison') {
254
      setBasePeriodDateRange([null, null]);
255
      setBasePeriodDateRangePickerDisabled(true);
256
    }
257
  };
258
259
  // Callback fired when value changed
260
  let onBasePeriodChange = (DateRange) => {
261
    if(DateRange == null) {
262
      setBasePeriodDateRange([null, null]);
263
    } else {
264
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
265
        // if the user did not change time value, set the default time to the end of day
266
        DateRange[1] = endOfDay(DateRange[1]);
267
      }
268
      setBasePeriodDateRange([DateRange[0], DateRange[1]]);
269
    }
270
  };
271
272
  // Callback fired when value changed
273
  let onReportingPeriodChange = (DateRange) => {
274
    if(DateRange == null) {
275
      setReportingPeriodDateRange([null, null]);
276
    } else {
277
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
278
        // if the user did not change time value, set the default time to the end of day
279
        DateRange[1] = endOfDay(DateRange[1]);
280
      }
281
      setReportingPeriodDateRange([DateRange[0], DateRange[1]]);
282
      if (comparisonType === 'year-over-year') {
283
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'years').toDate(), moment(DateRange[1]).clone().subtract(1, 'years').toDate()]);
284
      } else if (comparisonType === 'month-on-month') {
285
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'months').toDate(), moment(DateRange[1]).clone().subtract(1, 'months').toDate()]);
286
      }
287
    }
288
  };
289
290
  // Callback fired when value clean
291
  let onBasePeriodClean = event => {
292
    setBasePeriodDateRange([null, null]);
293
  };
294
295
  // Callback fired when value clean
296
  let onReportingPeriodClean = event => {
297
    setReportingPeriodDateRange([null, null]);
298
  };
299
300
  const isBasePeriodTimestampExists = (base_period_data) => {
301
    const timestamps = base_period_data['timestamps'];
302
303
    if (timestamps.length === 0) {
304
      return false;
305
    }
306
307
    for (let i = 0; i < timestamps.length; i++) {
308
      if (timestamps[i].length > 0) {
309
        return true;
310
      }
311
    }
312
    return false
313
  }
314
315
  // Handler
316
  const handleSubmit = e => {
317
    e.preventDefault();
318
    console.log('handleSubmit');
319
    console.log(selectedSpaceID);
320
    console.log(selectedEquipment);
321
    console.log(comparisonType);
322
    console.log(periodType);
323
    console.log(basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : null)
324
    console.log(basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : null)
325
    console.log(moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss'))
326
    console.log(moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss'));
327
328
    // disable submit button
329
    setSubmitButtonDisabled(true);
330
    // show spinner
331
    setSpinnerHidden(false);
332
    // hide export button
333
    setExportButtonHidden(true)
334
335
    // Reinitialize tables
336
    setDetailedDataTableData([]);
337
    
338
    let isResponseOK = false;
339
    fetch(APIBaseURL + '/reports/equipmentincome?' +
340
      'equipmentid=' + selectedEquipment +
341
      '&periodtype=' + periodType +
342
      '&baseperiodstartdatetime=' + (basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : '') +
343
      '&baseperiodenddatetime=' + (basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : '') +
344
      '&reportingperiodstartdatetime=' + moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') +
345
      '&reportingperiodenddatetime=' + moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') + 
346
      '&language=' + language, {
347
      method: 'GET',
348
      headers: {
349
        "Content-type": "application/json",
350
        "User-UUID": getCookieValue('user_uuid'),
351
        "Token": getCookieValue('token')
352
      },
353
      body: null,
354
355
    }).then(response => {
356
      if (response.ok) {
357
        isResponseOK = true;
358
      };
359
      return response.json();
360
    }).then(json => {
361
      if (isResponseOK) {
362
        console.log(json);
363
364
        let cardSummaryArray = []
365
        json['reporting_period']['names'].forEach((currentValue, index) => {
366
          let cardSummaryItem = {}
367
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
368
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
369
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals'][index];
370
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates'][index] * 100).toFixed(2) + "%";
371
          cardSummaryArray.push(cardSummaryItem);
372
        });
373
        let cardSummaryItem = {}
374
        cardSummaryItem['name'] = t('Total');
375
        cardSummaryItem['unit'] = json['reporting_period']['total_unit'];
376
        cardSummaryItem['subtotal'] = json['reporting_period']['total'];
377
        cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['total_increment_rate'] * 100).toFixed(2) + "%";
378
        cardSummaryArray.push(cardSummaryItem);
379
        setCardSummaryList(cardSummaryArray);
380
        
381
        let incomeDataArray = [];
382
        json['reporting_period']['names'].forEach((currentValue, index) => {
383
          let incomeDataItem = {}
384
          incomeDataItem['id'] = index;
385
          incomeDataItem['name'] = currentValue;
386
          incomeDataItem['value'] = json['reporting_period']['subtotals'][index];
387
          incomeDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
388
          incomeDataArray.push(incomeDataItem);
389
        });
390
        setIncomeShareData(incomeDataArray);
391
392
        let base_timestamps = {}
393
        json['base_period']['timestamps'].forEach((currentValue, index) => {
394
          base_timestamps['a' + index] = currentValue;
395
        });
396
        setEquipmentBaseLabels(base_timestamps)
397
398
        let base_values = {}
399
        json['base_period']['values'].forEach((currentValue, index) => {
400
          base_values['a' + index] = currentValue;
401
        });
402
        setEquipmentBaseData(base_values)
403
404
        /*
405
        * Tip:
406
        *     base_names === reporting_names
407
        *     base_units === reporting_units
408
        * */
409
410
        let base_and_reporting_names = {}
411
        json['reporting_period']['names'].forEach((currentValue, index) => {
412
          base_and_reporting_names['a' + index] = currentValue;
413
        });
414
        setEquipmentBaseAndReportingNames(base_and_reporting_names)
415
416
        let base_and_reporting_units = {}
417
        json['reporting_period']['units'].forEach((currentValue, index) => {
418
          base_and_reporting_units['a' + index] = "("+currentValue+")";
419
        });
420
        setEquipmentBaseAndReportingUnits(base_and_reporting_units)
421
422
        let base_subtotals = {}
423
        json['base_period']['subtotals'].forEach((currentValue, index) => {
424
          base_subtotals['a' + index] = currentValue.toFixed(2);
425
        });
426
        setEquipmentBaseSubtotals(base_subtotals)
427
428
        let reporting_timestamps = {}
429
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
430
          reporting_timestamps['a' + index] = currentValue;
431
        });
432
        setEquipmentReportingLabels(reporting_timestamps);
433
434
        let reporting_values = {}
435
        json['reporting_period']['values'].forEach((currentValue, index) => {
436
          reporting_values['a' + index] = currentValue;
437
        });
438
        setEquipmentReportingData(reporting_values);
439
440
        let reporting_subtotals = {}
441
        json['reporting_period']['subtotals'].forEach((currentValue, index) => {
442
          reporting_subtotals['a' + index] = currentValue.toFixed(2);
443
        });
444
        setEquipmentReportingSubtotals(reporting_subtotals);
445
446
        let rates = {}
447
        json['reporting_period']['rates'].forEach((currentValue, index) => {
448
          let currentRate = Array();
449
          currentValue.forEach((rate) => {
450
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
451
          });
452
          rates['a' + index] = currentRate;
453
        });
454
        setEquipmentReportingRates(rates)
455
456
        let options = Array();
457
        json['reporting_period']['names'].forEach((currentValue, index) => {
458
          let unit = json['reporting_period']['units'][index];
459
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
460
        });
461
        setEquipmentReportingOptions(options);
462
463
        let timestamps = {}
464
        json['parameters']['timestamps'].forEach((currentValue, index) => {
465
          timestamps['a' + index] = currentValue;
466
        });
467
        setParameterLineChartLabels(timestamps);
468
469
        let values = {}
470
        json['parameters']['values'].forEach((currentValue, index) => {
471
          values['a' + index] = currentValue;
472
        });
473
        setParameterLineChartData(values);
474
      
475
        let names = Array();
476
        json['parameters']['names'].forEach((currentValue, index) => {
477
          
478
          names.push({ 'value': 'a' + index, 'label': currentValue });
479
        });
480
        setParameterLineChartOptions(names);
481
482
        if(!isBasePeriodTimestampExists(json['base_period'])) {
483
          let detailed_value_list = [];
484
          if (json['reporting_period']['timestamps'].length > 0) {
485
            json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
486
              let detailed_value = {};
487
              detailed_value['id'] = timestampIndex;
488
              detailed_value['startdatetime'] = currentTimestamp;
489
              let total_current_timstamp = 0.0;
490
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
491
                detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values'][energyCategoryIndex][timestampIndex];
492
                total_current_timstamp += json['reporting_period']['values'][energyCategoryIndex][timestampIndex];
493
              });
494
              detailed_value['total'] = total_current_timstamp;
495
              detailed_value_list.push(detailed_value);
496
            });
497
          };
498
499
          let detailed_value = {};
500
          detailed_value['id'] = detailed_value_list.length;
501
          detailed_value['startdatetime'] = t('Subtotal');
502
          let total_of_subtotals = 0.0;
503
          json['reporting_period']['subtotals'].forEach((currentValue, index) => {
504
            detailed_value['a' + index] = currentValue;
505
            total_of_subtotals += currentValue
506
          });
507
          detailed_value['total'] = total_of_subtotals;
508
          detailed_value_list.push(detailed_value);
509
          setTimeout(() => {
510
            setDetailedDataTableData(detailed_value_list);
511
          }, 0)
512
513
          let detailed_column_list = [];
514
          detailed_column_list.push({
515
            dataField: 'startdatetime',
516
            text: t('Datetime'),
517
            sort: true
518
          });
519
          json['reporting_period']['names'].forEach((currentValue, index) => {
520
            let unit = json['reporting_period']['units'][index];
521
            detailed_column_list.push({
522
              dataField: 'a' + index,
523
              text: currentValue + ' (' + unit + ')',
524
              sort: true,
525
              formatter: function (decimalValue) {
526
                if (typeof decimalValue === 'number') {
527
                  return decimalValue.toFixed(2);
528
                } else {
529
                  return null;
530
                }
531
              }
532
            });
533
          });
534
          detailed_column_list.push({
535
            dataField: 'total',
536
            text: t('Total') + ' (' + json['reporting_period']['total_unit'] + ')',
537
            sort: true,
538
            formatter: function (decimalValue) {
539
              if (typeof decimalValue === 'number') {
540
                return decimalValue.toFixed(2);
541
              } else {
542
                return null;
543
              }
544
            }
545
          });
546
          setDetailedDataTableColumns(detailed_column_list);
547
        }else {
548
          /*
549
          * Tip:
550
          *     json['base_period']['names'] ===  json['reporting_period']['names']
551
          *     json['base_period']['units'] ===  json['reporting_period']['units']
552
          * */
553
          let detailed_column_list = [];
554
          detailed_column_list.push({
555
            dataField: 'basePeriodDatetime',
556
            text: t('Base Period') + ' - ' + t('Datetime'),
557
            sort: true
558
          })
559
560
          json['base_period']['names'].forEach((currentValue, index) => {
561
            let unit = json['base_period']['units'][index];
562
            detailed_column_list.push({
563
              dataField: 'a' + index,
564
              text: t('Base Period') + ' - ' + currentValue + ' (' + unit + ')',
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: 'basePeriodTotal',
578
            text: t('Base Period') + ' - ' + t('Total') + ' (' + json['reporting_period']['total_unit'] + ')',
579
            sort: true,
580
            formatter: function (decimalValue) {
581
              if (typeof decimalValue === 'number') {
582
                return decimalValue.toFixed(2);
583
              } else {
584
                return null;
585
              }
586
            }
587
          })
588
589
          detailed_column_list.push({
590
            dataField: 'reportingPeriodDatetime',
591
            text: t('Reporting Period') + ' - ' + t('Datetime'),
592
            sort: true
593
          })
594
595
          json['reporting_period']['names'].forEach((currentValue, index) => {
596
            let unit = json['reporting_period']['units'][index];
597
            detailed_column_list.push({
598
              dataField: 'b' + index,
599
              text: t('Reporting Period') + ' - ' + currentValue + ' (' + unit + ')',
600
              sort: true,
601
              formatter: function (decimalValue) {
602
                if (typeof decimalValue === 'number') {
603
                  return decimalValue.toFixed(2);
604
                } else {
605
                  return null;
606
                }
607
              }
608
            })
609
          });
610
611
          detailed_column_list.push({
612
            dataField: 'reportingPeriodTotal',
613
            text: t('Reporting Period') + ' - ' + t('Total') + ' (' + json['reporting_period']['total_unit'] + ')',
614
            sort: true,
615
            formatter: function (decimalValue) {
616
              if (typeof decimalValue === 'number') {
617
                return decimalValue.toFixed(2);
618
              } else {
619
                return null;
620
              }
621
            }
622
          })
623
624
          setDetailedDataTableColumns(detailed_column_list);
625
626
          let detailed_value_list = [];
627
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
628
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length ?
629
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
630
            for (let index = 0; index < max_timestamps_length; index++) {
631
              let detailed_value = {};
632
              detailed_value['id'] = index;
633
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length ? json['base_period']['timestamps'][0][index] : null;
634
              detailed_value['basePeriodTotal'] = 0.0;
635
              if (detailed_value['basePeriodDatetime'] == null) {
636
                detailed_value['basePeriodTotal'] = null;
637
              }
638
              json['base_period']['values'].forEach((currentValue, energyCategoryIndex) => {
639
                detailed_value['a' + energyCategoryIndex] = index < json['base_period']['values'][energyCategoryIndex].length ? json['base_period']['values'][energyCategoryIndex][index] : null;
640
                if (detailed_value['a' + energyCategoryIndex] != null) {
641
                  detailed_value['basePeriodTotal'] += detailed_value['a' + energyCategoryIndex];
642
                }
643
              });
644
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length ? json['reporting_period']['timestamps'][0][index] : null;
645
              detailed_value['reportingPeriodTotal'] = 0.0;
646
              if (detailed_value['reportingPeriodDatetime'] == null) {
647
                detailed_value['reportingPeriodTotal'] = null;
648
              }
649
              json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
650
                detailed_value['b' + energyCategoryIndex] = index < json['reporting_period']['values'][energyCategoryIndex].length ? json['reporting_period']['values'][energyCategoryIndex][index] : null;
651
                if (detailed_value['b' + energyCategoryIndex] != null) {
652
                  detailed_value['reportingPeriodTotal'] += detailed_value['b' + energyCategoryIndex];
653
                }
654
              });
655
              detailed_value_list.push(detailed_value);
656
            }
657
658
            let detailed_value = {};
659
            detailed_value['id'] = detailed_value_list.length;
660
            detailed_value['basePeriodDatetime'] = t('Subtotal');
661
            let total_of_subtotals_from_base_period = 0.0
662
            json['base_period']['subtotals'].forEach((currentValue, index) => {
663
              detailed_value['a' + index] = currentValue;
664
              total_of_subtotals_from_base_period += detailed_value['a' + index];
665
            });
666
            detailed_value['basePeriodTotal'] = total_of_subtotals_from_base_period;
667
668
            let total_of_subtotals_from_reporting_period = 0.0
669
            detailed_value['reportingPeriodDatetime'] = t('Subtotal');
670
            json['reporting_period']['subtotals'].forEach((currentValue, index) => {
671
              detailed_value['b' + index] = currentValue;
672
              total_of_subtotals_from_reporting_period += detailed_value['b' + index];
673
            });
674
            detailed_value['reportingPeriodTotal'] = total_of_subtotals_from_reporting_period;
675
            detailed_value_list.push(detailed_value);
676
            setTimeout(() => {
677
              setDetailedDataTableData(detailed_value_list);
678
            }, 0)
679
          }
680
        }
681
        
682
        setExcelBytesBase64(json['excel_bytes_base64']);
683
684
        // enable submit button
685
        setSubmitButtonDisabled(false);
686
        // hide spinner
687
        setSpinnerHidden(true);
688
        // show export button
689
        setExportButtonHidden(false);
690
          
691
      } else {
692
        toast.error(t(json.description))
693
      }
694
    }).catch(err => {
695
      console.log(err);
696
    });
697
  };
698
699
  const handleExport = e => {
700
    e.preventDefault();
701
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
702
    const fileName = 'equipmentincome.xlsx'
703
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
704
    fetch(fileUrl)
705
        .then(response => response.blob())
706
        .then(blob => {
707
            var link = window.document.createElement("a");
708
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
709
            link.download = fileName;
710
            document.body.appendChild(link);
711
            link.click();
712
            document.body.removeChild(link);
713
        });
714
  };
715
  
716
717
  return (
718
    <Fragment>
719
      <div>
720
        <Breadcrumb>
721
          <BreadcrumbItem>{t('Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Income')}</BreadcrumbItem>
722
        </Breadcrumb>
723
      </div>
724
      <Card className="bg-light mb-3">
725
        <CardBody className="p-3">
726
          <Form onSubmit={handleSubmit}>
727
            <Row form>
728
              <Col xs={6} sm={3}>
729
                <FormGroup className="form-group">
730
                  <Label className={labelClasses} for="space">
731
                    {t('Space')}
732
                  </Label>
733
                  <br />
734
                  <Cascader options={cascaderOptions}
735
                    onChange={onSpaceCascaderChange}
736
                    changeOnSelect
737
                    expandTrigger="hover">
738
                    <Input value={selectedSpaceName || ''} readOnly />
739
                  </Cascader>
740
                </FormGroup>
741
              </Col>
742
              <Col xs="auto">
743
                <FormGroup>
744
                  <Label className={labelClasses} for="equipmentSelect">
745
                    {t('Equipment')}
746
                  </Label>
747
                  <CustomInput type="select" id="equipmentSelect" name="equipmentSelect" onChange={({ target }) => setSelectedEquipment(target.value)}
748
                  >
749
                    {equipmentList.map((equipment, index) => (
750
                      <option value={equipment.value} key={equipment.value}>
751
                        {equipment.label}
752
                      </option>
753
                    ))}
754
                  </CustomInput>
755
                </FormGroup>
756
              </Col>
757
              <Col xs="auto">
758
                <FormGroup>
759
                  <Label className={labelClasses} for="comparisonType">
760
                    {t('Comparison Types')}
761
                  </Label>
762
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
763
                    defaultValue="month-on-month"
764
                    onChange={onComparisonTypeChange}
765
                  >
766
                    {comparisonTypeOptions.map((comparisonType, index) => (
767
                      <option value={comparisonType.value} key={comparisonType.value} >
768
                        {t(comparisonType.label)}
769
                      </option>
770
                    ))}
771
                  </CustomInput>
772
                </FormGroup>
773
              </Col>
774
              <Col xs="auto">
775
                <FormGroup>
776
                  <Label className={labelClasses} for="periodType">
777
                    {t('Period Types')}
778
                  </Label>
779
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
780
                  >
781
                    {periodTypeOptions.map((periodType, index) => (
782
                      <option value={periodType.value} key={periodType.value} >
783
                        {t(periodType.label)}
784
                      </option>
785
                    ))}
786
                  </CustomInput>
787
                </FormGroup>
788
              </Col>
789
              <Col xs={6} sm={3}>
790
                <FormGroup className="form-group">
791
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
792
                  <DateRangePickerWrapper 
793
                    id='basePeriodDateRangePicker'
794
                    disabled={basePeriodDateRangePickerDisabled}
795
                    format="yyyy-MM-dd HH:mm:ss"
796
                    value={basePeriodDateRange}
797
                    onChange={onBasePeriodChange}
798
                    size="md"
799
                    style={dateRangePickerStyle}
800
                    onClean={onBasePeriodClean}
801
                    locale={dateRangePickerLocale}
802
                    placeholder={t("Select Date Range")}
803
                   />
804
                </FormGroup>
805
              </Col>
806
              <Col xs={6} sm={3}>
807
                <FormGroup className="form-group">
808
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
809
                  <br/>
810
                  <DateRangePickerWrapper
811
                    id='reportingPeriodDateRangePicker'
812
                    format="yyyy-MM-dd HH:mm:ss"
813
                    value={reportingPeriodDateRange}
814
                    onChange={onReportingPeriodChange}
815
                    size="md"
816
                    style={dateRangePickerStyle}
817
                    onClean={onReportingPeriodClean}
818
                    locale={dateRangePickerLocale}
819
                    placeholder={t("Select Date Range")}
820
                  />
821
                </FormGroup>
822
              </Col>
823
              <Col xs="auto">
824
                <FormGroup>
825
                  <br></br>
826
                  <ButtonGroup id="submit">
827
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
828
                  </ButtonGroup>
829
                </FormGroup>
830
              </Col>
831
              <Col xs="auto">
832
                <FormGroup>
833
                  <br></br>
834
                  <Spinner color="primary" hidden={spinnerHidden}  />
835
                </FormGroup>
836
              </Col>
837
              <Col xs="auto">
838
                  <br></br>
839
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
840
                  hidden={exportButtonHidden}
841
                  onClick={handleExport} >
842
                    {t('Export')}
843
                  </ButtonIcon>
844
              </Col>
845
            </Row>
846
          </Form>
847
        </CardBody>
848
      </Card>
849
      <div className="card-deck">
850
        {cardSummaryList.map(cardSummaryItem => (
851
          <CardSummary key={cardSummaryItem['name']}
852
            rate={cardSummaryItem['increment_rate']}
853
            title={t('Reporting Period Income CATEGORY UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
854
            color="success" >
855
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
856
          </CardSummary>
857
        ))}
858
      </div>
859
      <Row noGutters>
860
        <Col className="mb-3 pr-lg-2 mb-3">
861
          <SharePie data={incomeShareData} title={t('Incomes by Energy Category')} />
862
        </Col>
863
      </Row>
864
865
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period Income CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": equipmentBaseAndReportingNames, "VALUE": equipmentReportingSubtotals, "UNIT": equipmentBaseAndReportingUnits}}
866
        baseTitle = {{"name": "Base Period Income CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": equipmentBaseAndReportingNames, "VALUE": equipmentBaseSubtotals, "UNIT": equipmentBaseAndReportingUnits}}
867
        reportingTooltipTitle = {{"name": "Reporting Period Income CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": equipmentBaseAndReportingNames, "VALUE": null, "UNIT": equipmentBaseAndReportingUnits}}
868
        baseTooltipTitle = {{"name": "Base Period Income CATEGORY VALUE UNIT", "substitute": ["CATEGORY", "VALUE", "UNIT"], "CATEGORY": equipmentBaseAndReportingNames, "VALUE": null, "UNIT": equipmentBaseAndReportingUnits}}
869
        reportingLabels={equipmentReportingLabels}
870
        reportingData={equipmentReportingData}
871
        baseLabels={equipmentBaseLabels}
872
        baseData={equipmentBaseData}
873
        rates={equipmentReportingRates}
874
        options={equipmentReportingOptions}>
875
      </MultiTrendChart>
876
877
      <MultipleLineChart reportingTitle={t('Related Parameters')}
878
        baseTitle=''
879
        labels={parameterLineChartLabels}
880
        data={parameterLineChartData}
881
        options={parameterLineChartOptions}>
882
      </MultipleLineChart>
883
      <br />
884
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
885
      </DetailedDataTable>
886
887
    </Fragment>
888
  );
889
};
890
891
export default withTranslation()(withRedirect(EquipmentIncome));
892