Issues (1577)

myems-api/reports/tenantstatistics.py (3 issues)

1
import re
2
from datetime import datetime, timedelta, timezone
3
from decimal import Decimal
4
import falcon
5
import mysql.connector
6
import simplejson as json
7
import config
8
import excelexporters.tenantstatistics
9
from core import utilities
10
from core.useractivity import access_control, api_key_control
11
12
13 View Code Duplication
class Reporting:
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
14
    def __init__(self):
15
        """"Initializes Reporting"""
16
        pass
17
18
    @staticmethod
19
    def on_options(req, resp):
20
        _ = req
21
        resp.status = falcon.HTTP_200
22
23
    ####################################################################################################################
24
    # PROCEDURES
25
    # Step 1: valid parameters
26
    # Step 2: query the tenant
27
    # Step 3: query energy categories
28
    # Step 4: query associated sensors
29
    # Step 5: query associated points
30
    # Step 6: query base period energy input
31
    # Step 7: query reporting period energy input
32
    # Step 8: query tariff data
33
    # Step 9: query associated sensors and points data
34
    # Step 10: construct the report
35
    ####################################################################################################################
36
    @staticmethod
37
    def on_get(req, resp):
38
        if 'API-KEY' not in req.headers or \
39
                not isinstance(req.headers['API-KEY'], str) or \
40
                len(str.strip(req.headers['API-KEY'])) == 0:
41
            access_control(req)
42
        else:
43
            api_key_control(req)
44
        print(req.params)
45
        tenant_id = req.params.get('tenantid')
46
        tenant_uuid = req.params.get('tenantuuid')
47
        period_type = req.params.get('periodtype')
48
        base_period_start_datetime_local = req.params.get('baseperiodstartdatetime')
49
        base_period_end_datetime_local = req.params.get('baseperiodenddatetime')
50
        reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime')
51
        reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime')
52
        language = req.params.get('language')
53
        quick_mode = req.params.get('quickmode')
54
55
        ################################################################################################################
56
        # Step 1: valid parameters
57
        ################################################################################################################
58
        if tenant_id is None and tenant_uuid is None:
59
            raise falcon.HTTPError(status=falcon.HTTP_400,
60
                                   title='API.BAD_REQUEST',
61
                                   description='API.INVALID_TENANT_ID')
62
63
        if tenant_id is not None:
64
            tenant_id = str.strip(tenant_id)
65
            if not tenant_id.isdigit() or int(tenant_id) <= 0:
66
                raise falcon.HTTPError(status=falcon.HTTP_400,
67
                                       title='API.BAD_REQUEST',
68
                                       description='API.INVALID_TENANT_ID')
69
70
        if tenant_uuid is not None:
71
            regex = re.compile(r'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
72
            match = regex.match(str.strip(tenant_uuid))
73
            if not bool(match):
74
                raise falcon.HTTPError(status=falcon.HTTP_400,
75
                                       title='API.BAD_REQUEST',
76
                                       description='API.INVALID_TENANT_UUID')
77
78
        if period_type is None:
79
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
80
                                   description='API.INVALID_PERIOD_TYPE')
81
        else:
82
            period_type = str.strip(period_type)
83
            if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']:
84
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
85
                                       description='API.INVALID_PERIOD_TYPE')
86
87
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
88
        if config.utc_offset[0] == '-':
89
            timezone_offset = -timezone_offset
90
91
        base_start_datetime_utc = None
92
        if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0:
93
            base_period_start_datetime_local = str.strip(base_period_start_datetime_local)
94
            try:
95
                base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S')
96
            except ValueError:
97
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
98
                                       description="API.INVALID_BASE_PERIOD_START_DATETIME")
99
            base_start_datetime_utc = \
100
                base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset)
101
            # nomalize the start datetime
102
            if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30:
103
                base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0)
104
            else:
105
                base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0)
106
107
        base_end_datetime_utc = None
108
        if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0:
