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

metercost.Reporting.on_get()   F

Complexity

Conditions 72

Size

Total Lines 435
Code Lines 310

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 310
dl 0
loc 435
rs 0
c 0
b 0
f 0
cc 72
nop 2

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