Passed
Push — master ( dc4cf6...d9c3b0 )
by Guangyu
02:47 queued 10s
created

reports.meterenergy.Reporting.on_get()   F

Complexity

Conditions 64

Size

Total Lines 373
Code Lines 275

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 64
eloc 275
nop 2
dl 0
loc 373
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like reports.meterenergy.Reporting.on_get() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
import utilities
7
from decimal import *
8
9
10
class Reporting:
11
    @staticmethod
12
    def __init__():
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    ####################################################################################################################
20
    # PROCEDURES
21
    # Step 1: valid parameters
22
    # Step 2: query the meter and energy category
23
    # Step 3: query associated points
24
    # Step 4: query base period energy consumption
25
    # Step 5: query reporting period energy consumption
26
    # Step 6: query tariff data
27
    # Step 7: query associated points data
28
    # Step 8: construct the report
29
    ####################################################################################################################
30
    @staticmethod
31
    def on_get(req, resp):
32
        print(req.params)
33
        meter_id = req.params.get('meterid')
34
        period_type = req.params.get('periodtype')
35
        base_period_start_datetime = req.params.get('baseperiodstartdatetime')
36
        base_period_end_datetime = req.params.get('baseperiodenddatetime')
37
        reporting_period_start_datetime = req.params.get('reportingperiodstartdatetime')
38
        reporting_period_end_datetime = req.params.get('reportingperiodenddatetime')
39
40
        ################################################################################################################
41
        # Step 1: valid parameters
42
        ################################################################################################################
43
        if meter_id is None:
44
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
45
        else:
46
            meter_id = str.strip(meter_id)
47
            if not meter_id.isdigit() or int(meter_id) <= 0:
48
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
49
50
        if period_type is None:
51
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
52
        else:
53
            period_type = str.strip(period_type)
54
            if period_type not in ['hourly', 'daily', 'monthly', 'yearly']:
55
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
56
57
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
58
        if config.utc_offset[0] == '-':
59
            timezone_offset = -timezone_offset
60
61
        base_start_datetime_utc = None
62
        if base_period_start_datetime is not None and len(str.strip(base_period_start_datetime)) > 0:
63
            base_period_start_datetime = str.strip(base_period_start_datetime)
64
            try:
65
                base_start_datetime_utc = datetime.strptime(base_period_start_datetime, '%Y-%m-%dT%H:%M:%S')
66
            except ValueError:
67
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
68
                                       description="API.INVALID_BASE_PERIOD_BEGINS_DATETIME")
69
            base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \
70
                timedelta(minutes=timezone_offset)
71
72
        base_end_datetime_utc = None
73
        if base_period_end_datetime is not None and len(str.strip(base_period_end_datetime)) > 0:
74
            base_period_end_datetime = str.strip(base_period_end_datetime)
75
            try:
76
                base_end_datetime_utc = datetime.strptime(base_period_end_datetime, '%Y-%m-%dT%H:%M:%S')
77
            except ValueError:
78
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
79
                                       description="API.INVALID_BASE_PERIOD_ENDS_DATETIME")
80
            base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \
81
                timedelta(minutes=timezone_offset)
82
83
        if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \
84
                base_start_datetime_utc >= base_end_datetime_utc:
85
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
86
                                   description='API.INVALID_BASE_PERIOD_ENDS_DATETIME')
87
88
        if reporting_period_start_datetime is None:
89
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
90
                                   description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME")
91
        else:
92
            reporting_period_start_datetime = str.strip(reporting_period_start_datetime)
93
            try:
94
                reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime, '%Y-%m-%dT%H:%M:%S')
95
            except ValueError:
96
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
97
                                       description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME")
98
            reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \
99
                timedelta(minutes=timezone_offset)
100
101
        if reporting_period_end_datetime is None:
102
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
103
                                   description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME")
104
        else:
105
            reporting_period_end_datetime = str.strip(reporting_period_end_datetime)
106
            try:
107
                reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime, '%Y-%m-%dT%H:%M:%S')
108
            except ValueError:
109
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
110
                                       description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME")
111
            reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \
112
                timedelta(minutes=timezone_offset)