109
            base_period_end_datetime_local = str.strip(base_period_end_datetime_local)
110
            try:
111
                base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S')
112
            except ValueError:
113
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
114
                                       description="API.INVALID_BASE_PERIOD_END_DATETIME")
115
            base_end_datetime_utc = \
116
                base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset)
117
118
        if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \
119
                base_start_datetime_utc >= base_end_datetime_utc:
120
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
121
                                   description='API.INVALID_BASE_PERIOD_END_DATETIME')
122
123
        if reporting_period_start_datetime_local is None:
124
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
125
                                   description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
126
        else:
127
            reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local)
128
            try:
129
                reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local,
130
                                                                 '%Y-%m-%dT%H:%M:%S')
131
            except ValueError:
132
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
133
                                       description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
134
            reporting_start_datetime_utc = \
135
                reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset)
136
            # nomalize the start datetime
137
            if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30:
138
                reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0)
139
            else:
140
                reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0)
141
142
        if reporting_period_end_datetime_local is None:
143
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
144
                                   description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
145
        else:
146
            reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local)
147
            try:
148
                reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local,
149
                                                               '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
150
                                             timedelta(minutes=timezone_offset)
151
            except ValueError:
152
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
153
                                       description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
154
155
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
156
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
157
                                   description='API.INVALID_REPORTING_PERIOD_END_DATETIME')
158
159
        # if turn quick mode on, do not return parameters data and excel file
160
        is_quick_mode = False
161
        if quick_mode is not None and \
162
                len(str.strip(quick_mode)) > 0 and \
163
                str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'):
164
            is_quick_mode = True
165
166
        trans = utilities.get_translation(language)
167
        trans.install()
168
        _ = trans.gettext
169
170
        ################################################################################################################
171
        # Step 2: query the tenant
172
        ################################################################################################################
173
        cnx_system = mysql.connector.connect(**config.myems_system_db)
174
        cursor_system = cnx_system.cursor()
175
176
        cnx_energy = mysql.connector.connect(**config.myems_energy_db)
177
        cursor_energy = cnx_energy.cursor()
178
179
        cnx_historical = mysql.connector.connect(**config.myems_historical_db)
180
        cursor_historical = cnx_historical.cursor()
181
182
        if tenant_id is not None:
183
            cursor_system.execute(" SELECT id, name, area, cost_center_id "
184
                                  " FROM tbl_tenants "
185
                                  " WHERE id = %s ", (tenant_id,))
186
            row_tenant = cursor_system.fetchone()
187
        elif tenant_uuid is not None:
188
            cursor_system.execute(" SELECT id, name, area, cost_center_id "
189
                                  " FROM tbl_tenants "
190
                                  " WHERE uuid = %s ", (tenant_uuid,))
191
            row_tenant = cursor_system.fetchone()
192
193
        if row_tenant is None:
0 ignored issues
show
The variable row_tenant does not seem to be defined for all execution paths.
Loading history...
194
            if cursor_system:
195
                cursor_system.close()
196
            if cnx_system:
197
                cnx_system.close()
198
199
            if cursor_energy:
200
                cursor_energy.close()
201
            if cnx_energy:
202
                cnx_energy.close()
203
204
            if cursor_historical:
205
                cursor_historical.close()
206
            if cnx_historical:
207
                cnx_historical.close()
208
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.TENANT_NOT_FOUND')
209
210
        tenant = dict()
211
        tenant['id'] = row_tenant[0]
212
        tenant['name'] = row_tenant[1]
213
        tenant['area'] = row_tenant[2]
214
        tenant['cost_center_id'] = row_tenant[3]
215
216
        ################################################################################################################
217
        # Step 3: query energy categories
218
        ################################################################################################################
219
        energy_category_set = set()
220
        # query energy categories in base period
