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

virtualmeterenergy.Reporting.on_get()   F

Complexity

Conditions 44

Size

Total Lines 287
Code Lines 217

Duplication

Lines 287
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 217
dl 287
loc 287
rs 0
c 0
b 0
f 0
cc 44
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 virtualmeterenergy.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 View Code Duplication
class Reporting:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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 virtual meter and energy category
23
    # Step 3: query base period energy consumption
24
    # Step 4: query reporting period energy consumption
25
    # Step 5: query tariff data
26
    # Step 6: construct the report
27
    ####################################################################################################################
28
    @staticmethod
29
    def on_get(req, resp):
30
        print(req.params)
31
        virtual_meter_id = req.params.get('virtualmeterid')
32
        period_type = req.params.get('periodtype')
33
        base_period_begins_datetime = req.params.get('baseperiodstartdatetime')
34
        base_period_ends_datetime = req.params.get('baseperiodenddatetime')
35
        reporting_period_begins_datetime = req.params.get('reportingperiodstartdatetime')
36
        reporting_period_ends_datetime = req.params.get('reportingperiodenddatetime')
37
38
        ################################################################################################################
39
        # Step 1: valid parameters
40
        ################################################################################################################
41
        if virtual_meter_id is None:
42
            raise falcon.HTTPError(falcon.HTTP_400,
43
                                   title='API.BAD_REQUEST',
44
                                   description='API.INVALID_VIRTUAL_METER_ID')
45
        else:
46
            virtual_meter_id = str.strip(virtual_meter_id)
47
            if not virtual_meter_id.isdigit() or int(virtual_meter_id) <= 0:
48
                raise falcon.HTTPError(falcon.HTTP_400,
49
                                       title='API.BAD_REQUEST',
50
                                       description='API.INVALID_VIRTUAL_METER_ID')
51
52
        if period_type is None:
53
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
54
        else:
55
            period_type = str.strip(period_type)
56
            if period_type not in ['hourly', 'daily', 'monthly', 'yearly']:
57
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
58
59
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
60
        if config.utc_offset[0] == '-':
61
            timezone_offset = -timezone_offset
62
63
        base_start_datetime_utc = None
64
        if base_period_begins_datetime is not None and len(str.strip(base_period_begins_datetime)) > 0:
65
            base_period_begins_datetime = str.strip(base_period_begins_datetime)
66
            try:
67
                base_start_datetime_utc = datetime.strptime(base_period_begins_datetime, '%Y-%m-%dT%H:%M:%S')
68
            except ValueError:
69
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
70
                                       description="API.INVALID_BASE_PERIOD_BEGINS_DATETIME")
71
            base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \
72
                timedelta(minutes=timezone_offset)
73
74
        base_end_datetime_utc = None
75
        if base_period_ends_datetime is not None and len(str.strip(base_period_ends_datetime)) > 0:
76
            base_period_ends_datetime = str.strip(base_period_ends_datetime)
77
            try:
78
                base_end_datetime_utc = datetime.strptime(base_period_ends_datetime, '%Y-%m-%dT%H:%M:%S')
79
            except ValueError:
80
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
81
                                       description="API.INVALID_BASE_PERIOD_ENDS_DATETIME")
82
            base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \
83
                timedelta(minutes=timezone_offset)
84
85
        if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \
86
                base_start_datetime_utc >= base_end_datetime_utc:
87
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
88
                                   description='API.INVALID_BASE_PERIOD_ENDS_DATETIME')
89
90
        if reporting_period_begins_datetime is None:
91
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
92
                                   description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME")
93
        else:
94
            reporting_period_begins_datetime = str.strip(reporting_period_begins_datetime)
95
            try:
96
                reporting_start_datetime_utc = datetime.strptime(reporting_period_begins_datetime, '%Y-%m-%dT%H:%M:%S')
97
            except ValueError:
98
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
99
                                       description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME")
100
            reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \
101
                timedelta(minutes=timezone_offset)
102
103
        if reporting_period_ends_datetime is None:
104
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
105
                                   description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME")
106
        else:
107
            reporting_period_ends_datetime = str.strip(reporting_period_ends_datetime)
108
            try:
109
                reporting_end_datetime_utc = datetime.strptime(reporting_period_ends_datetime, '%Y-%m-%dT%H:%M:%S')
110
            except ValueError:
111
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
112
                                       description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME")
113
            reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \
114
                timedelta(minutes=timezone_offset)
