Issues (1656)

myems-api/reports/tenantload.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.tenantload
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]['sub_averages'] = list()
311
                base[energy_category_id]['sub_maximums'] = list()
312
                base[energy_category_id]['average'] = None
313
                base[energy_category_id]['maximum'] = None
314
                base[energy_category_id]['factor'] = None
315
316
                cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
317
                                      " FROM tbl_tenant_input_category_hourly "
318
                                      " WHERE tenant_id = %s "
319
                                      "     AND energy_category_id = %s "
320
                                      "     AND start_datetime_utc >= %s "
321
                                      "     AND start_datetime_utc < %s "
322
                                      " ORDER BY start_datetime_utc ",
323
                                      (tenant['id'],
324
                                       energy_category_id,
325
                                       base_start_datetime_utc,
326
                                       base_end_datetime_utc))
327
                rows_tenant_hourly = cursor_energy.fetchall()
328
329
                rows_tenant_periodically, \
330
                    base[energy_category_id]['average'], \
331
                    base[energy_category_id]['maximum'] = \
332
                    utilities.averaging_hourly_data_by_period(rows_tenant_hourly,
333
                                                              base_start_datetime_utc,
334
                                                              base_end_datetime_utc,
335
                                                              period_type)
336
                base[energy_category_id]['factor'] = \
337
                    (base[energy_category_id]['average'] / base[energy_category_id]['maximum']
338
                     if (base[energy_category_id]['average'] is not None and
339
                         base[energy_category_id]['maximum'] is not None and
340
                         base[energy_category_id]['maximum'] > Decimal(0.0))
341
                     else None)
342
343
                for row_tenant_periodically in rows_tenant_periodically:
344
                    current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \
345
                                             timedelta(minutes=timezone_offset)
346
                    if period_type == 'hourly':
347
                        current_datetime = current_datetime_local.isoformat()[0:19]
348
                    elif period_type == 'daily':
349
                        current_datetime = current_datetime_local.isoformat()[0:10]
350
                    elif period_type == 'weekly':
351
                        current_datetime = current_datetime_local.isoformat()[0:10]
352
                    elif period_type == 'monthly':
353
                        current_datetime = current_datetime_local.isoformat()[0:7]
354
                    elif period_type == 'yearly':
355
                        current_datetime = current_datetime_local.isoformat()[0:4]
356
357
                    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...
358
                    base[energy_category_id]['sub_averages'].append(row_tenant_periodically[1])
359
                    base[energy_category_id]['sub_maximums'].append(row_tenant_periodically[2])
360
361
        ################################################################################################################
362
        # Step 7: query reporting period energy input
363
        ################################################################################################################
364
        reporting = dict()
365
        if energy_category_set is not None and len(energy_category_set) > 0:
366
            for energy_category_id in energy_category_set:
367
                reporting[energy_category_id] = dict()
368
                reporting[energy_category_id]['timestamps'] = list()
369
                reporting[energy_category_id]['sub_averages'] = list()
370
                reporting[energy_category_id]['sub_maximums'] = list()
371
                reporting[energy_category_id]['average'] = None
372
                reporting[energy_category_id]['maximum'] = None
373
                reporting[energy_category_id]['factor'] = None
374
375
                cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
376
                                      " FROM tbl_tenant_input_category_hourly "
377
                                      " WHERE tenant_id = %s "
378
                                      "     AND energy_category_id = %s "
379
                                      "     AND start_datetime_utc >= %s "
380
                                      "     AND start_datetime_utc < %s "
381
                                      " ORDER BY start_datetime_utc ",
382
                                      (tenant['id'],
383
                                       energy_category_id,
384
                                       reporting_start_datetime_utc,
385
                                       reporting_end_datetime_utc))
386
                rows_tenant_hourly = cursor_energy.fetchall()
387
388
                rows_tenant_periodically, \
389
                    reporting[energy_category_id]['average'], \
390
                    reporting[energy_category_id]['maximum'] = \
391
                    utilities.averaging_hourly_data_by_period(rows_tenant_hourly,
392
                                                              reporting_start_datetime_utc,
393
                                                              reporting_end_datetime_utc,
394
                                                              period_type)