221
        cursor_energy.execute(" SELECT DISTINCT(energy_category_id) "
222
                              " FROM tbl_tenant_input_category_hourly "
223
                              " WHERE tenant_id = %s "
224
                              "     AND start_datetime_utc >= %s "
225
                              "     AND start_datetime_utc < %s ",
226
                              (tenant['id'], base_start_datetime_utc, base_end_datetime_utc))
227
        rows_energy_categories = cursor_energy.fetchall()
228
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
229
            for row_energy_category in rows_energy_categories:
230
                energy_category_set.add(row_energy_category[0])
231
232
        # query energy categories in reporting period
233
        cursor_energy.execute(" SELECT DISTINCT(energy_category_id) "
234
                              " FROM tbl_tenant_input_category_hourly "
235
                              " WHERE tenant_id = %s "
236
                              "     AND start_datetime_utc >= %s "
237
                              "     AND start_datetime_utc < %s ",
238
                              (tenant['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
239
        rows_energy_categories = cursor_energy.fetchall()
240
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
241
            for row_energy_category in rows_energy_categories:
242
                energy_category_set.add(row_energy_category[0])
243
244
        # query all energy categories in base period and reporting period
245
        cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e "
246
                              " FROM tbl_energy_categories "
247
                              " ORDER BY id ", )
248
        rows_energy_categories = cursor_system.fetchall()
249
        if rows_energy_categories is None or len(rows_energy_categories) == 0:
250
            if cursor_system:
251
                cursor_system.close()
252
            if cnx_system:
253
                cnx_system.close()
254
255
            if cursor_energy:
256
                cursor_energy.close()
257
            if cnx_energy:
258
                cnx_energy.close()
259
260
            if cursor_historical:
261
                cursor_historical.close()
262
            if cnx_historical:
263
                cnx_historical.close()
264
            raise falcon.HTTPError(status=falcon.HTTP_404,
265
                                   title='API.NOT_FOUND',
266
                                   description='API.ENERGY_CATEGORY_NOT_FOUND')
267
        energy_category_dict = dict()
268
        for row_energy_category in rows_energy_categories:
269
            if row_energy_category[0] in energy_category_set:
270
                energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1],
271
                                                                "unit_of_measure": row_energy_category[2],
272
                                                                "kgce": row_energy_category[3],
273
                                                                "kgco2e": row_energy_category[4]}
274
275
        ################################################################################################################
276
        # Step 4: query associated sensors
277
        ################################################################################################################
278
        point_list = list()
279
        cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type  "
280
                              " FROM tbl_tenants t, tbl_sensors s, tbl_tenants_sensors ts, "
281
                              "      tbl_points p, tbl_sensors_points sp "
282
                              " WHERE t.id = %s AND t.id = ts.tenant_id AND ts.sensor_id = s.id "
283
                              "       AND s.id = sp.sensor_id AND sp.point_id = p.id "
284
                              " ORDER BY p.id ", (tenant['id'],))
285
        rows_points = cursor_system.fetchall()
286
        if rows_points is not None and len(rows_points) > 0:
287
            for row in rows_points:
288
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
289
290
        ################################################################################################################
291
        # Step 5: query associated points
292
        ################################################################################################################
293
        cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type  "
294
                              " FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p "
295
                              " WHERE t.id = %s AND t.id = tp.tenant_id AND tp.point_id = p.id "
296
                              " ORDER BY p.id ", (tenant['id'],))
297
        rows_points = cursor_system.fetchall()
298
        if rows_points is not None and len(rows_points) > 0:
299
            for row in rows_points:
300
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
301
302
        ################################################################################################################
303
        # Step 6: query base period energy input
304
        ################################################################################################################
305
        base = dict()
306
        if energy_category_set is not None and len(energy_category_set) > 0:
307
            for energy_category_id in energy_category_set:
308
                base[energy_category_id] = dict()
309
                base[energy_category_id]['timestamps'] = list()
310
                base[energy_category_id]['values'] = list()
311
                base[energy_category_id]['subtotal'] = Decimal(0.0)
312
                base[energy_category_id]['mean'] = None
