Passed
Push — master ( 414b30...be43ee )
by Guangyu
14:19 queued 13s
created

myems-web/src/components/MyEMS/CombinedEquipment/CombinedEquipmentIncome.js   B

Complexity

Total Complexity 51
Complexity/F 0

Size

Lines of Code 956
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 51
eloc 807
dl 0
loc 956
rs 7.713
c 0
b 0
f 0
mnd 51
bc 51
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

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