395
                reporting[energy_category_id]['factor'] = \
396
                    (reporting[energy_category_id]['average'] / reporting[energy_category_id]['maximum']
397
                     if (reporting[energy_category_id]['average'] is not None and
398
                         reporting[energy_category_id]['maximum'] is not None and
399
                         reporting[energy_category_id]['maximum'] > Decimal(0.0))
400
                     else None)
401
402
                for row_tenant_periodically in rows_tenant_periodically:
403
                    current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \
404
                                             timedelta(minutes=timezone_offset)
405
                    if period_type == 'hourly':
406
                        current_datetime = current_datetime_local.isoformat()[0:19]
407
                    elif period_type == 'daily':
408
                        current_datetime = current_datetime_local.isoformat()[0:10]
409
                    elif period_type == 'weekly':
410
                        current_datetime = current_datetime_local.isoformat()[0:10]
411
                    elif period_type == 'monthly':
412
                        current_datetime = current_datetime_local.isoformat()[0:7]
413
                    elif period_type == 'yearly':
414
                        current_datetime = current_datetime_local.isoformat()[0:4]
415
416
                    reporting[energy_category_id]['timestamps'].append(current_datetime)
417
                    reporting[energy_category_id]['sub_averages'].append(row_tenant_periodically[1])
418
                    reporting[energy_category_id]['sub_maximums'].append(row_tenant_periodically[2])
419
420
        ################################################################################################################
421
        # Step 8: query tariff data
422
        ################################################################################################################
423
        parameters_data = dict()
424
        parameters_data['names'] = list()
425
        parameters_data['timestamps'] = list()
426
        parameters_data['values'] = list()
427
        if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0 \
428
                and not is_quick_mode:
429
            for energy_category_id in energy_category_set:
430
                energy_category_tariff_dict = utilities.get_energy_category_tariffs(tenant['cost_center_id'],
431
                                                                                    energy_category_id,
432
                                                                                    reporting_start_datetime_utc,
433
                                                                                    reporting_end_datetime_utc)
434
                tariff_timestamp_list = list()
435
                tariff_value_list = list()
436
                for k, v in energy_category_tariff_dict.items():
437
                    # convert k from utc to local
438
                    k = k + timedelta(minutes=timezone_offset)
439
                    tariff_timestamp_list.append(k.isoformat()[0:19])
440
                    tariff_value_list.append(v)
441
442
                parameters_data['names'].append(_('Tariff') + '-' + energy_category_dict[energy_category_id]['name'])
443
                parameters_data['timestamps'].append(tariff_timestamp_list)
444
                parameters_data['values'].append(tariff_value_list)
445
446
        ################################################################################################################
447
        # Step 9: query associated sensors and points data
448
        ################################################################################################################
449
        if not is_quick_mode:
450
            for point in point_list:
451
                point_values = []
452
                point_timestamps = []
453
                if point['object_type'] == 'ENERGY_VALUE':
454
                    query = (" SELECT utc_date_time, actual_value "
455
                             " FROM tbl_energy_value "
456
                             " WHERE point_id = %s "
457
                             "       AND utc_date_time BETWEEN %s AND %s "
458
                             " ORDER BY utc_date_time ")
459
                    cursor_historical.execute(query, (point['id'],
460
                                                      reporting_start_datetime_utc,
461
                                                      reporting_end_datetime_utc))
462
                    rows = cursor_historical.fetchall()
463
464
                    if rows is not None and len(rows) > 0:
465
                        for row in rows:
466
                            current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
467
                                                     timedelta(minutes=timezone_offset)
468
                            current_datetime = current_datetime_local.isoformat()[0:19]
469
                            point_timestamps.append(current_datetime)
470
                            point_values.append(row[1])
471
                elif point['object_type'] == 'ANALOG_VALUE':
472
                    query = (" SELECT utc_date_time, actual_value "
473
                             " FROM tbl_analog_value "
474
                             " WHERE point_id = %s "
475
                             "       AND utc_date_time BETWEEN %s AND %s "
476
                             " ORDER BY utc_date_time ")