313
                base[energy_category_id]['median'] = None
314
                base[energy_category_id]['minimum'] = None
315
                base[energy_category_id]['maximum'] = None
316
                base[energy_category_id]['stdev'] = None
317
                base[energy_category_id]['variance'] = None
318
319
                cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
320
                                      " FROM tbl_tenant_input_category_hourly "
321
                                      " WHERE tenant_id = %s "
322
                                      "     AND energy_category_id = %s "
323
                                      "     AND start_datetime_utc >= %s "
324
                                      "     AND start_datetime_utc < %s "
325
                                      " ORDER BY start_datetime_utc ",
326
                                      (tenant['id'],
327
                                       energy_category_id,
328
                                       base_start_datetime_utc,
329
                                       base_end_datetime_utc))
330
                rows_tenant_hourly = cursor_energy.fetchall()
331
332
                rows_tenant_periodically, \
333
                    base[energy_category_id]['mean'], \
334
                    base[energy_category_id]['median'], \
335
                    base[energy_category_id]['minimum'], \
336
                    base[energy_category_id]['maximum'], \
337
                    base[energy_category_id]['stdev'], \
338
                    base[energy_category_id]['variance'] = \
339
                    utilities.statistics_hourly_data_by_period(rows_tenant_hourly,
340
                                                               base_start_datetime_utc,
341
                                                               base_end_datetime_utc,
342
                                                               period_type)
343
344
                for row_tenant_periodically in rows_tenant_periodically:
345
                    current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \
346
                                             timedelta(minutes=timezone_offset)
347
                    if period_type == 'hourly':
348
                        current_datetime = current_datetime_local.isoformat()[0:19]
349
                    elif period_type == 'daily':
350
                        current_datetime = current_datetime_local.isoformat()[0:10]
351
                    elif period_type == 'weekly':
352
                        current_datetime = current_datetime_local.isoformat()[0:10]
353
                    elif period_type == 'monthly':
354
                        current_datetime = current_datetime_local.isoformat()[0:7]
355
                    elif period_type == 'yearly':
356
                        current_datetime = current_datetime_local.isoformat()[0:4]
357
358
                    actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1]
359
                    base[energy_category_id]['timestamps'].append(current_datetime)
0 ignored issues
show
The variable current_datetime does not seem to be defined for all execution paths.
Loading history...
360
                    base[energy_category_id]['values'].append(actual_value)
361
                    base[energy_category_id]['subtotal'] += actual_value
362
363
        ################################################################################################################
364
        # Step 7: query reporting period energy input
365
        ################################################################################################################
366
        reporting = dict()
367
        if energy_category_set is not None and len(energy_category_set) > 0:
368
            for energy_category_id in energy_category_set:
369
                reporting[energy_category_id] = dict()
370
                reporting[energy_category_id]['timestamps'] = list()
371
                reporting[energy_category_id]['values'] = list()
372
                reporting[energy_category_id]['subtotal'] = Decimal(0.0)
373
                reporting[energy_category_id]['mean'] = None
374
                reporting[energy_category_id]['median'] = None
375
                reporting[energy_category_id]['minimum'] = None
376
                reporting[energy_category_id]['maximum'] = None
377
                reporting[energy_category_id]['stdev'] = None
378
                reporting[energy_category_id]['variance'] = None
379
380
                cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
381
                                      " FROM tbl_tenant_input_category_hourly "
382
                                      " WHERE tenant_id = %s "
383
                                      "     AND energy_category_id = %s "
384
                                      "     AND start_datetime_utc >= %s "
385
                                      "     AND start_datetime_utc < %s "
386
                                      " ORDER BY start_datetime_utc ",
387
                                      (tenant['id'],
388
                                       energy_category_id,
389
                                       reporting_start_datetime_utc,
390
                                       reporting_end_datetime_utc))
391
                rows_tenant_hourly = cursor_energy.fetchall()
392
393
                rows_tenant_periodically, \
