myems-web/src/components/MyEMS/Microgrid/ItemDashboard.js   F
last analyzed

Complexity

Total Complexity 73
Complexity/F 0

Size

Lines of Code 1070
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 73
eloc 891
mnd 73
bc 73
fnc 0
dl 0
loc 1070
rs 2.269
bpm 0
cpm 0
noi 0
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/Microgrid/ItemDashboard.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, useCallback } from 'react';
2
import CountUp from 'react-countup';
3
import { Col, Row, Spinner, Nav, NavItem, NavLink, TabContent, TabPane, Form, FormGroup, Input, CustomInput } from 'reactstrap';
4
import Cascader from 'rc-cascader';
5
import MicrogridTableCard from './MicrogridTableCard';
6
import CardSummary from '../common/CardSummary';
7
import { toast } from 'react-toastify';
8
import { getCookieValue, createCookie, checkEmpty } from '../../../helpers/utils';
9
import withRedirect from '../../../hoc/withRedirect';
10
import { withTranslation } from 'react-i18next';
11
import moment from 'moment';
12
import { APIBaseURL, settings } from '../../../config';
13
import { getItemFromStore } from '../../../helpers/utils';
14
import CustomizeMapBox from '../common/CustomizeMapBox';
15
import classNames from 'classnames';
16
import AppContext from '../../../context/Context';
17
import StackBarChart from './StackBarChart';
18
19
const ItemDashboard = ({ setRedirect, setRedirectUrl, t }) => {
20
  let current_moment = moment();
21
  const [isDashboardFetched, setIsDashboardFetched] = useState(false);
22
  const [isMicrogridsEnergyFetched, setIsMicrogridsEnergyFetched] = useState(false);
23
  const [isMicrogridsBillingFetched, setIsMicrogridsBillingFetched] = useState(false);
24
  const [isMicrogridsCarbonFetched, setIsMicrogridsCarbonFetched] = useState(false);
25
  const [isMicrogridsPhotovoltaicFetched, setIsMicrogridsPhotovoltaicFetched] = useState(false);
26
  const [isMicrogridsEvchargerFetched, setIsMicrogridsEvchargerFetched] = useState(false);
27
  const [isMicrogridsLoadFetched, setIsMicrogridsLoadFetched] = useState(false);
28
  const [isMicrogridsGridBuyFetched, setIsMicrogridsGridBuyFetched] = useState(false);
29
  const [isMicrogridsGridSellFetched, setIsMicrogridsGridSellFetched] = useState(false);
30
  const [periodType, setPeriodType] = useState('monthly');
31
  const [basePeriodBeginsDatetime, setBasePeriodBeginsDatetime] = useState(
32
    current_moment
33
      .clone()
34
      .subtract(1, 'years')
35
      .startOf('year')
36
  );
37
  const [basePeriodEndsDatetime, setBasePeriodEndsDatetime] = useState(current_moment.clone().subtract(1, 'years'));
38
  const [reportingPeriodBeginsDatetime, setReportingPeriodBeginsDatetime] = useState(
39
    current_moment.clone().startOf('year')
40
  );
41
  const [reportingPeriodEndsDatetime, setReportingPeriodEndsDatetime] = useState(current_moment);
42
  const [spinnerHidden, setSpinnerHidden] = useState(false);
43
  const [activeTabLeft, setActiveTabLeft] = useState('1');
44
  const toggleTabLeft = tab => {
45
    if (activeTabLeft !== tab) {
46
      setActiveTabLeft(tab);
47
      // Load data for the selected tab if not already loaded
48
      const user_uuid = getCookieValue('user_uuid');
49
      if (tab === '2' && !isMicrogridsBillingFetched) {
50
        loadBillingData(user_uuid);
51
      } else if (tab === '3' && !isMicrogridsCarbonFetched) {
52
        loadCarbonData(user_uuid);
53
      } else if (tab === '4' && !isMicrogridsPhotovoltaicFetched) {
54
        loadPhotovoltaicData(user_uuid);
55
      } else if (tab === '5' && !isMicrogridsEvchargerFetched) {
56
        loadEvchargerData(user_uuid);
57
      } else if (tab === '6' && !isMicrogridsLoadFetched) {
58
        loadLoadData(user_uuid);
59
      } else if (tab === '7' && !isMicrogridsGridBuyFetched) {
60
        loadGridBuyData(user_uuid);
61
      } else if (tab === '8' && !isMicrogridsGridSellFetched) {
62
        loadGridSellData(user_uuid);
63
      }
64
    }
65
  };
66
  const [activeTabRight, setActiveTabRight] = useState('1');
67
  const toggleTabRight = tab => {
68
    if (activeTabRight !== tab) setActiveTabRight(tab);
69
  };
70
  const { currency } = useContext(AppContext);
71
72
  // State for space selection
73
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
74
  const [filteredMicrogridList, setFilteredMicrogridList] = useState([]);
75
  const [selectedMicrogrid, setSelectedMicrogrid] = useState(undefined);
76
  const [cascaderOptions, setCascaderOptions] = useState([]);
77
  const [spaceCascaderHidden, setSpaceCascaderHidden] = useState(false);
78
79
  //Results
80
81
  const [microgridList, setMicrogridList] = useState([]);
82
  const [totalRatedCapacity, setTotalRatedCapacity] = useState({});
83
  const [totalRatedPower, setTotalRatedPower] = useState({});
84
  const [totalCharge, setTotalCharge] = useState({});
85
  const [totalDischarge, setTotalDischarge] = useState({});
86
  const [totalRevenue, setTotalRevenue] = useState({});
87
  const [totalPhotovoltaic, setTotalPhotovoltaic] = useState(0);
88
  const [totalEvcharger, setTotalEvcharger] = useState(0);
89
  const [totalLoad, setTotalLoad] = useState(0);
90
  const [totalGridBuy, setTotalGridBuy] = useState(0);
91
  const [totalGridSell, setTotalGridSell] = useState(0);
92
93
  const [chargeEnergyData, setChargeEnergyData] = useState({});
94
  const [dischargeEnergyData, setDischargeEnergyData] = useState({});
95
  const [chargeBillingData, setChargeBillingData] = useState({});
96
  const [dischargeBillingData, setDischargeBillingData] = useState({});
97
  const [chargeCarbonData, setChargeCarbonData] = useState({});
98
  const [dischargeCarbonData, setDischargeCarbonData] = useState({});
99
  const [photovoltaicEnergyData, setPhotovoltaicEnergyData] = useState({});
100
  const [evchargerEnergyData, setEvchargerEnergyData] = useState({});
101
  const [loadEnergyData, setLoadEnergyData] = useState({});
102
  const [gridBuyEnergyData, setGridBuyEnergyData] = useState({});
103
  const [gridSellEnergyData, setGridSellEnergyData] = useState({});
104
  const [energyLabels, setEnergyLabels] = useState([]);
105
  const [billingLabels, setBillingLabels] = useState([]);
106
  const [carbonLabels, setCarbonLabels] = useState([]);
107
  const [photovoltaicLabels, setPhotovoltaicLabels] = useState([]);
108
  const [evchargerLabels, setEvchargerLabels] = useState([]);
109
  const [loadLabels, setLoadLabels] = useState([]);
110
  const [gridBuyLabels, setGridBuyLabels] = useState([]);
111
  const [gridSellLabels, setGridSellLabels] = useState([]);
112
  const [periodTypes, setPeriodTypes] = useState([
113
    { value: 'a0', label: t('7 Days') },
114
    { value: 'a1', label: t('This Month') },
115
    { value: 'a2', label: t('This Year') }
116
  ]);
117
  const [language, setLanguage] = useState(getItemFromStore('myems_web_ui_language', settings.language));
118
  const [geojson, setGeojson] = useState({});
119
  const [rootLatitude, setRootLatitude] = useState('');
120
  const [rootLongitude, setRootLongitude] = useState('');
121
122
  // Load space tree and microgrids
123
  useEffect(() => {
124
    let is_logged_in = getCookieValue('is_logged_in');
125
    let user_name = getCookieValue('user_name');
126
    let user_display_name = getCookieValue('user_display_name');
127
    let user_uuid = getCookieValue('user_uuid');
128
    let token = getCookieValue('token');
129
    if (checkEmpty(is_logged_in) || checkEmpty(token) || checkEmpty(user_uuid) || !is_logged_in) {
130
      setRedirectUrl(`/authentication/basic/login`);
131
      setRedirect(true);
132
    } else {
133
      //update expires time of cookies
134
      createCookie('is_logged_in', true, settings.cookieExpireTime);
135
      createCookie('user_name', user_name, settings.cookieExpireTime);
136
      createCookie('user_display_name', user_display_name, settings.cookieExpireTime);
137
      createCookie('user_uuid', user_uuid, settings.cookieExpireTime);
138
      createCookie('token', token, settings.cookieExpireTime);
139
140
      setSpaceCascaderHidden(false);
141
      let isResponseOK = false;
142
      fetch(APIBaseURL + '/spaces/tree', {
143
        method: 'GET',
144
        headers: {
145
          'Content-type': 'application/json',
146
          'User-UUID': getCookieValue('user_uuid'),
147
          Token: getCookieValue('token')
148
        },
149
        body: null
150
      })
151
        .then(response => {
152
          if (response.ok) {
153
            isResponseOK = true;
154
          }
155
          return response.json();
156
        })
157
        .then(json => {
158
          if (isResponseOK) {
159
            console.log('Spaces tree response:', json);
160
            // rename keys to match Cascader component requirements
161
            let convertedJson = JSON.parse(
162
              JSON.stringify([json])
163
                .split('"id":')
164
                .join('"value":')
165
                .split('"name":')
166
                .join('"label":')
167
            );
168
            console.log('Converted spaces tree:', convertedJson);
169
            if (convertedJson && Array.isArray(convertedJson) && convertedJson.length > 0 && convertedJson[0]) {
170
              json = convertedJson;
171
              setCascaderOptions(json);
172
              setSelectedSpaceName([json[0]].map(o => o.label));
173
              let selectedSpaceID = [json[0]].map(o => o.value);
174
              // get Microgrids by root Space ID
175
              let isResponseOKMicrogrid = false;
176
            fetch(APIBaseURL + '/spaces/' + selectedSpaceID + '/microgrids', {
177
              method: 'GET',
178
              headers: {
179
                'Content-type': 'application/json',
180
                'User-UUID': getCookieValue('user_uuid'),
181
                Token: getCookieValue('token')
182
              },
183
              body: null
184
            })
185
              .then(response => {
186
                if (response.ok) {
187
                  isResponseOKMicrogrid = true;
188
                }
189
                return response.json();
190
              })
191
              .then(json => {
192
                if (isResponseOKMicrogrid) {
193
                  json = JSON.parse(
194
                    JSON.stringify([json])
195
                      .split('"id":')
196
                      .join('"value":')
197
                      .split('"name":')
198
                      .join('"label":')
199
                  );
200
                  if (json && Array.isArray(json) && json.length > 0 && json[0] && Array.isArray(json[0])) {
201
                    setMicrogridList(json[0]);
202
                    setFilteredMicrogridList(json[0]);
203
                    if (json[0].length > 0 && json[0][0]) {
204
                      // select the first microgrid
205
                      let microgridID = json[0][0].value;
206
                      setSelectedMicrogrid(microgridID);
207
                      // Reset fetched states to reload data
208
                      setIsMicrogridsEnergyFetched(false);
209
                      setIsMicrogridsBillingFetched(false);
210
                      setIsMicrogridsCarbonFetched(false);
211
                      // automatically load data for the first microgrid
212
                      loadMicrogridData(microgridID);
213
                    } else {
214
                      setSelectedMicrogrid(undefined);
215
                    }
216
                  } else {
217
                    setMicrogridList([]);
218
                    setFilteredMicrogridList([]);
219
                    setSelectedMicrogrid(undefined);
220
                  }
221
                } else {
222
                  if (json && json.description) {
223
                    toast.error(t(json.description));
224
                  } else {
225
                    toast.error(t('Failed to load microgrids'));
226
                  }
227
                }
228
              })
229
              .catch(err => {
230
                console.log(err);
231
                toast.error(t('Failed to load microgrids'));
232
              });
233
            } else {
234
              console.log('No valid space data after conversion');
235
              if (json && json.description) {
236
                toast.error(t(json.description));
237
              } else {
238
                toast.error(t('No spaces found'));
239
              }
240
            }
241
          } else {
242
            console.log('Response not OK or invalid format:', json);
243
            if (json && json.description) {
244
              toast.error(t(json.description));
245
            } else {
246
              toast.error(t('No spaces found'));
247
            }
248
          }
249
        })
250
        .catch(err => {
251
          console.log(err);
252
          toast.error(t('Failed to load spaces'));
253
        });
254
    }
255
  }, []);
256
257
  const loadMicrogridData = (microgridID) => {
258
    let user_uuid = getCookieValue('user_uuid');
259
    let isResponseOK = false;
260
    setSpinnerHidden(false);
261
262
    // Load dashboard data for selected microgrid
263
    fetch(
264
      APIBaseURL +
265
        '/reports/microgriddashboard?' +
266
        'useruuid=' +
267
        user_uuid +
268
        '&microgridid=' +
269
        microgridID +
270
        '&periodtype=' +
271
        periodType +
272
        '&baseperiodstartdatetime=' +
273
        (basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
274
        '&baseperiodenddatetime=' +
275
        (basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
276
        '&reportingperiodstartdatetime=' +
277
        reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') +
278
        '&reportingperiodenddatetime=' +
279
        reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'),
280
      {
281
        method: 'GET',
282
        headers: {
283
          'Content-type': 'application/json',
284
          'User-UUID': getCookieValue('user_uuid'),
285
          Token: getCookieValue('token')
286
        },
287
        body: null
288
      }
289
    )
290
      .then(response => {
291
        if (response.ok) {
292
          isResponseOK = true;
293
        }
294
        return response.json();
295
      })
296
      .then(json => {
297
        if (isResponseOK) {
298
          console.log(json);
299
          // hide spinner
300
          setSpinnerHidden(true);
301
302
          let microgridList = [];
303
          let totalRatedCapacity = 0;
304
          let totalRatedPower = 0;
305
306
          if (json['microgrids'] && json['microgrids'].length > 0) {
307
            setRootLongitude(json['microgrids'][0]['longitude']);
308
            setRootLatitude(json['microgrids'][0]['latitude']);
309
            let geojson = {};
310
            let geojsonData = [];
311
            json['microgrids'].forEach((currentValue, index) => {
312
              let microgridItem = json['microgrids'][index];
313
              totalRatedCapacity += microgridItem['rated_capacity'];
314
              totalRatedPower += microgridItem['rated_power'];
315
              if (microgridItem['latitude'] && microgridItem['longitude']) {
316
                geojsonData.push({
317
                  type: 'Feature',
318
                  geometry: {
319
                    type: 'Point',
320
                    coordinates: [microgridItem['longitude'], microgridItem['latitude']]
321
                  },
322
                  properties: {
323
                    title: microgridItem['name'],
324
                    description: microgridItem['description'],
325
                    uuid: microgridItem['uuid'],
326
                    url: '/microgrid/details'
327
                  }
328
                });
329
              }
330
              microgridItem['nameuuid'] = (microgridItem['name'] || '') + (microgridItem['uuid'] || '');
331
              microgridList.push(microgridItem);
332
            });
333
            setMicrogridList(microgridList);
334
            setTotalRatedCapacity(totalRatedCapacity);
335
            setTotalRatedPower(totalRatedPower);
336
            geojson['type'] = 'FeatureCollection';
337
            geojson['features'] = geojsonData;
338
            setGeojson(geojson);
339
          }
340
341
          setTotalCharge(json['total_charge_energy'] || 0);
342
343
          setTotalDischarge(json['total_discharge_energy'] || 0);
344
345
          setTotalRevenue(json['total_discharge_billing'] || 0);
346
347
          setTotalPhotovoltaic(json['total_photovoltaic_energy'] || 0);
348
349
          setTotalEvcharger(json['total_evcharger_energy'] || 0);
350
351
          setTotalLoad(json['total_load_energy'] || 0);
352
353
          setTotalGridBuy(json['total_grid_buy_energy'] || 0);
354
355
          setTotalGridSell(json['total_grid_sell_energy'] || 0);
356
        }
357
      });
358
  };
359
360
  const onSpaceCascaderChange = (value, selectedOptions) => {
361
    if (!selectedOptions || selectedOptions.length === 0) return;
362
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
363
    if (!value || value.length === 0) return;
364
    let selectedSpaceID = value[value.length - 1];
365
    let isResponseOK = false;
366
    fetch(APIBaseURL + '/spaces/' + selectedSpaceID + '/microgrids', {
367
      method: 'GET',
368
      headers: {
369
        'Content-type': 'application/json',
370
        'User-UUID': getCookieValue('user_uuid'),
371
        Token: getCookieValue('token')
372
      },
373
      body: null
374
    })
375
      .then(response => {
376
        if (response.ok) {
377
          isResponseOK = true;
378
        }
379
        return response.json();
380
      })
381
      .then(json => {
382
        if (isResponseOK) {
383
          json = JSON.parse(
384
            JSON.stringify([json])
385
              .split('"id":')
386
              .join('"value":')
387
              .split('"name":')
388
              .join('"label":')
389
          );
390
          if (json && Array.isArray(json) && json.length > 0 && json[0] && Array.isArray(json[0])) {
391
            setMicrogridList(json[0]);
392
            setFilteredMicrogridList(json[0]);
393
            if (json[0].length > 0 && json[0][0]) {
394
              // select the first microgrid
395
              let microgridID = json[0][0].value;
396
              setSelectedMicrogrid(microgridID);
397
              // Reset fetched states to reload data
398
              setIsMicrogridsEnergyFetched(false);
399
              setIsMicrogridsBillingFetched(false);
400
              setIsMicrogridsCarbonFetched(false);
401
              // automatically load data for the first microgrid
402
              loadMicrogridData(microgridID);
403
            } else {
404
              setSelectedMicrogrid(undefined);
405
            }
406
          } else {
407
            setMicrogridList([]);
408
            setFilteredMicrogridList([]);
409
            setSelectedMicrogrid(undefined);
410
          }
411
        } else {
412
          if (json && json.description) {
413
            toast.error(t(json.description));
414
          } else {
415
            toast.error(t('Failed to load microgrids'));
416
          }
417
        }
418
      })
419
      .catch(err => {
420
        console.log(err);
421
        toast.error(t('Failed to load microgrids'));
422
      });
423
  };
424
425
  const onMicrogridChange = event => {
426
    let microgridID = event.target.value;
427
    setSelectedMicrogrid(microgridID);
428
    // Reset fetched states to reload data
429
    setIsMicrogridsEnergyFetched(false);
430
    setIsMicrogridsBillingFetched(false);
431
    setIsMicrogridsCarbonFetched(false);
432
    if (microgridID) {
433
      loadMicrogridData(microgridID);
434
    }
435
  };
436
437
  // Load functions for each tab (called on demand when tab is activated)
438
  const loadEnergyDataFunc = useCallback((user_uuid, microgridID) => {
439
    if (isMicrogridsEnergyFetched) return;
440
    setIsMicrogridsEnergyFetched(true);
441
    let isResponseOK = false;
442
    fetch(APIBaseURL + '/reports/microgridsenergy?useruuid=' + user_uuid + '&microgridid=' + microgridID, {
443
      method: 'GET',
444
      headers: {
445
        'Content-type': 'application/json',
446
        'User-UUID': getCookieValue('user_uuid'),
447
        Token: getCookieValue('token')
448
      },
449
      body: null
450
    })
451
      .then(response => {
452
        if (response.ok) {
453
          isResponseOK = true;
454
        }
455
        return response.json();
456
      })
457
      .then(json => {
458
        if (isResponseOK) {
459
          console.log(json);
460
          setChargeEnergyData({
461
            unit: 'kWh',
462
            station_names_array: json['microgrid_names'] || [],
463
            subtotals_array: [
464
              json['reporting']['charge_7_days']['values_array'] || [],
465
              json['reporting']['charge_this_month']['values_array'] || [],
466
              json['reporting']['charge_this_year']['values_array'] || []
467
            ]
468
          });
469
          setDischargeEnergyData({
470
            unit: 'kWh',
471
            station_names_array: json['microgrid_names'] || [],
472
            subtotals_array: [
473
              json['reporting']['discharge_7_days']['values_array'] || [],
474
              json['reporting']['discharge_this_month']['values_array'] || [],
475
              json['reporting']['discharge_this_year']['values_array'] || []
476
            ]
477
          });
478
          setEnergyLabels([
479
            json['reporting']['charge_7_days']['timestamps_array'][0] || [],
480
            json['reporting']['charge_this_month']['timestamps_array'][0] || [],
481
            json['reporting']['charge_this_year']['timestamps_array'][0] || []
482
          ]);
483
        }
484
      });
485
  }, [isMicrogridsEnergyFetched]);
486
487
  // Load energy data when microgrid is selected (first tab - auto load)
488
  useEffect(() => {
489
    if (!selectedMicrogrid) return;
490
    const user_uuid = getCookieValue('user_uuid');
491
    loadEnergyDataFunc(user_uuid, selectedMicrogrid);
492
  }, [selectedMicrogrid, loadEnergyDataFunc]);
493
494
  const loadBillingData = useCallback((user_uuid) => {
495
    if (isMicrogridsBillingFetched || !selectedMicrogrid) return;
496
    setIsMicrogridsBillingFetched(true);
497
    let isResponseOK = false;
498
    fetch(APIBaseURL + '/reports/microgridsbilling?useruuid=' + user_uuid + '&microgridid=' + selectedMicrogrid, {
499
      method: 'GET',
500
      headers: {
501
        'Content-type': 'application/json',
502
        'User-UUID': getCookieValue('user_uuid'),
503
        Token: getCookieValue('token')
504
      },
505
      body: null
506
    })
507
      .then(response => {
508
        if (response.ok) {
509
          isResponseOK = true;
510
        }
511
        return response.json();
512
      })
513
      .then(json => {
514
        if (isResponseOK) {
515
          console.log(json);
516
          setChargeBillingData({
517
            unit: currency,
518
            station_names_array: json['microgrid_names'] || [],
519
            subtotals_array: [
520
              json['reporting']['charge_7_days']['values_array'] || [],
521
              json['reporting']['charge_this_month']['values_array'] || [],
522
              json['reporting']['charge_this_year']['values_array'] || []
523
            ]
524
          });
525
          setDischargeBillingData({
526
            unit: currency,
527
            station_names_array: json['microgrid_names'] || [],
528
            subtotals_array: [
529
              json['reporting']['discharge_7_days']['values_array'] || [],
530
              json['reporting']['discharge_this_month']['values_array'] || [],
531
              json['reporting']['discharge_this_year']['values_array'] || []
532
            ]
533
          });
534
          setBillingLabels([
535
            json['reporting']['charge_7_days']['timestamps_array'][0] || [],
536
            json['reporting']['charge_this_month']['timestamps_array'][0] || [],
537
            json['reporting']['charge_this_year']['timestamps_array'][0] || []
538
          ]);
539
        }
540
      });
541
  }, [currency, isMicrogridsBillingFetched, selectedMicrogrid]);
542
543
  const loadCarbonData = useCallback((user_uuid) => {
544
    if (isMicrogridsCarbonFetched || !selectedMicrogrid) return;
545
    setIsMicrogridsCarbonFetched(true);
546
    let isResponseOK = false;
547
    fetch(APIBaseURL + '/reports/microgridscarbon?useruuid=' + user_uuid + '&microgridid=' + selectedMicrogrid, {
548
      method: 'GET',
549
      headers: {
550
        'Content-type': 'application/json',
551
        'User-UUID': getCookieValue('user_uuid'),
552
        Token: getCookieValue('token')
553
      },
554
      body: null
555
    })
556
      .then(response => {
557
        if (response.ok) {
558
          isResponseOK = true;
559
        }
560
        return response.json();
561
      })
562
      .then(json => {
563
        if (isResponseOK) {
564
          console.log(json);
565
          setChargeCarbonData({
566
            unit: 'kgCO2',
567
            station_names_array: json['microgrid_names'] || [],
568
            subtotals_array: [
569
              json['reporting']['charge_7_days']['values_array'] || [],
570
              json['reporting']['charge_this_month']['values_array'] || [],
571
              json['reporting']['charge_this_year']['values_array'] || []
572
            ]
573
          });
574
          setDischargeCarbonData({
575
            unit: 'kgCO2',
576
            station_names_array: json['microgrid_names'] || [],
577
            subtotals_array: [
578
              json['reporting']['discharge_7_days']['values_array'] || [],
579
              json['reporting']['discharge_this_month']['values_array'] || [],
580
              json['reporting']['discharge_this_year']['values_array'] || []
581
            ]
582
          });
583
          setCarbonLabels([
584
            json['reporting']['charge_7_days']['timestamps_array'][0] || [],
585
            json['reporting']['charge_this_month']['timestamps_array'][0] || [],
586
            json['reporting']['charge_this_year']['timestamps_array'][0] || []
587
          ]);
588
        }
589
      });
590
  }, [isMicrogridsCarbonFetched, selectedMicrogrid]);
591
592
  const loadPhotovoltaicData = useCallback((user_uuid) => {
593
    if (isMicrogridsPhotovoltaicFetched || !selectedMicrogrid) return;
594
    setIsMicrogridsPhotovoltaicFetched(true);
595
    let isResponseOK = false;
596
    fetch(APIBaseURL + '/reports/microgridphotovoltaic?useruuid=' + user_uuid + '&microgridid=' + selectedMicrogrid, {
597
      method: 'GET',
598
      headers: {
599
        'Content-type': 'application/json',
600
        'User-UUID': getCookieValue('user_uuid'),
601
        Token: getCookieValue('token')
602
      },
603
      body: null
604
    })
605
      .then(response => {
606
        if (response.ok) {
607
          isResponseOK = true;
608
        }
609
        return response.json();
610
      })
611
      .then(json => {
612
        if (isResponseOK) {
613
          console.log(json);
614
          setPhotovoltaicEnergyData({
615
            unit: 'kWh',
616
            station_names_array: json['microgrid_names'] || [],
617
            subtotals_array: [
618
              json['reporting']['photovoltaic_7_days']['values_array'] || [],
619
              json['reporting']['photovoltaic_this_month']['values_array'] || [],
620
              json['reporting']['photovoltaic_this_year']['values_array'] || []
621
            ]
622
          });
623
          setPhotovoltaicLabels([
624
            json['reporting']['photovoltaic_7_days']['timestamps_array'][0] || [],
625
            json['reporting']['photovoltaic_this_month']['timestamps_array'][0] || [],
626
            json['reporting']['photovoltaic_this_year']['timestamps_array'][0] || []
627
          ]);
628
        }
629
      });
630
  }, [isMicrogridsPhotovoltaicFetched, selectedMicrogrid]);
631
632
  const loadEvchargerData = useCallback((user_uuid) => {
633
    if (isMicrogridsEvchargerFetched || !selectedMicrogrid) return;
634
    setIsMicrogridsEvchargerFetched(true);
635
    let isResponseOK = false;
636
    fetch(APIBaseURL + '/reports/microgridevcharger?useruuid=' + user_uuid + '&microgridid=' + selectedMicrogrid, {
637
      method: 'GET',
638
      headers: {
639
        'Content-type': 'application/json',
640
        'User-UUID': getCookieValue('user_uuid'),
641
        Token: getCookieValue('token')
642
      },
643
      body: null
644
    })
645
      .then(response => {
646
        if (response.ok) {
647
          isResponseOK = true;
648
        }
649
        return response.json();
650
      })
651
      .then(json => {
652
        if (isResponseOK) {
653
          console.log(json);
654
          setEvchargerEnergyData({
655
            unit: 'kWh',
656
            station_names_array: json['microgrid_names'] || [],
657
            subtotals_array: [
658
              json['reporting']['evcharger_7_days']['values_array'] || [],
659
              json['reporting']['evcharger_this_month']['values_array'] || [],
660
              json['reporting']['evcharger_this_year']['values_array'] || []
661
            ]
662
          });
663
          setEvchargerLabels([
664
            json['reporting']['evcharger_7_days']['timestamps_array'][0] || [],
665
            json['reporting']['evcharger_this_month']['timestamps_array'][0] || [],
666
            json['reporting']['evcharger_this_year']['timestamps_array'][0] || []
667
          ]);
668
        }
669
      });
670
  }, [isMicrogridsEvchargerFetched, selectedMicrogrid]);
671
672
  const loadLoadData = useCallback((user_uuid) => {
673
    if (isMicrogridsLoadFetched || !selectedMicrogrid) return;
674
    setIsMicrogridsLoadFetched(true);
675
    let isResponseOK = false;
676
    fetch(APIBaseURL + '/reports/microgridload?useruuid=' + user_uuid + '&microgridid=' + selectedMicrogrid, {
677
      method: 'GET',
678
      headers: {
679
        'Content-type': 'application/json',
680
        'User-UUID': getCookieValue('user_uuid'),
681
        Token: getCookieValue('token')
682
      },
683
      body: null
684
    })
685
      .then(response => {
686
        if (response.ok) {
687
          isResponseOK = true;
688
        }
689
        return response.json();
690
      })
691
      .then(json => {
692
        if (isResponseOK) {
693
          console.log(json);
694
          setLoadEnergyData({
695
            unit: 'kWh',
696
            station_names_array: json['microgrid_names'] || [],
697
            subtotals_array: [
698
              json['reporting']['load_7_days']['values_array'] || [],
699
              json['reporting']['load_this_month']['values_array'] || [],
700
              json['reporting']['load_this_year']['values_array'] || []
701
            ]
702
          });
703
          setLoadLabels([
704
            json['reporting']['load_7_days']['timestamps_array'][0] || [],
705
            json['reporting']['load_this_month']['timestamps_array'][0] || [],
706
            json['reporting']['load_this_year']['timestamps_array'][0] || []
707
          ]);
708
        }
709
      });
710
  }, [isMicrogridsLoadFetched, selectedMicrogrid]);
711
712
  const loadGridBuyData = useCallback((user_uuid) => {
713
    if (isMicrogridsGridBuyFetched || !selectedMicrogrid) return;
714
    setIsMicrogridsGridBuyFetched(true);
715
    let isResponseOK = false;
716
    fetch(APIBaseURL + '/reports/microgridgridbuy?useruuid=' + user_uuid + '&microgridid=' + selectedMicrogrid, {
717
      method: 'GET',
718
      headers: {
719
        'Content-type': 'application/json',
720
        'User-UUID': getCookieValue('user_uuid'),
721
        Token: getCookieValue('token')
722
      },
723
      body: null
724
    })
725
      .then(response => {
726
        if (response.ok) {
727
          isResponseOK = true;
728
        }
729
        return response.json();
730
      })
731
      .then(json => {
732
        if (isResponseOK) {
733
          console.log(json);
734
          setGridBuyEnergyData({
735
            unit: 'kWh',
736
            station_names_array: json['microgrid_names'] || [],
737
            subtotals_array: [
738
              json['reporting']['grid_buy_7_days']['values_array'] || [],
739
              json['reporting']['grid_buy_this_month']['values_array'] || [],
740
              json['reporting']['grid_buy_this_year']['values_array'] || []
741
            ]
742
          });
743
          setGridBuyLabels([
744
            json['reporting']['grid_buy_7_days']['timestamps_array'][0] || [],
745
            json['reporting']['grid_buy_this_month']['timestamps_array'][0] || [],
746
            json['reporting']['grid_buy_this_year']['timestamps_array'][0] || []
747
          ]);
748
        }
749
      });
750
  }, [isMicrogridsGridBuyFetched, selectedMicrogrid]);
751
752
  const loadGridSellData = useCallback((user_uuid) => {
753
    if (isMicrogridsGridSellFetched || !selectedMicrogrid) return;
754
    setIsMicrogridsGridSellFetched(true);
755
    let isResponseOK = false;
756
    fetch(APIBaseURL + '/reports/microgridgridsell?useruuid=' + user_uuid + '&microgridid=' + selectedMicrogrid, {
757
      method: 'GET',
758
      headers: {
759
        'Content-type': 'application/json',
760
        'User-UUID': getCookieValue('user_uuid'),
761
        Token: getCookieValue('token')
762
      },
763
      body: null
764
    })
765
      .then(response => {
766
        if (response.ok) {
767
          isResponseOK = true;
768
        }
769
        return response.json();
770
      })
771
      .then(json => {
772
        if (isResponseOK) {
773
          console.log(json);
774
          setGridSellEnergyData({
775
            unit: 'kWh',
776
            station_names_array: json['microgrid_names'] || [],
777
            subtotals_array: [
778
              json['reporting']['grid_sell_7_days']['values_array'] || [],
779
              json['reporting']['grid_sell_this_month']['values_array'] || [],
780
              json['reporting']['grid_sell_this_year']['values_array'] || []
781
            ]
782
          });
783
          setGridSellLabels([
784
            json['reporting']['grid_sell_7_days']['timestamps_array'][0] || [],
785
            json['reporting']['grid_sell_this_month']['timestamps_array'][0] || [],
786
            json['reporting']['grid_sell_this_year']['timestamps_array'][0] || []
787
          ]);
788
        }
789
      });
790
  }, [isMicrogridsGridSellFetched, selectedMicrogrid]);
791
792
  useEffect(() => {
793
    let timer = setInterval(() => {
794
      let is_logged_in = getCookieValue('is_logged_in');
795
      if (is_logged_in === null || !is_logged_in) {
796
        setRedirectUrl(`/authentication/basic/login`);
797
        setRedirect(true);
798
      }
799
    }, 1000);
800
    return () => clearInterval(timer);
801
  }, [setRedirect, setRedirectUrl]);
802
803
  useEffect(() => {
804
    setLanguage(getItemFromStore('myems_web_ui_language'));
805
  }, [getItemFromStore('myems_web_ui_language')]);
806
807
  return (
808
    <Fragment>
809
      <Form>
810
        <Row form>
811
          <Col xs={6} sm={3} hidden={spaceCascaderHidden}>
812
            <FormGroup className="form-group">
813
              {cascaderOptions && cascaderOptions.length > 0 ? (
814
                <Cascader options={cascaderOptions} onChange={onSpaceCascaderChange} changeOnSelect expandTrigger="hover">
815
                  <Input bsSize="sm" value={selectedSpaceName || ''} readOnly placeholder={t('Select Space')} />
816
                </Cascader>
817
              ) : (
818
                <Input bsSize="sm" value={t('Loading...')} readOnly disabled />
819
              )}
820
            </FormGroup>
821
          </Col>
822
          <Col xs="auto">
823
            <FormGroup>
824
              <Form inline>
825
                <CustomInput
826
                  type="select"
827
                  id="microgridSelect"
828
                  name="microgridSelect"
829
                  bsSize="sm"
830
                  onChange={onMicrogridChange}
831
                  value={selectedMicrogrid || ''}
832
                >
833
                  <option value="">{t('Select Microgrid')}</option>
834
                  {filteredMicrogridList.map((microgrid, index) => (
835
                    <option value={microgrid.value} key={index}>
836
                      {microgrid.label}
837
                    </option>
838
                  ))}
839
                </CustomInput>
840
              </Form>
841
            </FormGroup>
842
          </Col>
843
          <Col xs="auto">
844
            <FormGroup>
845
              <Spinner color="primary" hidden={spinnerHidden} />
846
            </FormGroup>
847
          </Col>
848
        </Row>
849
      </Form>
850
      <div className="card-deck">
851
852
        <CardSummary rate={''} title={t('Total Rated Power')} footunit={'kW'} color="ratedPower">
853
          {1 && <CountUp end={totalRatedPower} duration={2} prefix="" separator="," decimal="." decimals={2} />}
854
        </CardSummary>
855
        <CardSummary rate={''} title={t('Total Rated Capacity')} footunit={'kWh'} color="ratedCapacity">
856
          {1 && <CountUp end={totalRatedCapacity} duration={2} prefix="" separator="," decimal="." decimals={2} />}
857
        </CardSummary>
858
        <CardSummary rate={''} title={t('Total Charge')} footunit={'kWh'} color="electricity">
859
          {1 && <CountUp end={totalCharge} duration={2} prefix="" separator="," decimal="." decimals={2} />}
860
        </CardSummary>
861
        <CardSummary rate={''} title={t('Total Discharge')} footunit={'kWh'} color="electricity">
862
          {1 && <CountUp end={totalDischarge} duration={2} prefix="" separator="," decimal="." decimals={2} />}
863
        </CardSummary>
864
        <CardSummary rate={''} title={t('Total Revenue')} footunit={currency} color="income">
865
          {1 && <CountUp end={totalRevenue} duration={2} prefix="" separator="," decimal="." decimals={2} />}
866
        </CardSummary>
867
        <CardSummary rate={''} title={t('Total Photovoltaic Generation')} footunit={'kWh'} color="electricity">
868
          {1 && <CountUp end={totalPhotovoltaic} duration={2} prefix="" separator="," decimal="." decimals={2} />}
869
        </CardSummary>
870
        <CardSummary rate={''} title={t('Total EV Charger Consumption')} footunit={'kWh'} color="electricity">
871
          {1 && <CountUp end={totalEvcharger} duration={2} prefix="" separator="," decimal="." decimals={2} />}
872
        </CardSummary>
873
        <CardSummary rate={''} title={t('Total Load Consumption')} footunit={'kWh'} color="electricity">
874
          {1 && <CountUp end={totalLoad} duration={2} prefix="" separator="," decimal="." decimals={2} />}
875
        </CardSummary>
876
        <CardSummary rate={''} title={t('Total Grid Buy')} footunit={'kWh'} color="electricity">
877
          {1 && <CountUp end={totalGridBuy} duration={2} prefix="" separator="," decimal="." decimals={2} />}
878
        </CardSummary>
879
        <CardSummary rate={''} title={t('Total Grid Sell')} footunit={'kWh'} color="electricity">
880
          {1 && <CountUp end={totalGridSell} duration={2} prefix="" separator="," decimal="." decimals={2} />}
881
        </CardSummary>
882
      </div>
883
884
      <Row noGutters>
885
        <Col lg={6} xl={6} className="mb-3 pr-lg-2">
886
          <div className="mb-3 card" style={{ height: '100%' }}>
887
            <Nav tabs>
888
              <NavItem className="cursor-pointer">
889
                <NavLink
890
                  className={classNames({ active: activeTabLeft === '1' })}
891
                  onClick={() => {
892
                    toggleTabLeft('1');
893
                  }}
894
                >
895
                  <h6>{t('Microgrid Energy')}</h6>
896
                </NavLink>
897
              </NavItem>
898
              <NavItem className="cursor-pointer">
899
                <NavLink
900
                  className={classNames({ active: activeTabLeft === '2' })}
901
                  onClick={() => {
902
                    toggleTabLeft('2');
903
                  }}
904
                >
905
                  <h6>{t('Microgrid Revenue')}</h6>
906
                </NavLink>
907
              </NavItem>
908
              <NavItem className="cursor-pointer">
909
                <NavLink
910
                  className={classNames({ active: activeTabLeft === '3' })}
911
                  onClick={() => {
912
                    toggleTabLeft('3');
913
                  }}
914
                >
915
                  <h6>{t('Microgrid Carbon')}</h6>
916
                </NavLink>
917
              </NavItem>
918
              <NavItem className="cursor-pointer">
919
                <NavLink
920
                  className={classNames({ active: activeTabLeft === '4' })}
921
                  onClick={() => {
922
                    toggleTabLeft('4');
923
                  }}
924
                >
925
                  <h6>{t('Photovoltaic Generation')}</h6>
926
                </NavLink>
927
              </NavItem>
928
              <NavItem className="cursor-pointer">
929
                <NavLink
930
                  className={classNames({ active: activeTabLeft === '5' })}
931
                  onClick={() => {
932
                    toggleTabLeft('5');
933
                  }}
934
                >
935
                  <h6>{t('EV Charger Consumption')}</h6>
936
                </NavLink>
937
              </NavItem>
938
              <NavItem className="cursor-pointer">
939
                <NavLink
940
                  className={classNames({ active: activeTabLeft === '6' })}
941
                  onClick={() => {
942
                    toggleTabLeft('6');
943
                  }}
944
                >
945
                  <h6>{t('Load Consumption')}</h6>
946
                </NavLink>
947
              </NavItem>
948
              <NavItem className="cursor-pointer">
949
                <NavLink
950
                  className={classNames({ active: activeTabLeft === '7' })}
951
                  onClick={() => {
952
                    toggleTabLeft('7');
953
                  }}
954
                >
955
                  <h6>{t('Grid Buy')}</h6>
956
                </NavLink>
957
              </NavItem>
958
              <NavItem className="cursor-pointer">
959
                <NavLink
960
                  className={classNames({ active: activeTabLeft === '8' })}
961
                  onClick={() => {
962
                    toggleTabLeft('8');
963
                  }}
964
                >
965
                  <h6>{t('Grid Sell')}</h6>
966
                </NavLink>
967
              </NavItem>
968
            </Nav>
969
            <TabContent activeTab={activeTabLeft}>
970
              <TabPane tabId="1">
971
                <StackBarChart
972
                  labels={energyLabels}
973
                  chargeData={chargeEnergyData}
974
                  dischargeData={dischargeEnergyData}
975
                  periodTypes={periodTypes}
976
                  chargeLabelPrefix={chargeEnergyData && chargeEnergyData['unit'] ? t('Microgrid Energy') + ' ' + t('Charge UNIT', { UNIT: chargeEnergyData['unit'] }) : undefined}
977
                  dischargeLabelPrefix={dischargeEnergyData && dischargeEnergyData['unit'] ? t('Microgrid Energy') + ' ' + t('Discharge UNIT', { UNIT: dischargeEnergyData['unit'] }) : undefined}
978
                />
979
              </TabPane>
980
              <TabPane tabId="2">
981
                <StackBarChart
982
                  labels={billingLabels}
983
                  chargeData={chargeBillingData}
984
                  dischargeData={dischargeBillingData}
985
                  periodTypes={periodTypes}
986
                  chargeLabelPrefix={chargeBillingData && chargeBillingData['unit'] ? t('Microgrid Revenue') + ' ' + t('Charge UNIT', { UNIT: chargeBillingData['unit'] }) : undefined}
987
                  dischargeLabelPrefix={dischargeBillingData && dischargeBillingData['unit'] ? t('Microgrid Revenue') + ' ' + t('Discharge UNIT', { UNIT: dischargeBillingData['unit'] }) : undefined}
988
                />
989
              </TabPane>
990
              <TabPane tabId="3">
991
                <StackBarChart
992
                  labels={carbonLabels}
993
                  chargeData={chargeCarbonData}
994
                  dischargeData={dischargeCarbonData}
995
                  periodTypes={periodTypes}
996
                  chargeLabelPrefix={chargeCarbonData && chargeCarbonData['unit'] ? t('Microgrid Carbon') + ' ' + t('Charge UNIT', { UNIT: chargeCarbonData['unit'] }) : undefined}
997
                  dischargeLabelPrefix={dischargeCarbonData && dischargeCarbonData['unit'] ? t('Microgrid Carbon') + ' ' + t('Discharge UNIT', { UNIT: dischargeCarbonData['unit'] }) : undefined}
998
                />
999
              </TabPane>
1000
              <TabPane tabId="4">
1001
                <StackBarChart
1002
                  labels={photovoltaicLabels}
1003
                  chargeData={photovoltaicEnergyData}
1004
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
1005
                  periodTypes={periodTypes}
1006
                  chargeLabelPrefix={photovoltaicEnergyData && photovoltaicEnergyData['unit'] ? t('Photovoltaic Generation') + ' ' + photovoltaicEnergyData['unit'] : undefined}
1007
                />
1008
              </TabPane>
1009
              <TabPane tabId="5">
1010
                <StackBarChart
1011
                  labels={evchargerLabels}
1012
                  chargeData={evchargerEnergyData}
1013
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
1014
                  periodTypes={periodTypes}
1015
                  chargeLabelPrefix={evchargerEnergyData && evchargerEnergyData['unit'] ? t('EV Charger Consumption') + ' ' + evchargerEnergyData['unit'] : undefined}
1016
                />
1017
              </TabPane>
1018
              <TabPane tabId="6">
1019
                <StackBarChart
1020
                  labels={loadLabels}
1021
                  chargeData={loadEnergyData}
1022
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
1023
                  periodTypes={periodTypes}
1024
                  chargeLabelPrefix={loadEnergyData && loadEnergyData['unit'] ? t('Load Consumption') + ' ' + loadEnergyData['unit'] : undefined}
1025
                />
1026
              </TabPane>
1027
              <TabPane tabId="7">
1028
                <StackBarChart
1029
                  labels={gridBuyLabels}
1030
                  chargeData={gridBuyEnergyData}
1031
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
1032
                  periodTypes={periodTypes}
1033
                  chargeLabelPrefix={gridBuyEnergyData && gridBuyEnergyData['unit'] ? t('Grid Buy') + ' ' + gridBuyEnergyData['unit'] : undefined}
1034
                />
1035
              </TabPane>
1036
              <TabPane tabId="8">
1037
                <StackBarChart
1038
                  labels={gridSellLabels}
1039
                  chargeData={gridSellEnergyData}
1040
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
1041
                  periodTypes={periodTypes}
1042
                  chargeLabelPrefix={gridSellEnergyData && gridSellEnergyData['unit'] ? t('Grid Sell') + ' ' + gridSellEnergyData['unit'] : undefined}
1043
                />
1044
              </TabPane>
1045
            </TabContent>
1046
          </div>
1047
        </Col>
1048
        <Col lg={6} xl={6} className="mb-3 pr-lg-2">
1049
          {settings.showOnlineMap ? (
1050
            <div className="mb-3 card" style={{ height: '100%' }}>
1051
              <CustomizeMapBox
1052
                Latitude={rootLatitude}
1053
                Longitude={rootLongitude}
1054
                Zoom={4}
1055
                Geojson={geojson['features']}
1056
              />
1057
            </div>
1058
          ) : (
1059
            <></>
1060
          )}
1061
        </Col>
1062
      </Row>
1063
1064
      <MicrogridTableCard microgridList={microgridList} />
1065
    </Fragment>
1066
  );
1067
};
1068
1069
export default withTranslation()(withRedirect(ItemDashboard));
1070