477
                    cursor_historical.execute(query, (point['id'],
478
                                                      reporting_start_datetime_utc,
479
                                                      reporting_end_datetime_utc))
480
                    rows = cursor_historical.fetchall()
481
482
                    if rows is not None and len(rows) > 0:
483
                        for row in rows:
484
                            current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
485
                                                     timedelta(minutes=timezone_offset)
486
                            current_datetime = current_datetime_local.isoformat()[0:19]
487
                            point_timestamps.append(current_datetime)
488
                            point_values.append(row[1])
489
                elif point['object_type'] == 'DIGITAL_VALUE':
490
                    query = (" SELECT utc_date_time, actual_value "
491
                             " FROM tbl_digital_value "
492
                             " WHERE point_id = %s "
493
                             "       AND utc_date_time BETWEEN %s AND %s "
494
                             " ORDER BY utc_date_time ")
495
                    cursor_historical.execute(query, (point['id'],
496
                                                      reporting_start_datetime_utc,
497
                                                      reporting_end_datetime_utc))
498
                    rows = cursor_historical.fetchall()
499
500
                    if rows is not None and len(rows) > 0:
501
                        for row in rows:
502
                            current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
503
                                                     timedelta(minutes=timezone_offset)
504
                            current_datetime = current_datetime_local.isoformat()[0:19]
505
                            point_timestamps.append(current_datetime)
506
                            point_values.append(row[1])
507
508
                parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
509
                parameters_data['timestamps'].append(point_timestamps)
510
                parameters_data['values'].append(point_values)
511
512
        ################################################################################################################
513
        # Step 10: construct the report
514
        ################################################################################################################
515
        if cursor_system:
516
            cursor_system.close()
517
        if cnx_system:
518
            cnx_system.close()
519
520
        if cursor_energy:
521
            cursor_energy.close()
522
        if cnx_energy:
523
            cnx_energy.close()
524
525
        if cursor_historical:
526
            cursor_historical.close()
527
        if cnx_historical:
528
            cnx_historical.close()
529
530
        result = dict()
531
532
        result['tenant'] = dict()
533
        result['tenant']['name'] = tenant['name']
534
        result['tenant']['area'] = tenant['area']
535
536
        result['base_period'] = dict()
537
        result['base_period']['names'] = list()
538
        result['base_period']['units'] = list()
539
        result['base_period']['timestamps'] = list()
540
        result['base_period']['sub_averages'] = list()
541
        result['base_period']['sub_maximums'] = list()
542
        result['base_period']['averages'] = list()
543
        result['base_period']['maximums'] = list()
544
        result['base_period']['factors'] = list()
545
        if energy_category_set is not None and len(energy_category_set) > 0:
546
            for energy_category_id in energy_category_set:
547
                result['base_period']['names'].append(energy_category_dict[energy_category_id]['name'])
548
                result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
549
                result['base_period']['timestamps'].append(base[energy_category_id]['timestamps'])
550
                result['base_period']['sub_averages'].append(base[energy_category_id]['sub_averages'])
551
                result['base_period']['sub_maximums'].append(base[energy_category_id]['sub_maximums'])
552
                result['base_period']['averages'].append(base[energy_category_id]['average'])
553
                result['base_period']['maximums'].append(base[energy_category_id]['maximum'])
554
                result['base_period']['factors'].append(base[energy_category_id]['factor'])
555
556
        result['reporting_period'] = dict()
557
        result['reporting_period']['names'] = list()
558
        result['reporting_period']['energy_category_ids'] = list()
559
        result['reporting_period']['units'] = list()
560
        result['reporting_period']['timestamps'] = list()
561
        result['reporting_period']['sub_averages'] = list()
562
        result['reporting_period']['sub_maximums'] = list()
563
        result['reporting_period']['rates_of_sub_maximums'] = list()
564
        result['reporting_period']['averages'] = list()
565
        result['reporting_period']['averages_per_unit_area'] = list()
566
        result['reporting_period']['averages_increment_rate'] = list()
567
        result['reporting_period']['maximums'] = list()
568
        result['reporting_period']['maximums_per_unit_area'] = list()
569
        result['reporting_period']['maximums_increment_rate'] = list()