394
                    reporting[energy_category_id]['mean'], \
395
                    reporting[energy_category_id]['median'], \
396
                    reporting[energy_category_id]['minimum'], \
397
                    reporting[energy_category_id]['maximum'], \
398
                    reporting[energy_category_id]['stdev'], \
399
                    reporting[energy_category_id]['variance'] = \
400
                    utilities.statistics_hourly_data_by_period(rows_tenant_hourly,
401
                                                               reporting_start_datetime_utc,
402
                                                               reporting_end_datetime_utc,
403
                                                               period_type)
404
405
                for row_tenant_periodically in rows_tenant_periodically:
406
                    current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \
407
                                             timedelta(minutes=timezone_offset)
408
                    if period_type == 'hourly':
409
                        current_datetime = current_datetime_local.isoformat()[0:19]
410
                    elif period_type == 'daily':
411
                        current_datetime = current_datetime_local.isoformat()[0:10]
412
                    elif period_type == 'weekly':
413
                        current_datetime = current_datetime_local.isoformat()[0:10]
414
                    elif period_type == 'monthly':
415
                        current_datetime = current_datetime_local.isoformat()[0:7]
416
                    elif period_type == 'yearly':
417
                        current_datetime = current_datetime_local.isoformat()[0:4]
418
419
                    actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1]
420
                    reporting[energy_category_id]['timestamps'].append(current_datetime)
421
                    reporting[energy_category_id]['values'].append(actual_value)
422
                    reporting[energy_category_id]['subtotal'] += actual_value
423
424
        ################################################################################################################
425
        # Step 8: query tariff data
426
        ################################################################################################################
427
        parameters_data = dict()
428
        parameters_data['names'] = list()
429
        parameters_data['timestamps'] = list()
430
        parameters_data['values'] = list()
431
        if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0 \
432
                and not is_quick_mode:
433
            for energy_category_id in energy_category_set:
434
                energy_category_tariff_dict = utilities.get_energy_category_tariffs(tenant['cost_center_id'],
435
                                                                                    energy_category_id,
436
                                                                                    reporting_start_datetime_utc,
437
                                                                                    reporting_end_datetime_utc)
438
                tariff_timestamp_list = list()
439
                tariff_value_list = list()
440
                for k, v in energy_category_tariff_dict.items():
441
                    # convert k from utc to local
442
                    k = k + timedelta(minutes=timezone_offset)
443
                    tariff_timestamp_list.append(k.isoformat()[0:19])
444
                    tariff_value_list.append(v)
445
446
                parameters_data['names'].append(_('Tariff') + '-' + energy_category_dict[energy_category_id]['name'])
447
                parameters_data['timestamps'].append(tariff_timestamp_list)
448
                parameters_data['values'].append(tariff_value_list)
449
450
        ################################################################################################################
451
        # Step 9: query associated sensors and points data
452
        ################################################################################################################
453
        if not is_quick_mode:
454
            for point in point_list:
455
                point_values = []
456
                point_timestamps = []
457
                if point['object_type'] == 'ENERGY_VALUE':
458
                    query = (" SELECT utc_date_time, actual_value "
459
                             " FROM tbl_energy_value "
460
                             " WHERE point_id = %s "
461
                             "       AND utc_date_time BETWEEN %s AND %s "
462
                             " ORDER BY utc_date_time ")
463
                    cursor_historical.execute(query, (point['id'],
464
                                                      reporting_start_datetime_utc,
465
                                                      reporting_end_datetime_utc))
466
                    rows = cursor_historical.fetchall()
467
468
                    if rows is not None and len(rows) > 0:
469
                        for row in rows:
470
                            current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
471
                                                     timedelta(minutes=timezone_offset)
472
                            current_datetime = current_datetime_local.isoformat()[0:19]
473
                            point_timestamps.append(current_datetime)
474
                            point_values.append(row[1])
475
                elif point['object_type'] == 'ANALOG_VALUE':