115
116
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
117
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
118
                                   description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME')
119
120
        ################################################################################################################
121
        # Step 2: query the virtual meter and energy category
122
        ################################################################################################################
123
        cnx_system = mysql.connector.connect(**config.myems_system_db)
124
        cursor_system = cnx_system.cursor()
125
126
        cnx_energy = mysql.connector.connect(**config.myems_energy_db)
127
        cursor_energy = cnx_energy.cursor()
128
129
        cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, "
130
                              "        ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e "
131
                              " FROM tbl_virtual_meters m, tbl_energy_categories ec "
132
                              " WHERE m.id = %s AND m.energy_category_id = ec.id ", (virtual_meter_id,))
133
        row_virtual_meter = cursor_system.fetchone()
134
        if row_virtual_meter is None:
135
            if cursor_system:
136
                cursor_system.close()
137
            if cnx_system:
138
                cnx_system.disconnect()
139
140
            if cursor_energy:
141
                cursor_energy.close()
142
            if cnx_energy:
143
                cnx_energy.disconnect()
144
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.VIRTUAL_METER_NOT_FOUND')
145
146
        virtual_meter = dict()
147
        virtual_meter['id'] = row_virtual_meter[0]
148
        virtual_meter['name'] = row_virtual_meter[1]
149
        virtual_meter['cost_center_id'] = row_virtual_meter[2]
150
        virtual_meter['energy_category_id'] = row_virtual_meter[3]
151
        virtual_meter['energy_category_name'] = row_virtual_meter[4]
152
        virtual_meter['unit_of_measure'] = row_virtual_meter[5]
153
        virtual_meter['kgce'] = row_virtual_meter[6]
154
        virtual_meter['kgco2e'] = row_virtual_meter[7]
155
156
        ################################################################################################################
157
        # Step 3: query base period energy consumption
158
        ################################################################################################################
159
        query = (" SELECT start_datetime_utc, actual_value "
160
                 " FROM tbl_virtual_meter_hourly "
161
                 " WHERE virtual_meter_id = %s "
162
                 " AND start_datetime_utc >= %s "
163
                 " AND start_datetime_utc < %s "
164
                 " ORDER BY start_datetime_utc ")
165
        cursor_energy.execute(query, (virtual_meter['id'], base_start_datetime_utc, base_end_datetime_utc))
166
        rows_virtual_meter_hourly = cursor_energy.fetchall()
167
168
        rows_virtual_meter_periodically = \
169
            utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly,
170
                                                      base_start_datetime_utc,
171
                                                      base_end_datetime_utc,
172
                                                      period_type)
173
        base = dict()
174
        base['timestamps'] = list()
175
        base['values'] = list()
176
        base['total_in_category'] = Decimal(0.0)
177
        base['total_in_kgce'] = Decimal(0.0)
178
        base['total_in_kgco2e'] = Decimal(0.0)
179
180
        for row_virtual_meter_periodically in rows_virtual_meter_periodically:
181
            current_datetime_local = row_virtual_meter_periodically[0].replace(tzinfo=timezone.utc) + \
182
                                     timedelta(minutes=timezone_offset)
183
            if period_type == 'hourly':
184
                current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
185
            elif period_type == 'daily':
186
                current_datetime = current_datetime_local.strftime('%Y-%m-%d')
187
            elif period_type == 'monthly':
188
                current_datetime = current_datetime_local.strftime('%Y-%m')
189
            elif period_type == 'yearly':
190
                current_datetime = current_datetime_local.strftime('%Y')
191
192
            actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \
193
                else row_virtual_meter_periodically[1]
194
            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...
195
            base['values'].append(actual_value)
196
            base['total_in_category'] += actual_value
197
            base['total_in_kgce'] += actual_value * virtual_meter['kgce']
198
            base['total_in_kgco2e'] += actual_value * virtual_meter['kgco2e']
199
200
        ################################################################################################################
201
        # Step 3: query reporting period energy consumption
202
        ################################################################################################################
203
        query = (" SELECT start_datetime_utc, actual_value "
204
                 " FROM tbl_virtual_meter_hourly "
205
                 " WHERE virtual_meter_id = %s "
206
                 " AND start_datetime_utc >= %s "
207
                 " AND start_datetime_utc < %s "
208
                 " ORDER BY start_datetime_utc ")
