Passed
Push — master ( 363a8a...c9211f )
by
unknown
11:04 queued 10s
created

myems-web/src/components/MyEMS/Microgrid/Dashboard.js   C

Complexity

Total Complexity 54
Complexity/F 0

Size

Lines of Code 845
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 54
eloc 705
mnd 54
bc 54
fnc 0
dl 0
loc 845
rs 6.375
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/Dashboard.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 } from 'reactstrap';
4
import MicrogridTableCard from './MicrogridTableCard';
5
import CardSummary from '../common/CardSummary';
6
import { toast } from 'react-toastify';
7
import { getCookieValue, createCookie, checkEmpty } from '../../../helpers/utils';
8
import withRedirect from '../../../hoc/withRedirect';
9
import { withTranslation } from 'react-i18next';
10
import moment from 'moment';
11
import { APIBaseURL, settings } from '../../../config';
12
import { getItemFromStore } from '../../../helpers/utils';
13
import CustomizeMapBox from '../common/CustomizeMapBox';
14
import classNames from 'classnames';
15
import AppContext from '../../../context/Context';
16
import StackBarChart from './StackBarChart';
17
18
const Dashboard = ({ setRedirect, setRedirectUrl, t }) => {
19
  let current_moment = moment();
20
  const [isDashboardFetched, setIsDashboardFetched] = useState(false);
21
  const [isMicrogridsEnergyFetched, setIsMicrogridsEnergyFetched] = useState(false);
22
  const [isMicrogridsBillingFetched, setIsMicrogridsBillingFetched] = useState(false);
23
  const [isMicrogridsCarbonFetched, setIsMicrogridsCarbonFetched] = useState(false);
24
  const [isMicrogridsPhotovoltaicFetched, setIsMicrogridsPhotovoltaicFetched] = useState(false);
25
  const [isMicrogridsEvchargerFetched, setIsMicrogridsEvchargerFetched] = useState(false);
26
  const [isMicrogridsLoadFetched, setIsMicrogridsLoadFetched] = useState(false);
27
  const [isMicrogridsGridBuyFetched, setIsMicrogridsGridBuyFetched] = useState(false);
28
  const [isMicrogridsGridSellFetched, setIsMicrogridsGridSellFetched] = useState(false);
29
  const [periodType, setPeriodType] = useState('monthly');
30
  const [basePeriodBeginsDatetime, setBasePeriodBeginsDatetime] = useState(
31
    current_moment
32
      .clone()
33
      .subtract(1, 'years')
34
      .startOf('year')
35
  );
36
  const [basePeriodEndsDatetime, setBasePeriodEndsDatetime] = useState(current_moment.clone().subtract(1, 'years'));
37
  const [reportingPeriodBeginsDatetime, setReportingPeriodBeginsDatetime] = useState(
38
    current_moment.clone().startOf('year')
39
  );
40
  const [reportingPeriodEndsDatetime, setReportingPeriodEndsDatetime] = useState(current_moment);
41
  const [spinnerHidden, setSpinnerHidden] = useState(false);
42
  const [activeTabLeft, setActiveTabLeft] = useState('1');
43
  const toggleTabLeft = tab => {
44
    if (activeTabLeft !== tab) {
45
      setActiveTabLeft(tab);
46
      // Load data for the selected tab if not already loaded
47
      const user_uuid = getCookieValue('user_uuid');
48
      if (tab === '2' && !isMicrogridsBillingFetched) {
49
        loadBillingData(user_uuid);
50
      } else if (tab === '3' && !isMicrogridsCarbonFetched) {
51
        loadCarbonData(user_uuid);
52
      } else if (tab === '4' && !isMicrogridsPhotovoltaicFetched) {
53
        loadPhotovoltaicData(user_uuid);
54
      } else if (tab === '5' && !isMicrogridsEvchargerFetched) {
55
        loadEvchargerData(user_uuid);
56
      } else if (tab === '6' && !isMicrogridsLoadFetched) {
57
        loadLoadData(user_uuid);
58
      } else if (tab === '7' && !isMicrogridsGridBuyFetched) {
59
        loadGridBuyData(user_uuid);
60
      } else if (tab === '8' && !isMicrogridsGridSellFetched) {
61
        loadGridSellData(user_uuid);
62
      }
63
    }
64
  };
65
  const [activeTabRight, setActiveTabRight] = useState('1');
66
  const toggleTabRight = tab => {
67
    if (activeTabRight !== tab) setActiveTabRight(tab);
68
  };
69
  const { currency } = useContext(AppContext);
70
71
  //Results
72
73
  const [microgridList, setMicrogridList] = useState([]);
74
  const [totalRatedCapacity, setTotalRatedCapacity] = useState({});
75
  const [totalRatedPower, setTotalRatedPower] = useState({});
76
  const [totalCharge, setTotalCharge] = useState({});
77
  const [totalDischarge, setTotalDischarge] = useState({});
78
  const [totalRevenue, setTotalRevenue] = useState({});
79
  const [totalPhotovoltaic, setTotalPhotovoltaic] = useState(0);
80
  const [totalEvcharger, setTotalEvcharger] = useState(0);
81
  const [totalLoad, setTotalLoad] = useState(0);
82
  const [totalGridBuy, setTotalGridBuy] = useState(0);
83
  const [totalGridSell, setTotalGridSell] = useState(0);
84
85
  const [chargeEnergyData, setChargeEnergyData] = useState({});
86
  const [dischargeEnergyData, setDischargeEnergyData] = useState({});
87
  const [chargeBillingData, setChargeBillingData] = useState({});
88
  const [dischargeBillingData, setDischargeBillingData] = useState({});
89
  const [chargeCarbonData, setChargeCarbonData] = useState({});
90
  const [dischargeCarbonData, setDischargeCarbonData] = useState({});
91
  const [photovoltaicEnergyData, setPhotovoltaicEnergyData] = useState({});
92
  const [evchargerEnergyData, setEvchargerEnergyData] = useState({});
93
  const [loadEnergyData, setLoadEnergyData] = useState({});
94
  const [gridBuyEnergyData, setGridBuyEnergyData] = useState({});
95
  const [gridSellEnergyData, setGridSellEnergyData] = useState({});
96
  const [energyLabels, setEnergyLabels] = useState([]);
97
  const [billingLabels, setBillingLabels] = useState([]);
98
  const [carbonLabels, setCarbonLabels] = useState([]);
99
  const [photovoltaicLabels, setPhotovoltaicLabels] = useState([]);
100
  const [evchargerLabels, setEvchargerLabels] = useState([]);
101
  const [loadLabels, setLoadLabels] = useState([]);
102
  const [gridBuyLabels, setGridBuyLabels] = useState([]);
103
  const [gridSellLabels, setGridSellLabels] = useState([]);
104
  const [periodTypes, setPeriodTypes] = useState([
105
    { value: 'a0', label: t('7 Days') },
106
    { value: 'a1', label: t('This Month') },
107
    { value: 'a2', label: t('This Year') }
108
  ]);
109
  const [language, setLanguage] = useState(getItemFromStore('myems_web_ui_language', settings.language));
110
  const [geojson, setGeojson] = useState({});
111
  const [rootLatitude, setRootLatitude] = useState('');
112
  const [rootLongitude, setRootLongitude] = useState('');
113
114
  useEffect(() => {
115
    let is_logged_in = getCookieValue('is_logged_in');
116
    let user_name = getCookieValue('user_name');
117
    let user_display_name = getCookieValue('user_display_name');
118
    let user_uuid = getCookieValue('user_uuid');
119
    let token = getCookieValue('token');
120
    if (checkEmpty(is_logged_in) || checkEmpty(token) || checkEmpty(user_uuid) || !is_logged_in) {
121
      setRedirectUrl(`/authentication/basic/login`);
122
      setRedirect(true);
123
    } else {
124
      //update expires time of cookies
125
      createCookie('is_logged_in', true, settings.cookieExpireTime);
126
      createCookie('user_name', user_name, settings.cookieExpireTime);
127
      createCookie('user_display_name', user_display_name, settings.cookieExpireTime);
128
      createCookie('user_uuid', user_uuid, settings.cookieExpireTime);
129
      createCookie('token', token, settings.cookieExpireTime);
130
131
      let isResponseOK = false;
132
      if (!isDashboardFetched) {
133
        setIsDashboardFetched(true);
134
        toast(
135
          <Fragment>
136
            {t('Welcome to MyEMS')}
137
            <br />
138
            {t('An Industry Leading Open Source Energy Management System')}
139
          </Fragment>
140
        );
141
142
        fetch(
143
          APIBaseURL +
144
            '/reports/microgriddashboard?' +
145
            'useruuid=' +
146
            user_uuid +
147
            '&periodtype=' +
148
            periodType +
149
            '&baseperiodstartdatetime=' +
150
            (basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
151
            '&baseperiodenddatetime=' +
152
            (basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
153
            '&reportingperiodstartdatetime=' +
154
            reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') +
155
            '&reportingperiodenddatetime=' +
156
            reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'),
157
          {
158
            method: 'GET',
159
            headers: {
160
              'Content-type': 'application/json',
161
              'User-UUID': getCookieValue('user_uuid'),
162
              Token: getCookieValue('token')
163
            },
164
            body: null
165
          }
166
        )
167
          .then(response => {
168
            if (response.ok) {
169
              isResponseOK = true;
170
            }
171
            return response.json();
172
          })
173
          .then(json => {
174
            if (isResponseOK) {
175
              console.log(json);
176
              // hide spinner
177
              setSpinnerHidden(true);
178
179
              let microgridList = [];
180
              let totalRatedCapacity = 0;
181
              let totalRatedPower = 0;
182
183
              setRootLongitude(json['microgrids'][0]['longitude']);
184
              setRootLatitude(json['microgrids'][0]['latitude']);
185
              let geojson = {};
186
              let geojsonData = [];
187
              json['microgrids'].forEach((currentValue, index) => {
188
                let microgridItem = json['microgrids'][index];
189
                totalRatedCapacity += microgridItem['rated_capacity'];
190
                totalRatedPower += microgridItem['rated_power'];
191
                if (microgridItem['latitude'] && microgridItem['longitude']) {
192
                  geojsonData.push({
193
                    type: 'Feature',
194
                    geometry: {
195
                      type: 'Point',
196
                      coordinates: [microgridItem['longitude'], microgridItem['latitude']]
197
                    },
198
                    properties: {
199
                      title: microgridItem['name'],
200
                      description: microgridItem['description'],
201
                      uuid: microgridItem['uuid'],
202
                      url: '/microgrid/details'
203
                    }
204
                  });
205
                }
206
                microgridItem['nameuuid'] = microgridItem['name'] + microgridItem['uuid'];
207
                microgridList.push(microgridItem);
208
              });
209
              setMicrogridList(microgridList);
210
              setTotalRatedCapacity(totalRatedCapacity);
211
              setTotalRatedPower(totalRatedPower);
212
              geojson['type'] = 'FeatureCollection';
213
              geojson['features'] = geojsonData;
214
              setGeojson(geojson);
215
216
              setTotalCharge(json['total_charge_energy']);
217
218
              setTotalDischarge(json['total_discharge_energy']);
219
220
              setTotalRevenue(json['total_discharge_billing']);
221
222
              setTotalPhotovoltaic(json['total_photovoltaic_energy'] || 0);
223
224
              setTotalEvcharger(json['total_evcharger_energy'] || 0);
225
226
              setTotalLoad(json['total_load_energy'] || 0);
227
228
              setTotalGridBuy(json['total_grid_buy_energy'] || 0);
229
230
              setTotalGridSell(json['total_grid_sell_energy'] || 0);
231
            }
232
          });
233
      }
234
    }
235
  });
236
237
  useEffect(() => {
238
    let is_logged_in = getCookieValue('is_logged_in');
239
    let user_name = getCookieValue('user_name');
240
    let user_display_name = getCookieValue('user_display_name');
241
    let user_uuid = getCookieValue('user_uuid');
242
    let token = getCookieValue('token');
243
    if (checkEmpty(is_logged_in) || checkEmpty(token) || checkEmpty(user_uuid) || !is_logged_in) {
244
      setRedirectUrl(`/authentication/basic/login`);
245
      setRedirect(true);
246
    } else {
247
      //update expires time of cookies
248
      createCookie('is_logged_in', true, settings.cookieExpireTime);
249
      createCookie('user_name', user_name, settings.cookieExpireTime);
250
      createCookie('user_display_name', user_display_name, settings.cookieExpireTime);
251
      createCookie('user_uuid', user_uuid, settings.cookieExpireTime);
252
      createCookie('token', token, settings.cookieExpireTime);
253
254
      let isResponseOK = false;
255
      if (!isMicrogridsEnergyFetched) {
256
        setIsMicrogridsEnergyFetched(true);
257
        fetch(APIBaseURL + '/reports/microgridsenergy?useruuid=' + user_uuid, {
258
          method: 'GET',
259
          headers: {
260
            'Content-type': 'application/json',
261
            'User-UUID': getCookieValue('user_uuid'),
262
            Token: getCookieValue('token')
263
          },
264
          body: null
265
        })
266
          .then(response => {
267
            if (response.ok) {
268
              isResponseOK = true;
269
            }
270
            return response.json();
271
          })
272
          .then(json => {
273
            if (isResponseOK) {
274
              console.log(json);
275
276
              setChargeEnergyData({
277
                unit: 'kWh',
278
                station_names_array: json['microgrid_names'],
279
                subtotals_array: [
280
                  json['reporting']['charge_7_days']['values_array'],
281
                  json['reporting']['charge_this_month']['values_array'],
282
                  json['reporting']['charge_this_year']['values_array']
283
                ]
284
              });
285
              setDischargeEnergyData({
286
                unit: 'kWh',
287
                station_names_array: json['microgrid_names'],
288
                subtotals_array: [
289
                  json['reporting']['discharge_7_days']['values_array'],
290
                  json['reporting']['discharge_this_month']['values_array'],
291
                  json['reporting']['discharge_this_year']['values_array']
292
                ]
293
              });
294
              setEnergyLabels([
295
                json['reporting']['charge_7_days']['timestamps_array'][0],
296
                json['reporting']['charge_this_month']['timestamps_array'][0],
297
                json['reporting']['charge_this_year']['timestamps_array'][0]
298
              ]);
299
            }
300
          });
301
      }
302
    }
303
  });
304
305
  // Load functions for each tab (called on demand when tab is activated)
306
  const loadBillingData = useCallback((user_uuid) => {
307
    if (isMicrogridsBillingFetched) return;
308
    setIsMicrogridsBillingFetched(true);
309
    let isResponseOK = false;
310
    fetch(APIBaseURL + '/reports/microgridsbilling?useruuid=' + user_uuid, {
311
      method: 'GET',
312
      headers: {
313
        'Content-type': 'application/json',
314
        'User-UUID': getCookieValue('user_uuid'),
315
        Token: getCookieValue('token')
316
      },
317
      body: null
318
    })
319
      .then(response => {
320
        if (response.ok) {
321
          isResponseOK = true;
322
        }
323
        return response.json();
324
      })
325
      .then(json => {
326
        if (isResponseOK) {
327
          console.log(json);
328
          setChargeBillingData({
329
            unit: currency,
330
            station_names_array: json['microgrid_names'],
331
            subtotals_array: [
332
              json['reporting']['charge_7_days']['values_array'],
333
              json['reporting']['charge_this_month']['values_array'],
334
              json['reporting']['charge_this_year']['values_array']
335
            ]
336
          });
337
          setDischargeBillingData({
338
            unit: currency,
339
            station_names_array: json['microgrid_names'],
340
            subtotals_array: [
341
              json['reporting']['discharge_7_days']['values_array'],
342
              json['reporting']['discharge_this_month']['values_array'],
343
              json['reporting']['discharge_this_year']['values_array']
344
            ]
345
          });
346
          setBillingLabels([
347
            json['reporting']['charge_7_days']['timestamps_array'][0],
348
            json['reporting']['charge_this_month']['timestamps_array'][0],
349
            json['reporting']['charge_this_year']['timestamps_array'][0]
350
          ]);
351
        }
352
      });
353
  }, [currency, isMicrogridsBillingFetched]);
354
355
  const loadCarbonData = useCallback((user_uuid) => {
356
    if (isMicrogridsCarbonFetched) return;
357
    setIsMicrogridsCarbonFetched(true);
358
    let isResponseOK = false;
359
    fetch(APIBaseURL + '/reports/microgridscarbon?useruuid=' + user_uuid, {
360
      method: 'GET',
361
      headers: {
362
        'Content-type': 'application/json',
363
        'User-UUID': getCookieValue('user_uuid'),
364
        Token: getCookieValue('token')
365
      },
366
      body: null
367
    })
368
      .then(response => {
369
        if (response.ok) {
370
          isResponseOK = true;
371
        }
372
        return response.json();
373
      })
374
      .then(json => {
375
        if (isResponseOK) {
376
          console.log(json);
377
          setChargeCarbonData({
378
            unit: 'kgCO2',
379
            station_names_array: json['microgrid_names'],
380
            subtotals_array: [
381
              json['reporting']['charge_7_days']['values_array'],
382
              json['reporting']['charge_this_month']['values_array'],
383
              json['reporting']['charge_this_year']['values_array']
384
            ]
385
          });
386
          setDischargeCarbonData({
387
            unit: 'kgCO2',
388
            station_names_array: json['microgrid_names'],
389
            subtotals_array: [
390
              json['reporting']['discharge_7_days']['values_array'],
391
              json['reporting']['discharge_this_month']['values_array'],
392
              json['reporting']['discharge_this_year']['values_array']
393
            ]
394
          });
395
          setCarbonLabels([
396
            json['reporting']['charge_7_days']['timestamps_array'][0],
397
            json['reporting']['charge_this_month']['timestamps_array'][0],
398
            json['reporting']['charge_this_year']['timestamps_array'][0]
399
          ]);
400
        }
401
      });
402
  }, [isMicrogridsCarbonFetched]);
403
404
  const loadPhotovoltaicData = useCallback((user_uuid) => {
405
    if (isMicrogridsPhotovoltaicFetched) return;
406
    setIsMicrogridsPhotovoltaicFetched(true);
407
    let isResponseOK = false;
408
    fetch(APIBaseURL + '/reports/microgridphotovoltaic?useruuid=' + user_uuid, {
409
      method: 'GET',
410
      headers: {
411
        'Content-type': 'application/json',
412
        'User-UUID': getCookieValue('user_uuid'),
413
        Token: getCookieValue('token')
414
      },
415
      body: null
416
    })
417
      .then(response => {
418
        if (response.ok) {
419
          isResponseOK = true;
420
        }
421
        return response.json();
422
      })
423
      .then(json => {
424
        if (isResponseOK) {
425
          console.log(json);
426
          setPhotovoltaicEnergyData({
427
            unit: 'kWh',
428
            station_names_array: json['microgrid_names'],
429
            subtotals_array: [
430
              json['reporting']['photovoltaic_7_days']['values_array'],
431
              json['reporting']['photovoltaic_this_month']['values_array'],
432
              json['reporting']['photovoltaic_this_year']['values_array']
433
            ]
434
          });
435
          setPhotovoltaicLabels([
436
            json['reporting']['photovoltaic_7_days']['timestamps_array'][0],
437
            json['reporting']['photovoltaic_this_month']['timestamps_array'][0],
438
            json['reporting']['photovoltaic_this_year']['timestamps_array'][0]
439
          ]);
440
        }
441
      });
442
  }, [isMicrogridsPhotovoltaicFetched]);
443
444
  const loadEvchargerData = useCallback((user_uuid) => {
445
    if (isMicrogridsEvchargerFetched) return;
446
    setIsMicrogridsEvchargerFetched(true);
447
    let isResponseOK = false;
448
    fetch(APIBaseURL + '/reports/microgridevcharger?useruuid=' + user_uuid, {
449
      method: 'GET',
450
      headers: {
451
        'Content-type': 'application/json',
452
        'User-UUID': getCookieValue('user_uuid'),
453
        Token: getCookieValue('token')
454
      },
455
      body: null
456
    })
457
      .then(response => {
458
        if (response.ok) {
459
          isResponseOK = true;
460
        }
461
        return response.json();
462
      })
463
      .then(json => {
464
        if (isResponseOK) {
465
          console.log(json);
466
          setEvchargerEnergyData({
467
            unit: 'kWh',
468
            station_names_array: json['microgrid_names'],
469
            subtotals_array: [
470
              json['reporting']['evcharger_7_days']['values_array'],
471
              json['reporting']['evcharger_this_month']['values_array'],
472
              json['reporting']['evcharger_this_year']['values_array']
473
            ]
474
          });
475
          setEvchargerLabels([
476
            json['reporting']['evcharger_7_days']['timestamps_array'][0],
477
            json['reporting']['evcharger_this_month']['timestamps_array'][0],
478
            json['reporting']['evcharger_this_year']['timestamps_array'][0]
479
          ]);
480
        }
481
      });
482
  }, [isMicrogridsEvchargerFetched]);
483
484
  const loadLoadData = useCallback((user_uuid) => {
485
    if (isMicrogridsLoadFetched) return;
486
    setIsMicrogridsLoadFetched(true);
487
    let isResponseOK = false;
488
    fetch(APIBaseURL + '/reports/microgridload?useruuid=' + user_uuid, {
489
      method: 'GET',
490
      headers: {
491
        'Content-type': 'application/json',
492
        'User-UUID': getCookieValue('user_uuid'),
493
        Token: getCookieValue('token')
494
      },
495
      body: null
496
    })
497
      .then(response => {
498
        if (response.ok) {
499
          isResponseOK = true;
500
        }
501
        return response.json();
502
      })
503
      .then(json => {
504
        if (isResponseOK) {
505
          console.log(json);
506
          setLoadEnergyData({
507
            unit: 'kWh',
508
            station_names_array: json['microgrid_names'],
509
            subtotals_array: [
510
              json['reporting']['load_7_days']['values_array'],
511
              json['reporting']['load_this_month']['values_array'],
512
              json['reporting']['load_this_year']['values_array']
513
            ]
514
          });
515
          setLoadLabels([
516
            json['reporting']['load_7_days']['timestamps_array'][0],
517
            json['reporting']['load_this_month']['timestamps_array'][0],
518
            json['reporting']['load_this_year']['timestamps_array'][0]
519
          ]);
520
        }
521
      });
522
  }, [isMicrogridsLoadFetched]);
523
524
  const loadGridBuyData = useCallback((user_uuid) => {
525
    if (isMicrogridsGridBuyFetched) return;
526
    setIsMicrogridsGridBuyFetched(true);
527
    let isResponseOK = false;
528
    fetch(APIBaseURL + '/reports/microgridgridbuy?useruuid=' + user_uuid, {
529
      method: 'GET',
530
      headers: {
531
        'Content-type': 'application/json',
532
        'User-UUID': getCookieValue('user_uuid'),
533
        Token: getCookieValue('token')
534
      },
535
      body: null
536
    })
537
      .then(response => {
538
        if (response.ok) {
539
          isResponseOK = true;
540
        }
541
        return response.json();
542
      })
543
      .then(json => {
544
        if (isResponseOK) {
545
          console.log(json);
546
          setGridBuyEnergyData({
547
            unit: 'kWh',
548
            station_names_array: json['microgrid_names'],
549
            subtotals_array: [
550
              json['reporting']['grid_buy_7_days']['values_array'],
551
              json['reporting']['grid_buy_this_month']['values_array'],
552
              json['reporting']['grid_buy_this_year']['values_array']
553
            ]
554
          });
555
          setGridBuyLabels([
556
            json['reporting']['grid_buy_7_days']['timestamps_array'][0],
557
            json['reporting']['grid_buy_this_month']['timestamps_array'][0],
558
            json['reporting']['grid_buy_this_year']['timestamps_array'][0]
559
          ]);
560
        }
561
      });
562
  }, [isMicrogridsGridBuyFetched]);
563
564
  const loadGridSellData = useCallback((user_uuid) => {
565
    if (isMicrogridsGridSellFetched) return;
566
    setIsMicrogridsGridSellFetched(true);
567
    let isResponseOK = false;
568
    fetch(APIBaseURL + '/reports/microgridgridsell?useruuid=' + user_uuid, {
569
      method: 'GET',
570
      headers: {
571
        'Content-type': 'application/json',
572
        'User-UUID': getCookieValue('user_uuid'),
573
        Token: getCookieValue('token')
574
      },
575
      body: null
576
    })
577
      .then(response => {
578
        if (response.ok) {
579
          isResponseOK = true;
580
        }
581
        return response.json();
582
      })
583
      .then(json => {
584
        if (isResponseOK) {
585
          console.log(json);
586
          setGridSellEnergyData({
587
            unit: 'kWh',
588
            station_names_array: json['microgrid_names'],
589
            subtotals_array: [
590
              json['reporting']['grid_sell_7_days']['values_array'],
591
              json['reporting']['grid_sell_this_month']['values_array'],
592
              json['reporting']['grid_sell_this_year']['values_array']
593
            ]
594
          });
595
          setGridSellLabels([
596
            json['reporting']['grid_sell_7_days']['timestamps_array'][0],
597
            json['reporting']['grid_sell_this_month']['timestamps_array'][0],
598
            json['reporting']['grid_sell_this_year']['timestamps_array'][0]
599
          ]);
600
        }
601
      });
602
  }, [isMicrogridsGridSellFetched]);
603
604
  useEffect(() => {
605
    let timer = setInterval(() => {
606
      let is_logged_in = getCookieValue('is_logged_in');
607
      if (is_logged_in === null || !is_logged_in) {
608
        setRedirectUrl(`/authentication/basic/login`);
609
        setRedirect(true);
610
      }
611
    }, 1000);
612
    return () => clearInterval(timer);
613
  }, [setRedirect, setRedirectUrl]);
614
615
  useEffect(() => {
616
    setLanguage(getItemFromStore('myems_web_ui_language'));
617
  }, [getItemFromStore('myems_web_ui_language')]);
618
619
  return (
620
    <Fragment>
621
      <div className="card-deck">
622
        <Spinner color="primary" hidden={spinnerHidden} />
623
624
        <CardSummary rate={''} title={t('Number of Microgrids')} footunit={''} color="powerStation">
625
          {1 && <CountUp end={microgridList.length} duration={2} prefix="" separator="," decimal="." decimals={0} />}
626
        </CardSummary>
627
        <CardSummary rate={''} title={t('Total Rated Power')} footunit={'kW'} color="ratedPower">
628
          {1 && <CountUp end={totalRatedPower} duration={2} prefix="" separator="," decimal="." decimals={2} />}
629
        </CardSummary>
630
        <CardSummary rate={''} title={t('Total Rated Capacity')} footunit={'kWh'} color="ratedCapacity">
631
          {1 && <CountUp end={totalRatedCapacity} duration={2} prefix="" separator="," decimal="." decimals={2} />}
632
        </CardSummary>
633
        <CardSummary rate={''} title={t('Total Charge')} footunit={'kWh'} color="electricity">
634
          {1 && <CountUp end={totalCharge} duration={2} prefix="" separator="," decimal="." decimals={2} />}
635
        </CardSummary>
636
        <CardSummary rate={''} title={t('Total Discharge')} footunit={'kWh'} color="electricity">
637
          {1 && <CountUp end={totalDischarge} duration={2} prefix="" separator="," decimal="." decimals={2} />}
638
        </CardSummary>
639
        <CardSummary rate={''} title={t('Total Revenue')} footunit={currency} color="income">
640
          {1 && <CountUp end={totalRevenue} duration={2} prefix="" separator="," decimal="." decimals={2} />}
641
        </CardSummary>
642
        <CardSummary rate={''} title={t('Total Photovoltaic Generation')} footunit={'kWh'} color="electricity">
643
          {1 && <CountUp end={totalPhotovoltaic} duration={2} prefix="" separator="," decimal="." decimals={2} />}
644
        </CardSummary>
645
        <CardSummary rate={''} title={t('Total EV Charger Consumption')} footunit={'kWh'} color="electricity">
646
          {1 && <CountUp end={totalEvcharger} duration={2} prefix="" separator="," decimal="." decimals={2} />}
647
        </CardSummary>
648
        <CardSummary rate={''} title={t('Total Load Consumption')} footunit={'kWh'} color="electricity">
649
          {1 && <CountUp end={totalLoad} duration={2} prefix="" separator="," decimal="." decimals={2} />}
650
        </CardSummary>
651
        <CardSummary rate={''} title={t('Total Grid Buy')} footunit={'kWh'} color="electricity">
652
          {1 && <CountUp end={totalGridBuy} duration={2} prefix="" separator="," decimal="." decimals={2} />}
653
        </CardSummary>
654
        <CardSummary rate={''} title={t('Total Grid Sell')} footunit={'kWh'} color="electricity">
655
          {1 && <CountUp end={totalGridSell} duration={2} prefix="" separator="," decimal="." decimals={2} />}
656
        </CardSummary>
657
      </div>
658
659
      <Row noGutters>
660
        <Col lg={6} xl={6} className="mb-3 pr-lg-2">
661
          <div className="mb-3 card" style={{ height: '100%' }}>
662
            <Nav tabs>
663
              <NavItem className="cursor-pointer">
664
                <NavLink
665
                  className={classNames({ active: activeTabLeft === '1' })}
666
                  onClick={() => {
667
                    toggleTabLeft('1');
668
                  }}
669
                >
670
                  <h6>{t('Microgrid Energy')}</h6>
671
                </NavLink>
672
              </NavItem>
673
              <NavItem className="cursor-pointer">
674
                <NavLink
675
                  className={classNames({ active: activeTabLeft === '2' })}
676
                  onClick={() => {
677
                    toggleTabLeft('2');
678
                  }}
679
                >
680
                  <h6>{t('Microgrid Revenue')}</h6>
681
                </NavLink>
682
              </NavItem>
683
              <NavItem className="cursor-pointer">
684
                <NavLink
685
                  className={classNames({ active: activeTabLeft === '3' })}
686
                  onClick={() => {
687
                    toggleTabLeft('3');
688
                  }}
689
                >
690
                  <h6>{t('Microgrid Carbon')}</h6>
691
                </NavLink>
692
              </NavItem>
693
              <NavItem className="cursor-pointer">
694
                <NavLink
695
                  className={classNames({ active: activeTabLeft === '4' })}
696
                  onClick={() => {
697
                    toggleTabLeft('4');
698
                  }}
699
                >
700
                  <h6>{t('Photovoltaic Generation')}</h6>
701
                </NavLink>
702
              </NavItem>
703
              <NavItem className="cursor-pointer">
704
                <NavLink
705
                  className={classNames({ active: activeTabLeft === '5' })}
706
                  onClick={() => {
707
                    toggleTabLeft('5');
708
                  }}
709
                >
710
                  <h6>{t('EV Charger Consumption')}</h6>
711
                </NavLink>
712
              </NavItem>
713
              <NavItem className="cursor-pointer">
714
                <NavLink
715
                  className={classNames({ active: activeTabLeft === '6' })}
716
                  onClick={() => {
717
                    toggleTabLeft('6');
718
                  }}
719
                >
720
                  <h6>{t('Load Consumption')}</h6>
721
                </NavLink>
722
              </NavItem>
723
              <NavItem className="cursor-pointer">
724
                <NavLink
725
                  className={classNames({ active: activeTabLeft === '7' })}
726
                  onClick={() => {
727
                    toggleTabLeft('7');
728
                  }}
729
                >
730
                  <h6>{t('Grid Buy')}</h6>
731
                </NavLink>
732
              </NavItem>
733
              <NavItem className="cursor-pointer">
734
                <NavLink
735
                  className={classNames({ active: activeTabLeft === '8' })}
736
                  onClick={() => {
737
                    toggleTabLeft('8');
738
                  }}
739
                >
740
                  <h6>{t('Grid Sell')}</h6>
741
                </NavLink>
742
              </NavItem>
743
            </Nav>
744
            <TabContent activeTab={activeTabLeft}>
745
              <TabPane tabId="1">
746
                <StackBarChart
747
                  labels={energyLabels}
748
                  chargeData={chargeEnergyData}
749
                  dischargeData={dischargeEnergyData}
750
                  periodTypes={periodTypes}
751
                  chargeLabelPrefix={chargeEnergyData && chargeEnergyData['unit'] ? t('Microgrid Energy') + ' ' + t('Charge UNIT', { UNIT: chargeEnergyData['unit'] }) : undefined}
752
                  dischargeLabelPrefix={dischargeEnergyData && dischargeEnergyData['unit'] ? t('Microgrid Energy') + ' ' + t('Discharge UNIT', { UNIT: dischargeEnergyData['unit'] }) : undefined}
753
                />
754
              </TabPane>
755
              <TabPane tabId="2">
756
                <StackBarChart
757
                  labels={billingLabels}
758
                  chargeData={chargeBillingData}
759
                  dischargeData={dischargeBillingData}
760
                  periodTypes={periodTypes}
761
                  chargeLabelPrefix={chargeBillingData && chargeBillingData['unit'] ? t('Microgrid Revenue') + ' ' + t('Charge UNIT', { UNIT: chargeBillingData['unit'] }) : undefined}
762
                  dischargeLabelPrefix={dischargeBillingData && dischargeBillingData['unit'] ? t('Microgrid Revenue') + ' ' + t('Discharge UNIT', { UNIT: dischargeBillingData['unit'] }) : undefined}
763
                />
764
              </TabPane>
765
              <TabPane tabId="3">
766
                <StackBarChart
767
                  labels={carbonLabels}
768
                  chargeData={chargeCarbonData}
769
                  dischargeData={dischargeCarbonData}
770
                  periodTypes={periodTypes}
771
                  chargeLabelPrefix={chargeCarbonData && chargeCarbonData['unit'] ? t('Microgrid Carbon') + ' ' + t('Charge UNIT', { UNIT: chargeCarbonData['unit'] }) : undefined}
772
                  dischargeLabelPrefix={dischargeCarbonData && dischargeCarbonData['unit'] ? t('Microgrid Carbon') + ' ' + t('Discharge UNIT', { UNIT: dischargeCarbonData['unit'] }) : undefined}
773
                />
774
              </TabPane>
775
              <TabPane tabId="4">
776
                <StackBarChart
777
                  labels={photovoltaicLabels}
778
                  chargeData={photovoltaicEnergyData}
779
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
780
                  periodTypes={periodTypes}
781
                  chargeLabelPrefix={photovoltaicEnergyData && photovoltaicEnergyData['unit'] ? t('Photovoltaic Generation') + ' ' + photovoltaicEnergyData['unit'] : undefined}
782
                />
783
              </TabPane>
784
              <TabPane tabId="5">
785
                <StackBarChart
786
                  labels={evchargerLabels}
787
                  chargeData={evchargerEnergyData}
788
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
789
                  periodTypes={periodTypes}
790
                  chargeLabelPrefix={evchargerEnergyData && evchargerEnergyData['unit'] ? t('EV Charger Consumption') + ' ' + evchargerEnergyData['unit'] : undefined}
791
                />
792
              </TabPane>
793
              <TabPane tabId="6">
794
                <StackBarChart
795
                  labels={loadLabels}
796
                  chargeData={loadEnergyData}
797
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
798
                  periodTypes={periodTypes}
799
                  chargeLabelPrefix={loadEnergyData && loadEnergyData['unit'] ? t('Load Consumption') + ' ' + loadEnergyData['unit'] : undefined}
800
                />
801
              </TabPane>
802
              <TabPane tabId="7">
803
                <StackBarChart
804
                  labels={gridBuyLabels}
805
                  chargeData={gridBuyEnergyData}
806
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
807
                  periodTypes={periodTypes}
808
                  chargeLabelPrefix={gridBuyEnergyData && gridBuyEnergyData['unit'] ? t('Grid Buy') + ' ' + gridBuyEnergyData['unit'] : undefined}
809
                />
810
              </TabPane>
811
              <TabPane tabId="8">
812
                <StackBarChart
813
                  labels={gridSellLabels}
814
                  chargeData={gridSellEnergyData}
815
                  dischargeData={{ unit: 'kWh', station_names_array: [], subtotals_array: [] }}
816
                  periodTypes={periodTypes}
817
                  chargeLabelPrefix={gridSellEnergyData && gridSellEnergyData['unit'] ? t('Grid Sell') + ' ' + gridSellEnergyData['unit'] : undefined}
818
                />
819
              </TabPane>
820
            </TabContent>
821
          </div>
822
        </Col>
823
        <Col lg={6} xl={6} className="mb-3 pr-lg-2">
824
          {settings.showOnlineMap ? (
825
            <div className="mb-3 card" style={{ height: '100%' }}>
826
              <CustomizeMapBox
827
                Latitude={rootLatitude}
828
                Longitude={rootLongitude}
829
                Zoom={4}
830
                Geojson={geojson['features']}
831
              />
832
            </div>
833
          ) : (
834
            <></>
835
          )}
836
        </Col>
837
      </Row>
838
839
      <MicrogridTableCard microgridList={microgridList} />
840
    </Fragment>
841
  );
842
};
843
844
export default withTranslation()(withRedirect(Dashboard));
845