476
                    query = (" SELECT utc_date_time, actual_value "
477
                             " FROM tbl_analog_value "
478
                             " WHERE point_id = %s "
479
                             "       AND utc_date_time BETWEEN %s AND %s "
480
                             " ORDER BY utc_date_time ")
481
                    cursor_historical.execute(query, (point['id'],
482
                                                      reporting_start_datetime_utc,
483
                                                      reporting_end_datetime_utc))
484
                    rows = cursor_historical.fetchall()
485
486
                    if rows is not None and len(rows) > 0:
487
                        for row in rows:
488
                            current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
489
                                                     timedelta(minutes=timezone_offset)
490
                            current_datetime = current_datetime_local.isoformat()[0:19]
491
                            point_timestamps.append(current_datetime)
492
                            point_values.append(row[1])
493
                elif point['object_type'] == 'DIGITAL_VALUE':
494
                    query = (" SELECT utc_date_time, actual_value "
495
                             " FROM tbl_digital_value "
496
                             " WHERE point_id = %s "
497
                             "       AND utc_date_time BETWEEN %s AND %s "
498
                             " ORDER BY utc_date_time ")
499
                    cursor_historical.execute(query, (point['id'],
500
                                                      reporting_start_datetime_utc,
501
                                                      reporting_end_datetime_utc))
502
                    rows = cursor_historical.fetchall()
503
504
                    if rows is not None and len(rows) > 0:
505
                        for row in rows:
506
                            current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
507
                                                     timedelta(minutes=timezone_offset)
508
                            current_datetime = current_datetime_local.isoformat()[0:19]
509
                            point_timestamps.append(current_datetime)
510
                            point_values.append(row[1])
511
512
                parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
513
                parameters_data['timestamps'].append(point_timestamps)
514
                parameters_data['values'].append(point_values)
515
516
        ################################################################################################################
517
        # Step 10: construct the report
518
        ################################################################################################################
519
        if cursor_system:
520
            cursor_system.close()
521
        if cnx_system:
522
            cnx_system.close()
523
524
        if cursor_energy:
525
            cursor_energy.close()
526
        if cnx_energy:
527
            cnx_energy.close()
528
529
        if cursor_historical:
530
            cursor_historical.close()
531
        if cnx_historical:
532
            cnx_historical.close()
533
534
        result = dict()
535
536
        result['tenant'] = dict()
537
        result['tenant']['name'] = tenant['name']
538
        result['tenant']['area'] = tenant['area']
539
540
        result['base_period'] = dict()
541
        result['base_period']['names'] = list()
542
        result['base_period']['units'] = list()
543
        result['base_period']['timestamps'] = list()
544
        result['base_period']['values'] = list()
545
        result['base_period']['subtotals'] = list()
546
        result['base_period']['means'] = list()
547
        result['base_period']['medians'] = list()
548
        result['base_period']['minimums'] = list()
549
        result['base_period']['maximums'] = list()
550
        result['base_period']['stdevs'] = list()
551
        result['base_period']['variances'] = list()
552
553
        if energy_category_set is not None and len(energy_category_set) > 0:
554
            for energy_category_id in energy_category_set:
555
                result['base_period']['names'].append(energy_category_dict[energy_category_id]['name'])
556
                result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
557
                result['base_period']['timestamps'].append(base[energy_category_id]['timestamps'])
558
                result['base_period']['values'].append(base[energy_category_id]['values'])
559
                result['base_period']['subtotals'].append(base[energy_category_id]['subtotal'])
560
                result['base_period']['means'].append(base[energy_category_id]['mean'])
561
                result['base_period']['medians'].append(base[energy_category_id]['median'])
562
                result['base_period']['minimums'].append(base[energy_category_id]['minimum'])
563
                result['base_period']['maximums'].append(base[energy_category_id]['maximum'])
564
                result['base_period']['stdevs'].append(base[energy_category_id]['stdev'])
565
                result['base_period']['variances'].append(base[energy_category_id]['variance'])