209
        cursor_energy.execute(query, (virtual_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
210
        rows_virtual_meter_hourly = cursor_energy.fetchall()
211
212
        rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly,
213
                                                                                    reporting_start_datetime_utc,
214
                                                                                    reporting_end_datetime_utc,
215
                                                                                    period_type)
216
        reporting = dict()
217
        reporting['timestamps'] = list()
218
        reporting['values'] = list()
219
        reporting['total_in_category'] = Decimal(0.0)
220
        reporting['total_in_kgce'] = Decimal(0.0)
221
        reporting['total_in_kgco2e'] = Decimal(0.0)
222
223
        for row_virtual_meter_periodically in rows_virtual_meter_periodically:
224
            current_datetime_local = row_virtual_meter_periodically[0].replace(tzinfo=timezone.utc) + \
225
                timedelta(minutes=timezone_offset)
226
            if period_type == 'hourly':
227
                current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
228
            elif period_type == 'daily':
229
                current_datetime = current_datetime_local.strftime('%Y-%m-%d')
230
            elif period_type == 'monthly':
231
                current_datetime = current_datetime_local.strftime('%Y-%m')
232
            elif period_type == 'yearly':
233
                current_datetime = current_datetime_local.strftime('%Y')
234
235
            actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \
236
                else row_virtual_meter_periodically[1]
237
238
            reporting['timestamps'].append(current_datetime)
239
            reporting['values'].append(actual_value)
240
            reporting['total_in_category'] += actual_value
241
            reporting['total_in_kgce'] += actual_value * virtual_meter['kgce']
242
            reporting['total_in_kgco2e'] += actual_value * virtual_meter['kgco2e']
243
244
        ################################################################################################################
245
        # Step 5: query tariff data
246
        ################################################################################################################
247
        parameters_data = dict()
248
        parameters_data['names'] = list()
249
        parameters_data['timestamps'] = list()
250
        parameters_data['values'] = list()
251
252
        tariff_dict = utilities.get_energy_category_tariffs(virtual_meter['cost_center_id'],
253
                                                            virtual_meter['energy_category_id'],
254
                                                            reporting_start_datetime_utc,
255
                                                            reporting_end_datetime_utc)
256
        tariff_timestamp_list = list()
257
        tariff_value_list = list()
258
        for k, v in tariff_dict.items():
259
            # convert k from utc to local
260
            k = k + timedelta(minutes=timezone_offset)
261
            tariff_timestamp_list.append(k.isoformat()[0:19])
262
            tariff_value_list.append(v)
263
264
        parameters_data['names'].append('TARIFF-' + virtual_meter['energy_category_name'])
265
        parameters_data['timestamps'].append(tariff_timestamp_list)
266
        parameters_data['values'].append(tariff_value_list)
267
268
        ################################################################################################################
269
        # Step 6: construct the report
270
        ################################################################################################################
271
        if cursor_system:
272
            cursor_system.close()
273
        if cnx_system:
274
            cnx_system.disconnect()
275
276
        if cursor_energy:
277
            cursor_energy.close()
278
        if cnx_energy:
279
            cnx_energy.disconnect()
280
281
        result = {
282
            "virtual_meter": {
283
                "cost_center_id": virtual_meter['cost_center_id'],
284
                "energy_category_id": virtual_meter['energy_category_id'],
285
                "energy_category_name": virtual_meter['energy_category_name'],
286
                "unit_of_measure": virtual_meter['unit_of_measure'],
287
                "kgce": virtual_meter['kgce'],
288
                "kgco2e": virtual_meter['kgco2e'],
289
            },
290
            "base_period": {
291
                "total_in_category": base['total_in_category'],
292
                "total_in_kgce": base['total_in_kgce'],
293
                "total_in_kgco2e": base['total_in_kgco2e'],
294
                "timestamps": base['timestamps'],
295
                "values": base['values'],
296
            },
297
            "reporting_period": {
298
                "increment_rate":
299
                    (reporting['total_in_category'] - base['total_in_category'])/base['total_in_category']
300
                    if base['total_in_category'] > 0 else None,
301
                "total_in_category": reporting['total_in_category'],
302
                "total_in_kgce": reporting['total_in_kgce'],
303
                "total_in_kgco2e": reporting['total_in_kgco2e'],
304
                "timestamps": reporting['timestamps'],
305
                "values": reporting['values'],
306
            },
307
            "parameters": {
308
                "names": parameters_data['names'],
309
                "timestamps": parameters_data['timestamps'],
310
                "values": parameters_data['values']
311
            },
312
        }
313
314
        resp.body = json.dumps(result)
315