113
114
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
115
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
116
                                   description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME')
117
118
        ################################################################################################################
119
        # Step 2: query the meter and energy category
120
        ################################################################################################################
121
        cnx_system = mysql.connector.connect(**config.myems_system_db)
122
        cursor_system = cnx_system.cursor()
123
124
        cnx_energy = mysql.connector.connect(**config.myems_energy_db)
125
        cursor_energy = cnx_energy.cursor()
126
127
        cnx_historical = mysql.connector.connect(**config.myems_historical_db)
128
        cursor_historical = cnx_historical.cursor()
129
130
        cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, "
131
                              "        ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e "
132
                              " FROM tbl_meters m, tbl_energy_categories ec "
133
                              " WHERE m.id = %s AND m.energy_category_id = ec.id ", (meter_id,))
134
        row_meter = cursor_system.fetchone()
135
        if row_meter is None:
136
            if cursor_system:
137
                cursor_system.close()
138
            if cnx_system:
139
                cnx_system.disconnect()
140
141
            if cursor_energy:
142
                cursor_energy.close()
143
            if cnx_energy:
144
                cnx_energy.disconnect()
145
146
            if cursor_historical:
147
                cursor_historical.close()
148
            if cnx_historical:
149
                cnx_historical.disconnect()
150
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND')
151
152
        meter = dict()
153
        meter['id'] = row_meter[0]
154
        meter['name'] = row_meter[1]
155
        meter['cost_center_id'] = row_meter[2]
156
        meter['energy_category_id'] = row_meter[3]
157
        meter['energy_category_name'] = row_meter[4]
158
        meter['unit_of_measure'] = row_meter[5]
159
        meter['kgce'] = row_meter[6]
160
        meter['kgco2e'] = row_meter[7]
161
162
        ################################################################################################################
163
        # Step 3: query associated points
164
        ################################################################################################################
165
        point_list = list()
166
        cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type  "
167
                              " FROM tbl_meters m, tbl_meters_points mp, tbl_points p "
168
                              " WHERE m.id = %s AND m.id = mp.meter_id AND mp.point_id = p.id "
169
                              " ORDER BY p.id ", (meter['id'],))
170
        rows_points = cursor_system.fetchall()
171
        if rows_points is not None and len(rows_points) > 0:
172
            for row in rows_points:
173
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
174
175
        ################################################################################################################
176
        # Step 4: query base period energy consumption
177
        ################################################################################################################
178
        cnx_energy = mysql.connector.connect(**config.myems_energy_db)
179
        cursor_energy = cnx_energy.cursor()
180
        query = (" SELECT start_datetime_utc, actual_value "
181
                 " FROM tbl_meter_hourly "
182
                 " WHERE meter_id = %s "
183
                 " AND start_datetime_utc >= %s "
184
                 " AND start_datetime_utc < %s "
185
                 " ORDER BY start_datetime_utc ")
186
        cursor_energy.execute(query, (meter['id'], base_start_datetime_utc, base_end_datetime_utc))
187
        rows_meter_hourly = cursor_energy.fetchall()
188
189
        rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly,
190
                                                                            base_start_datetime_utc,
191
                                                                            base_end_datetime_utc,
192
                                                                            period_type)
193
        base = dict()
194
        base['timestamps'] = list()
195
        base['values'] = list()
196
        base['total_in_category'] = Decimal(0.0)
197
        base['total_in_kgce'] = Decimal(0.0)
198
        base['total_in_kgco2e'] = Decimal(0.0)
199
200
        for row_meter_periodically in rows_meter_periodically:
201
            current_datetime_local = row_meter_periodically[0].replace(tzinfo=timezone.utc) + \
202
                                     timedelta(minutes=timezone_offset)
203
            if period_type == 'hourly':
204
                current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
205
            elif period_type == 'daily':
206
                current_datetime = current_datetime_local.strftime('%Y-%m-%d')
207
            elif period_type == 'monthly':
208
                current_datetime = current_datetime_local.strftime('%Y-%m')
209
            elif period_type == 'yearly':
210
                current_datetime = current_datetime_local.strftime('%Y')