566
567
        result['reporting_period'] = dict()
568
        result['reporting_period']['names'] = list()
569
        result['reporting_period']['energy_category_ids'] = list()
570
        result['reporting_period']['units'] = list()
571
        result['reporting_period']['timestamps'] = list()
572
        result['reporting_period']['values'] = list()
573
        result['reporting_period']['rates'] = list()
574
        result['reporting_period']['subtotals'] = list()
575
        result['reporting_period']['means'] = list()
576
        result['reporting_period']['means_per_unit_area'] = list()
577
        result['reporting_period']['means_increment_rate'] = list()
578
        result['reporting_period']['medians'] = list()
579
        result['reporting_period']['medians_per_unit_area'] = list()
580
        result['reporting_period']['medians_increment_rate'] = list()
581
        result['reporting_period']['minimums'] = list()
582
        result['reporting_period']['minimums_per_unit_area'] = list()
583
        result['reporting_period']['minimums_increment_rate'] = list()
584
        result['reporting_period']['maximums'] = list()
585
        result['reporting_period']['maximums_per_unit_area'] = list()
586
        result['reporting_period']['maximums_increment_rate'] = list()
587
        result['reporting_period']['stdevs'] = list()
588
        result['reporting_period']['stdevs_per_unit_area'] = list()
589
        result['reporting_period']['stdevs_increment_rate'] = list()
590
        result['reporting_period']['variances'] = list()
591
        result['reporting_period']['variances_per_unit_area'] = list()
592
        result['reporting_period']['variances_increment_rate'] = list()
593
594
        if energy_category_set is not None and len(energy_category_set) > 0:
595
            for energy_category_id in energy_category_set:
596
                result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name'])
597
                result['reporting_period']['energy_category_ids'].append(energy_category_id)
598
                result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
599
                result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps'])
600
                result['reporting_period']['values'].append(reporting[energy_category_id]['values'])
601
                result['reporting_period']['subtotals'].append(reporting[energy_category_id]['subtotal'])
602
                result['reporting_period']['means'].append(reporting[energy_category_id]['mean'])
603
                result['reporting_period']['means_per_unit_area'].append(
604
                    reporting[energy_category_id]['mean'] / tenant['area']
605
                    if reporting[energy_category_id]['mean'] is not None and
606
                    tenant['area'] is not None and
607
                    tenant['area'] > Decimal(0.0)
608
                    else None)
609
                result['reporting_period']['means_increment_rate'].append(
610
                    (reporting[energy_category_id]['mean'] - base[energy_category_id]['mean']) /
611
                    base[energy_category_id]['mean'] if (base[energy_category_id]['mean'] is not None and
612
                                                         base[energy_category_id]['mean'] > Decimal(0.0))
613
                    else None)
614
                result['reporting_period']['medians'].append(reporting[energy_category_id]['median'])
615
                result['reporting_period']['medians_per_unit_area'].append(
616
                    reporting[energy_category_id]['median'] / tenant['area']
617
                    if reporting[energy_category_id]['median'] is not None and
618
                    tenant['area'] is not None and
619
                    tenant['area'] > Decimal(0.0)
620
                    else None)
621
                result['reporting_period']['medians_increment_rate'].append(
622
                    (reporting[energy_category_id]['median'] - base[energy_category_id]['median']) /
623
                    base[energy_category_id]['median'] if (base[energy_category_id]['median'] is not None and
624
                                                           base[energy_category_id]['median'] > Decimal(0.0))
625
                    else None)
626
                result['reporting_period']['minimums'].append(reporting[energy_category_id]['minimum'])
627
                result['reporting_period']['minimums_per_unit_area'].append(
628
                    reporting[energy_category_id]['minimum'] / tenant['area']
629
                    if reporting[energy_category_id]['minimum'] is not None and
630
                    tenant['area'] is not None and
631
                    tenant['area'] > Decimal(0.0)
632
                    else None)
