Issues (1656)

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