Passed
Push — master ( 59898a...bb64ab )
by Guangyu
02:43 queued 10s
created

reports.metersubmetersbalance   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 327
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 218
dl 0
loc 327
rs 8.64
c 0
b 0
f 0
wmc 47

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Reporting.on_options() 0 3 1
A Reporting.__init__() 0 3 1
F Reporting.on_get() 0 297 45

How to fix   Complexity   

Complexity

Complex classes like reports.metersubmetersbalance 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
from core import utilities
7
from decimal import Decimal
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 master meter and energy category
23
    # Step 3: query associated submeters
24
    # Step 4: query reporting period master meter energy consumption
25
    # Step 5: query reporting period submeters energy consumption
26
    # Step 6: calculate reporting period difference between master meter and submeters
27
    # Step 7: query submeter values as parameter 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
        reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime')
36
        reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime')
37
38
        ################################################################################################################
39
        # Step 1: valid parameters
40
        ################################################################################################################
41
        if meter_id is None:
42
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
43
        else:
44
            meter_id = str.strip(meter_id)
45
            if not meter_id.isdigit() or int(meter_id) <= 0:
46
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
47
48
        if period_type is None:
49
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
50
        else:
51
            period_type = str.strip(period_type)
52
            if period_type not in ['hourly', 'daily', 'monthly', 'yearly']:
53
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
54
55
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
56
        if config.utc_offset[0] == '-':
57
            timezone_offset = -timezone_offset
58
59
        if reporting_period_start_datetime_local is None:
60
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
61
                                   description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
62
        else:
63
            reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local)
64
            try:
65
                reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local,
66
                                                                 '%Y-%m-%dT%H:%M:%S')
67
            except ValueError:
68
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
69
                                       description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
70
            reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \
71
                timedelta(minutes=timezone_offset)
72
73
        if reporting_period_end_datetime_local is None:
74
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
75
                                   description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
76
        else:
77
            reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local)
78
            try:
79
                reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local,
80
                                                               '%Y-%m-%dT%H:%M:%S')
81
            except ValueError:
82
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
83
                                       description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
84
            reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \
85
                timedelta(minutes=timezone_offset)
86
87
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
88
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
89
                                   description='API.INVALID_REPORTING_PERIOD_END_DATETIME')
90
91
        ################################################################################################################
92
        # Step 2: query the meter and energy category
93
        ################################################################################################################
94
        cnx_system = mysql.connector.connect(**config.myems_system_db)
95
        cursor_system = cnx_system.cursor()
96
97
        cnx_energy = mysql.connector.connect(**config.myems_energy_db)
98
        cursor_energy = cnx_energy.cursor()
99
100
        cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, "
101
                              "        ec.name, ec.unit_of_measure "
102
                              " FROM tbl_meters m, tbl_energy_categories ec "
103
                              " WHERE m.id = %s AND m.energy_category_id = ec.id ", (meter_id,))
104
        row_meter = cursor_system.fetchone()
105
        if row_meter is None:
106
            if cursor_system:
107
                cursor_system.close()
108
            if cnx_system:
109
                cnx_system.disconnect()
110
111
            if cursor_energy:
112
                cursor_energy.close()
113
            if cnx_energy:
114
                cnx_energy.disconnect()
115
116
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND')
117
118
        master_meter = dict()
119
        master_meter['id'] = row_meter[0]
120
        master_meter['name'] = row_meter[1]
121
        master_meter['cost_center_id'] = row_meter[2]
122
        master_meter['energy_category_id'] = row_meter[3]
123
        master_meter['energy_category_name'] = row_meter[4]
124
        master_meter['unit_of_measure'] = row_meter[5]
125
126
        ################################################################################################################
127
        # Step 3: query associated submeters
128
        ################################################################################################################
129
        submeter_list = list()
130
        submeter_id_set = set()
131
132
        cursor_system.execute(" SELECT id, name, energy_category_id "
133
                              " FROM tbl_meters "
134
                              " WHERE master_meter_id = %s ",
135
                              (master_meter['id'],))
136
        rows_meters = cursor_system.fetchall()
137
138
        if rows_meters is not None and len(rows_meters) > 0:
139
            for row in rows_meters:
140
                submeter_list.append({"id": row[0],
141
                                      "name": row[1],
142
                                      "energy_category_id": row[2]})
143
                submeter_id_set.add(row[0])
144
145
        ################################################################################################################
146
        # Step 4: query reporting period master meter energy consumption
147
        ################################################################################################################
148
        reporting = dict()
149
        reporting['master_meter_total_in_category'] = Decimal(0.0)
150
        reporting['submeters_total_in_category'] = Decimal(0.0)
151
        reporting['total_difference_in_category'] = Decimal(0.0)
152
        reporting['percentage_difference'] = Decimal(0.0)
153
        reporting['timestamps'] = list()
154
        reporting['master_meter_values'] = list()
155
        reporting['submeters_values'] = list()
156
        reporting['difference_values'] = list()
157
158
        parameters_data = dict()
159
        parameters_data['names'] = list()
160
        parameters_data['timestamps'] = list()
161
        parameters_data['values'] = list()
162
163
        query = (" SELECT start_datetime_utc, actual_value "
164
                 " FROM tbl_meter_hourly "
165
                 " WHERE meter_id = %s "
166
                 " AND start_datetime_utc >= %s "
167
                 " AND start_datetime_utc < %s "
168
                 " ORDER BY start_datetime_utc ")
169
        cursor_energy.execute(query, (master_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
170
        rows_meter_hourly = cursor_energy.fetchall()
171
172
        rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly,
173
                                                                            reporting_start_datetime_utc,
174
                                                                            reporting_end_datetime_utc,
175
                                                                            period_type)
176
177
        for row_meter_periodically in rows_meter_periodically:
178
            current_datetime_local = row_meter_periodically[0].replace(tzinfo=timezone.utc) + \
179
                                     timedelta(minutes=timezone_offset)
180
            if period_type == 'hourly':
181
                current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
182
            elif period_type == 'daily':
183
                current_datetime = current_datetime_local.strftime('%Y-%m-%d')
184
            elif period_type == 'monthly':
185
                current_datetime = current_datetime_local.strftime('%Y-%m')
186
            elif period_type == 'yearly':
187
                current_datetime = current_datetime_local.strftime('%Y')
188
189
            actual_value = Decimal(0.0) if row_meter_periodically[1] is None else row_meter_periodically[1]
190
191
            reporting['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...
192
            reporting['master_meter_values'].append(actual_value)
193
            reporting['master_meter_total_in_category'] += actual_value
194
195
        # add master meter values to parameter data
196
        parameters_data['names'].append(master_meter['name'])
197
        parameters_data['timestamps'].append(reporting['timestamps'])
198
        parameters_data['values'].append(reporting['master_meter_values'])
199
200
        ################################################################################################################
201
        # Step 5: query reporting period submeters energy consumption
202
        ################################################################################################################
203
        query = (" SELECT start_datetime_utc, SUM(actual_value) "
204
                 " FROM tbl_meter_hourly "
205
                 " WHERE meter_id IN ( " + ', '.join(map(str, submeter_id_set)) + ") "
206
                 " AND start_datetime_utc >= %s "
207
                 " AND start_datetime_utc < %s "
208
                 " GROUP BY start_datetime_utc "
209
                 " ORDER BY start_datetime_utc ")
210
        cursor_energy.execute(query, (reporting_start_datetime_utc, reporting_end_datetime_utc))
211
        rows_submeters_hourly = cursor_energy.fetchall()
212
213
        rows_submeters_periodically = utilities.aggregate_hourly_data_by_period(rows_submeters_hourly,
214
                                                                                reporting_start_datetime_utc,
215
                                                                                reporting_end_datetime_utc,
216
                                                                                period_type)
217
218
        for row_submeters_periodically in rows_submeters_periodically:
219
            current_datetime_local = row_submeters_periodically[0].replace(tzinfo=timezone.utc) + \
220
                                     timedelta(minutes=timezone_offset)
221
            if period_type == 'hourly':
222
                current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
223
            elif period_type == 'daily':
224
                current_datetime = current_datetime_local.strftime('%Y-%m-%d')
225
            elif period_type == 'monthly':
226
                current_datetime = current_datetime_local.strftime('%Y-%m')
227
            elif period_type == 'yearly':
228
                current_datetime = current_datetime_local.strftime('%Y')
229
230
            actual_value = Decimal(0.0) if row_submeters_periodically[1] is None else row_submeters_periodically[1]
231
232
            reporting['submeters_values'].append(actual_value)
233
            reporting['submeters_total_in_category'] += actual_value
234
235
        ################################################################################################################
236
        # Step 6: calculate reporting period difference between master meter and submeters
237
        ################################################################################################################
238
        for i in range(len(reporting['timestamps'])):
239
            reporting['difference_values'].append(reporting['master_meter_values'][i] -
240
                                                  reporting['submeters_values'][i])
241
242
        reporting['total_difference_in_category'] = \
243
            reporting['master_meter_total_in_category'] - reporting['submeters_total_in_category']
244
245
        reporting['percentage_difference'] = \
246
            reporting['total_difference_in_category'] / reporting['master_meter_total_in_category'] \
247
            if abs(reporting['master_meter_total_in_category']) > Decimal(0.0) else Decimal(0.0)
248
249
        ################################################################################################################
250
        # Step 7: query submeter values as parameter data
251
        ################################################################################################################
252
        for submeter in submeter_list:
253
            submeter_timestamps = list()
254
            submeter_values = list()
255
256
            query = (" SELECT start_datetime_utc, actual_value "
257
                     " FROM tbl_meter_hourly "
258
                     " WHERE meter_id = %s "
259
                     " AND start_datetime_utc >= %s "
260
                     " AND start_datetime_utc < %s "
261
                     " ORDER BY start_datetime_utc ")
262
            cursor_energy.execute(query, (submeter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
263
            rows_meter_hourly = cursor_energy.fetchall()
264
265
            rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly,
266
                                                                                reporting_start_datetime_utc,
267
                                                                                reporting_end_datetime_utc,
268
                                                                                period_type)
269
270
            for row_meter_periodically in rows_meter_periodically:
271
                current_datetime_local = row_meter_periodically[0].replace(tzinfo=timezone.utc) + \
272
                                         timedelta(minutes=timezone_offset)
273
                if period_type == 'hourly':
274
                    current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
275
                elif period_type == 'daily':
276
                    current_datetime = current_datetime_local.strftime('%Y-%m-%d')
277
                elif period_type == 'monthly':
278
                    current_datetime = current_datetime_local.strftime('%Y-%m')
279
                elif period_type == 'yearly':
280
                    current_datetime = current_datetime_local.strftime('%Y')
281
282
                actual_value = Decimal(0.0) if row_meter_periodically[1] is None else row_meter_periodically[1]
283
284
                submeter_timestamps.append(current_datetime)
285
                submeter_values.append(actual_value)
286
287
            parameters_data['names'].append(submeter['name'])
288
            parameters_data['timestamps'].append(submeter_timestamps)
289
            parameters_data['values'].append(submeter_values)
290
291
        ################################################################################################################
292
        # Step 8: construct the report
293
        ################################################################################################################
294
        if cursor_system:
295
            cursor_system.close()
296
        if cnx_system:
297
            cnx_system.disconnect()
298
299
        if cursor_energy:
300
            cursor_energy.close()
301
        if cnx_energy:
302
            cnx_energy.disconnect()
303
304
        result = {
305
            "meter": {
306
                "cost_center_id": master_meter['cost_center_id'],
307
                "energy_category_id": master_meter['energy_category_id'],
308
                "energy_category_name": master_meter['energy_category_name'],
309
                "unit_of_measure": master_meter['unit_of_measure'],
310
            },
311
            "reporting_period": {
312
                "master_meter_consumption_in_category": reporting['master_meter_total_in_category'],
313
                "submeters_consumption_in_category": reporting['submeters_total_in_category'],
314
                "difference_in_category": reporting['total_difference_in_category'],
315
                "percentage_difference": reporting['percentage_difference'],
316
                "timestamps": reporting['timestamps'],
317
                "difference_values": reporting['difference_values'],
318
            },
319
            "parameters": {
320
                "names": parameters_data['names'],
321
                "timestamps": parameters_data['timestamps'],
322
                "values": parameters_data['values']
323
            },
324
        }
325
326
        resp.body = json.dumps(result)
327