633
                result['reporting_period']['minimums_increment_rate'].append(
634
                    (reporting[energy_category_id]['minimum'] - base[energy_category_id]['minimum']) /
635
                    base[energy_category_id]['minimum'] if (base[energy_category_id]['minimum'] is not None and
636
                                                            base[energy_category_id]['minimum'] > Decimal(0.0))
637
                    else None)
638
                result['reporting_period']['maximums'].append(reporting[energy_category_id]['maximum'])
639
                result['reporting_period']['maximums_per_unit_area'].append(
640
                    reporting[energy_category_id]['maximum'] / tenant['area']
641
                    if reporting[energy_category_id]['maximum'] is not None and
642
                    tenant['area'] is not None and
643
                    tenant['area'] > Decimal(0.0)
644
                    else None)
645
                result['reporting_period']['maximums_increment_rate'].append(
646
                    (reporting[energy_category_id]['maximum'] - base[energy_category_id]['maximum']) /
647
                    base[energy_category_id]['maximum'] if (base[energy_category_id]['maximum'] is not None and
648
                                                            base[energy_category_id]['maximum'] > Decimal(0.0))
649
                    else None)
650
                result['reporting_period']['stdevs'].append(reporting[energy_category_id]['stdev'])
651
                result['reporting_period']['stdevs_per_unit_area'].append(
652
                    reporting[energy_category_id]['stdev'] / tenant['area']
653
                    if reporting[energy_category_id]['stdev'] is not None and
654
                    tenant['area'] is not None and
655
                    tenant['area'] > Decimal(0.0)
656
                    else None)
657
                result['reporting_period']['stdevs_increment_rate'].append(
658
                    (reporting[energy_category_id]['stdev'] - base[energy_category_id]['stdev']) /
659
                    base[energy_category_id]['stdev'] if (base[energy_category_id]['stdev'] is not None and
660
                                                          base[energy_category_id]['stdev'] > Decimal(0.0))
661
                    else None)
662
                result['reporting_period']['variances'].append(reporting[energy_category_id]['variance'])
663
                result['reporting_period']['variances_per_unit_area'].append(
664
                    reporting[energy_category_id]['variance'] / tenant['area']
665
                    if reporting[energy_category_id]['variance'] is not None and
666
                    tenant['area'] is not None and
667
                    tenant['area'] > Decimal(0.0)
668
                    else None)
669
                result['reporting_period']['variances_increment_rate'].append(
670
                    (reporting[energy_category_id]['variance'] - base[energy_category_id]['variance']) /
671
                    base[energy_category_id]['variance'] if (base[energy_category_id]['variance'] is not None and
672
                                                             base[energy_category_id]['variance'] > Decimal(0.0))
673
                    else None)
674
675
                rate = list()
676
                for index, value in enumerate(reporting[energy_category_id]['values']):
677
                    if index < len(base[energy_category_id]['values']) \
678
                            and base[energy_category_id]['values'][index] != 0 and value != 0:
679
                        rate.append((value - base[energy_category_id]['values'][index])
680
                                    / base[energy_category_id]['values'][index])
681
                    else:
682
                        rate.append(None)
683
                result['reporting_period']['rates'].append(rate)
684
685
        result['parameters'] = {
686
            "names": parameters_data['names'],
687
            "timestamps": parameters_data['timestamps'],
688
            "values": parameters_data['values']
689
        }
690
        # export result to Excel file and then encode the file to base64 string
691
        if not is_quick_mode:
692
            result['excel_bytes_base64'] = excelexporters.tenantstatistics.export(result,
693
                                                                                  tenant['name'],
694
                                                                                  base_period_start_datetime_local,
695
                                                                                  base_period_end_datetime_local,
696
                                                                                  reporting_period_start_datetime_local,
697
                                                                                  reporting_period_end_datetime_local,
698
                                                                                  period_type,
699
                                                                                  language)
700
701
        resp.text = json.dumps(result)
702