570
        result['reporting_period']['factors'] = list()
571
        result['reporting_period']['factors_increment_rate'] = list()
572
573
        if energy_category_set is not None and len(energy_category_set) > 0:
574
            for energy_category_id in energy_category_set:
575
                result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name'])
576
                result['reporting_period']['energy_category_ids'].append(energy_category_id)
577
                result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
578
                result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps'])
579
                result['reporting_period']['sub_averages'].append(reporting[energy_category_id]['sub_averages'])
580
                result['reporting_period']['sub_maximums'].append(reporting[energy_category_id]['sub_maximums'])
581
                result['reporting_period']['averages'].append(reporting[energy_category_id]['average'])
582
                result['reporting_period']['averages_per_unit_area'].append(
583
                    reporting[energy_category_id]['average'] / tenant['area']
584
                    if reporting[energy_category_id]['average'] is not None and
585
                    tenant['area'] is not None and
586
                    tenant['area'] > Decimal(0.0)
587
                    else None)
588
                result['reporting_period']['averages_increment_rate'].append(
589
                    (reporting[energy_category_id]['average'] - base[energy_category_id]['average']) /
590
                    base[energy_category_id]['average'] if (reporting[energy_category_id]['average'] is not None and
591
                                                            base[energy_category_id]['average'] is not None and
592
                                                            base[energy_category_id]['average'] > Decimal(0.0))
593
                    else None)
594
                result['reporting_period']['maximums'].append(reporting[energy_category_id]['maximum'])
595
                result['reporting_period']['maximums_increment_rate'].append(
596
                    (reporting[energy_category_id]['maximum'] - base[energy_category_id]['maximum']) /
597
                    base[energy_category_id]['maximum'] if (reporting[energy_category_id]['maximum'] is not None and
598
                                                            base[energy_category_id]['maximum'] is not None and
599
                                                            base[energy_category_id]['maximum'] > Decimal(0.0))
600
                    else None)
601
                result['reporting_period']['maximums_per_unit_area'].append(
602
                    reporting[energy_category_id]['maximum'] / tenant['area']
603
                    if reporting[energy_category_id]['maximum'] is not None and
604
                    tenant['area'] is not None and
605
                    tenant['area'] > Decimal(0.0)
606
                    else None)
607
                result['reporting_period']['factors'].append(reporting[energy_category_id]['factor'])
608
                result['reporting_period']['factors_increment_rate'].append(
609
                    (reporting[energy_category_id]['factor'] - base[energy_category_id]['factor']) /
610
                    base[energy_category_id]['factor'] if (reporting[energy_category_id]['factor'] is not None and
611
                                                           base[energy_category_id]['factor'] is not None and
612
                                                           base[energy_category_id]['factor'] > Decimal(0.0))
613
                    else None)
614
615
                rate = list()
616
                for index, value in enumerate(reporting[energy_category_id]['sub_maximums']):
617
                    if index < len(base[energy_category_id]['sub_maximums']) \
618
                            and base[energy_category_id]['sub_maximums'][index] != 0 and value != 0\
619
                            and base[energy_category_id]['sub_maximums'][index] is not None and value is not None:
620
                        rate.append((value - base[energy_category_id]['sub_maximums'][index])
621
                                    / base[energy_category_id]['sub_maximums'][index])
622
                    else:
623
                        rate.append(None)
624
                result['reporting_period']['rates_of_sub_maximums'].append(rate)
625
626
        result['parameters'] = {
627
            "names": parameters_data['names'],
628
            "timestamps": parameters_data['timestamps'],
629
            "values": parameters_data['values']
630
        }
631
632
        # export result to Excel file and then encode the file to base64 string
633
        if not is_quick_mode:
634
            result['excel_bytes_base64'] = excelexporters.tenantload.export(result,
635
                                                                            tenant['name'],
636
                                                                            base_period_start_datetime_local,
637
                                                                            base_period_end_datetime_local,
638
                                                                            reporting_period_start_datetime_local,
639
                                                                            reporting_period_end_datetime_local,
640
                                                                            period_type,
641
                                                                            language)
642
643
        resp.text = json.dumps(result)
644