211
212
            actual_value = Decimal(0.0) if row_meter_periodically[1] is None else row_meter_periodically[1]
213
            base['timestamps'].append(current_datetime)
0 ignored issues
show
introduced by
The variable current_datetime does not seem to be defined for all execution paths.
Loading history...
214
            base['values'].append(actual_value)
215
            base['total_in_category'] += actual_value
216
            base['total_in_kgce'] += actual_value * meter['kgce']
217
            base['total_in_kgco2e'] += actual_value * meter['kgco2e']
218
219
        ################################################################################################################
220
        # Step 5: query reporting period energy consumption
221
        ################################################################################################################
222
        query = (" SELECT start_datetime_utc, actual_value "
223
                 " FROM tbl_meter_hourly "
224
                 " WHERE meter_id = %s "
225
                 " AND start_datetime_utc >= %s "
226
                 " AND start_datetime_utc < %s "
227
                 " ORDER BY start_datetime_utc ")
228
        cursor_energy.execute(query, (meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
229
        rows_meter_hourly = cursor_energy.fetchall()
230
231
        rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly,
232
                                                                            reporting_start_datetime_utc,
233
                                                                            reporting_end_datetime_utc,
234
                                                                            period_type)
235
        reporting = dict()
236
        reporting['timestamps'] = list()
237
        reporting['values'] = list()
238
        reporting['total_in_category'] = Decimal(0.0)
239
        reporting['total_in_kgce'] = Decimal(0.0)
240
        reporting['total_in_kgco2e'] = Decimal(0.0)
241
242
        for row_meter_periodically in rows_meter_periodically:
243
            current_datetime_local = row_meter_periodically[0].replace(tzinfo=timezone.utc) + \
244
                timedelta(minutes=timezone_offset)
245
            if period_type == 'hourly':
246
                current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
247
            elif period_type == 'daily':
248
                current_datetime = current_datetime_local.strftime('%Y-%m-%d')
249
            elif period_type == 'monthly':
250
                current_datetime = current_datetime_local.strftime('%Y-%m')
251
            elif period_type == 'yearly':
252
                current_datetime = current_datetime_local.strftime('%Y')
253
254
            actual_value = Decimal(0.0) if row_meter_periodically[1] is None else row_meter_periodically[1]
255
256
            reporting['timestamps'].append(current_datetime)
257
            reporting['values'].append(actual_value)
258
            reporting['total_in_category'] += actual_value
259
            reporting['total_in_kgce'] += actual_value * meter['kgce']
260
            reporting['total_in_kgco2e'] += actual_value * meter['kgco2e']
261
262
        ################################################################################################################
263
        # Step 6: query tariff data
264
        ################################################################################################################
265
        parameters_data = dict()
266
        parameters_data['names'] = list()
267
        parameters_data['timestamps'] = list()
268
        parameters_data['values'] = list()
269
270
        tariff_dict = utilities.get_energy_category_tariffs(meter['cost_center_id'],
271
                                                            meter['energy_category_id'],
272
                                                            reporting_start_datetime_utc,
273
                                                            reporting_end_datetime_utc)
274
        print(tariff_dict)
275
        tariff_timestamp_list = list()
276
        tariff_value_list = list()
277
        for k, v in tariff_dict.items():
278
            # convert k from utc to local
279
            k = k + timedelta(minutes=timezone_offset)
280
            tariff_timestamp_list.append(k.isoformat()[0:19])
281
            tariff_value_list.append(v)
282
283
        parameters_data['names'].append('TARIFF-' + meter['energy_category_name'])
284
        parameters_data['timestamps'].append(tariff_timestamp_list)
285
        parameters_data['values'].append(tariff_value_list)
286
287
        ################################################################################################################
288
        # Step 7: query associated points data
289
        ################################################################################################################
290
        for point in point_list:
291
            point_values = []
292
            point_timestamps = []
293
            if point['object_type'] == 'ANALOG_VALUE':
294
                query = (" SELECT utc_date_time, actual_value "
295
                         " FROM tbl_analog_value "
296
                         " WHERE point_id = %s "
297
                         "       AND utc_date_time BETWEEN %s AND %s "
298
                         " ORDER BY utc_date_time ")
299
                cursor_historical.execute(query, (point['id'],
300
                                                  reporting_start_datetime_utc,
301
                                                  reporting_end_datetime_utc))
302
                rows = cursor_historical.fetchall()
303
304
                if rows is not None and len(rows) > 0:
305
                    for row in rows:
306
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
307
                                                 timedelta(minutes=timezone_offset)
308
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
309
                        point_timestamps.append(current_datetime)
310
                        point_values.append(row[1])
311
312
            elif point['object_type'] == 'ENERGY_VALUE':
313
                query = (" SELECT utc_date_time, actual_value "
314
                         " FROM tbl_energy_value "
315
                         " WHERE point_id = %s "
316
                         "       AND utc_date_time BETWEEN %s AND %s "
317
                         " ORDER BY utc_date_time ")
318
                cursor_historical.execute(query, (point['id'],
319
                                                  reporting_start_datetime_utc,
320
                                                  reporting_end_datetime_utc))
321
                rows = cursor_historical.fetchall()
322
323
                if rows is not None and len(rows) > 0:
324
                    for row in rows:
325
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
326
                                                 timedelta(minutes=timezone_offset)
327
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
328
                        point_timestamps.append(current_datetime)
329
                        point_values.append(row[1])
330
            elif point['object_type'] == 'DIGITAL_VALUE':
331
                query = (" SELECT utc_date_time, actual_value "
332
                         " FROM tbl_digital_value "
333
                         " WHERE point_id = %s "
334
                         "       AND utc_date_time BETWEEN %s AND %s ")
335
                cursor_historical.execute(query, (point['id'],
336
                                                  reporting_start_datetime_utc,
337
                                                  reporting_end_datetime_utc))
338
                rows = cursor_historical.fetchall()
339
340
                if rows is not None and len(rows) > 0:
341
                    for row in rows:
342
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
343
                                                 timedelta(minutes=timezone_offset)
344
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
345
                        point_timestamps.append(current_datetime)
346
                        point_values.append(row[1])
347
348
            parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
349
            parameters_data['timestamps'].append(point_timestamps)
350
            parameters_data['values'].append(point_values)
351
352
        ################################################################################################################
353
        # Step 8: construct the report
354
        ################################################################################################################
355
        if cursor_system:
356
            cursor_system.close()
357
        if cnx_system:
358
            cnx_system.disconnect()
359
360
        if cursor_energy:
361
            cursor_energy.close()
362
        if cnx_energy:
363
            cnx_energy.disconnect()
364
365
        if cursor_historical:
366
            cursor_historical.close()
367
        if cnx_historical:
368
            cnx_historical.disconnect()
369
        result = {
370
            "meter": {
371
                "cost_center_id": meter['cost_center_id'],
372
                "energy_category_id": meter['energy_category_id'],
373
                "energy_category_name": meter['energy_category_name'],
374
                "unit_of_measure": meter['unit_of_measure'],
375
                "kgce": meter['kgce'],
376
                "kgco2e": meter['kgco2e'],
377
            },
378
            "base_period": {
379
                "total_in_category": base['total_in_category'],
380
                "total_in_kgce": base['total_in_kgce'],
381
                "total_in_kgco2e": base['total_in_kgco2e'],
382
                "timestamps": base['timestamps'],
383
                "values": base['values']
384
            },
385
            "reporting_period": {
386
                "increment_rate":
387
                    (reporting['total_in_category'] - base['total_in_category'])/base['total_in_category']
388
                    if base['total_in_category'] > 0 else None,
389
                "total_in_category": reporting['total_in_category'],
390
                "total_in_kgce": reporting['total_in_kgce'],
391
                "total_in_kgco2e": reporting['total_in_kgco2e'],
392
                "timestamps": reporting['timestamps'],
393
                "values": reporting['values'],
394
            },
395
            "parameters": {
396
                "names": parameters_data['names'],
397
                "timestamps": parameters_data['timestamps'],
398
                "values": parameters_data['values']
399
            },
400
        }
401
402
        resp.body = json.dumps(result)
403