Passed
Push — master ( 51918a...fb64d8 )
by Guangyu
07:51 queued 12s
created

reports.metersubmetersbalance   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 371
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 63
eloc 254
dl 0
loc 371
rs 3.36
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Reporting.on_options() 0 3 1
A Reporting.__init__() 0 4 1
F Reporting.on_get() 0 337 61

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 re
2
3
import falcon
4
import simplejson as json
5
import mysql.connector
6
import config
7
from datetime import datetime, timedelta, timezone
8
from core import utilities
9
from decimal import Decimal
10
import excelexporters.metersubmetersbalance
11
12
13
class Reporting:
14
    @staticmethod
15
    def __init__():
16
        """"Initializes Reporting"""
17
        pass
18
19
    @staticmethod
20
    def on_options(req, resp):
21
        resp.status = falcon.HTTP_200
22
23
    ####################################################################################################################
24
    # PROCEDURES
25
    # Step 1: valid parameters
26
    # Step 2: query the master meter and energy category
27
    # Step 3: query associated submeters
28
    # Step 4: query reporting period master meter energy consumption
29
    # Step 5: query reporting period submeters energy consumption
30
    # Step 6: calculate reporting period difference between master meter and submeters
31
    # Step 7: query submeter values as parameter data
32
    # Step 8: construct the report
33
    ####################################################################################################################
34
    @staticmethod
35
    def on_get(req, resp):
36
        print(req.params)
37
        meter_id = req.params.get('meterid')
38
        meter_uuid = req.params.get('meteruuid')
39
        period_type = req.params.get('periodtype')
40
        reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime')
41
        reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime')
42
43
        ################################################################################################################
44
        # Step 1: valid parameters
45
        ################################################################################################################
46
        if meter_id is None and meter_uuid is None:
47
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
48
49
        if meter_id is not None:
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, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
53
54
        if meter_uuid is not None:
55
            meter_uuid = str.strip(meter_uuid)
56
            regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
57
            match = regex.match(meter_uuid)
58
            if not bool(match):
59
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_UUID')
60
61
        if period_type is None:
62
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
63
        else:
64
            period_type = str.strip(period_type)
65
            if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']:
66
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
67
68
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
69
        if config.utc_offset[0] == '-':
70
            timezone_offset = -timezone_offset
71
72
        if reporting_period_start_datetime_local is None:
73
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
74
                                   description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
75
        else:
76
            reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local)
77
            try:
78
                reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local,
79
                                                                 '%Y-%m-%dT%H:%M:%S')
80
            except ValueError:
81
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
82
                                       description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
83
            reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \
84
                timedelta(minutes=timezone_offset)
85
86
        if reporting_period_end_datetime_local is None:
87
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
88
                                   description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
89
        else:
90
            reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local)
91
            try:
92
                reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local,
93
                                                               '%Y-%m-%dT%H:%M:%S')
94
            except ValueError:
95
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
96
                                       description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
97
            reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \
98
                timedelta(minutes=timezone_offset)
99
100
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
101
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
102
                                   description='API.INVALID_REPORTING_PERIOD_END_DATETIME')
103
104
        ################################################################################################################
105
        # Step 2: query the meter and energy category
106
        ################################################################################################################
107
        cnx_system = mysql.connector.connect(**config.myems_system_db)
108
        cursor_system = cnx_system.cursor()
109
110
        cnx_energy = mysql.connector.connect(**config.myems_energy_db)
111
        cursor_energy = cnx_energy.cursor()
112
113
        if meter_id is not None:
114
            cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, "
115
                                  "        ec.name, ec.unit_of_measure "
116
                                  " FROM tbl_meters m, tbl_energy_categories ec "
117
                                  " WHERE m.id = %s AND m.energy_category_id = ec.id ", (meter_id,))
118
            row_meter = cursor_system.fetchone()
119
        elif meter_uuid is not None:
120
            cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, "
121
                                  "        ec.name, ec.unit_of_measure "
122
                                  " FROM tbl_meters m, tbl_energy_categories ec "
123
                                  " WHERE m.uuid = %s AND m.energy_category_id = ec.id ", (meter_uuid,))
124
            row_meter = cursor_system.fetchone()
125
        if row_meter is None:
0 ignored issues
show
introduced by
The variable row_meter does not seem to be defined for all execution paths.
Loading history...
126
            if cursor_system:
127
                cursor_system.close()
128
            if cnx_system:
129
                cnx_system.disconnect()
130
131
            if cursor_energy:
132
                cursor_energy.close()
133
            if cnx_energy:
134
                cnx_energy.disconnect()
135
136
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND')
137
        if meter_id is not None and int(meter_id) != int(row_meter[0]):
138
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND')
139
140
        master_meter = dict()
141
        master_meter['id'] = row_meter[0]
142
        master_meter['name'] = row_meter[1]
143
        master_meter['cost_center_id'] = row_meter[2]
144
        master_meter['energy_category_id'] = row_meter[3]
145
        master_meter['energy_category_name'] = row_meter[4]
146
        master_meter['unit_of_measure'] = row_meter[5]
147
148
        ################################################################################################################
149
        # Step 3: query associated submeters
150
        ################################################################################################################
151
        submeter_list = list()
152
        submeter_id_set = set()
153
154
        cursor_system.execute(" SELECT id, name, energy_category_id "
155
                              " FROM tbl_meters "
156
                              " WHERE master_meter_id = %s ",
157
                              (master_meter['id'],))
158
        rows_meters = cursor_system.fetchall()
159
160
        if rows_meters is not None and len(rows_meters) > 0:
161
            for row in rows_meters:
162
                submeter_list.append({"id": row[0],
163
                                      "name": row[1],
164
                                      "energy_category_id": row[2]})
165
                submeter_id_set.add(row[0])
166
167
        ################################################################################################################
168
        # Step 4: query reporting period master meter energy consumption
169
        ################################################################################################################
170
        reporting = dict()
171
        reporting['master_meter_total_in_category'] = Decimal(0.0)
172
        reporting['submeters_total_in_category'] = Decimal(0.0)
173
        reporting['total_difference_in_category'] = Decimal(0.0)
174
        reporting['percentage_difference'] = Decimal(0.0)
175
        reporting['timestamps'] = list()
176
        reporting['master_meter_values'] = list()
177
        reporting['submeters_values'] = list()
178
        reporting['difference_values'] = list()
179
180
        parameters_data = dict()
181
        parameters_data['names'] = list()
182
        parameters_data['timestamps'] = list()
183
        parameters_data['values'] = list()
184
185
        query = (" SELECT start_datetime_utc, actual_value "
186
                 " FROM tbl_meter_hourly "
187
                 " WHERE meter_id = %s "
188
                 " AND start_datetime_utc >= %s "
189
                 " AND start_datetime_utc < %s "
190
                 " ORDER BY start_datetime_utc ")
191
        cursor_energy.execute(query, (master_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
192
        rows_meter_hourly = cursor_energy.fetchall()
193
194
        rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly,
195
                                                                            reporting_start_datetime_utc,
196
                                                                            reporting_end_datetime_utc,
197
                                                                            period_type)
198
199
        for row_meter_periodically in rows_meter_periodically:
200
            current_datetime_local = row_meter_periodically[0].replace(tzinfo=timezone.utc) + \
201
                                     timedelta(minutes=timezone_offset)
202
            if period_type == 'hourly':
203
                current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
204
            elif period_type == 'daily':
205
                current_datetime = current_datetime_local.strftime('%Y-%m-%d')
206
            elif period_type == 'weekly':
207
                current_datetime = current_datetime_local.strftime('%Y-%m-%d')
208
            elif period_type == 'monthly':
209
                current_datetime = current_datetime_local.strftime('%Y-%m')
210
            elif period_type == 'yearly':
211
                current_datetime = current_datetime_local.strftime('%Y')
212
213
            actual_value = Decimal(0.0) if row_meter_periodically[1] is None else row_meter_periodically[1]
214
215
            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...
216
            reporting['master_meter_values'].append(actual_value)
217
            reporting['master_meter_total_in_category'] += actual_value
218
219
        # add master meter values to parameter data
220
        parameters_data['names'].append(master_meter['name'])
221
        parameters_data['timestamps'].append(reporting['timestamps'])
222
        parameters_data['values'].append(reporting['master_meter_values'])
223
224
        ################################################################################################################
225
        # Step 5: query reporting period submeters energy consumption
226
        ################################################################################################################
227
        if len(submeter_list) > 0:
228
            query = (" SELECT start_datetime_utc, SUM(actual_value) "
229
                     " FROM tbl_meter_hourly "
230
                     " WHERE meter_id IN ( " + ', '.join(map(str, submeter_id_set)) + ") "
231
                     " AND start_datetime_utc >= %s "
232
                     " AND start_datetime_utc < %s "
233
                     " GROUP BY start_datetime_utc "
234
                     " ORDER BY start_datetime_utc ")
235
            cursor_energy.execute(query, (reporting_start_datetime_utc, reporting_end_datetime_utc))
236
            rows_submeters_hourly = cursor_energy.fetchall()
237
238
            rows_submeters_periodically = utilities.aggregate_hourly_data_by_period(rows_submeters_hourly,
239
                                                                                    reporting_start_datetime_utc,
240
                                                                                    reporting_end_datetime_utc,
241
                                                                                    period_type)
242
243
            for row_submeters_periodically in rows_submeters_periodically:
244
                current_datetime_local = row_submeters_periodically[0].replace(tzinfo=timezone.utc) + \
245
                                         timedelta(minutes=timezone_offset)
246
                if period_type == 'hourly':
247
                    current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
248
                elif period_type == 'daily':
249
                    current_datetime = current_datetime_local.strftime('%Y-%m-%d')
250
                elif period_type == 'weekly':
251
                    current_datetime = current_datetime_local.strftime('%Y-%m-%d')
252
                elif period_type == 'monthly':
253
                    current_datetime = current_datetime_local.strftime('%Y-%m')
254
                elif period_type == 'yearly':
255
                    current_datetime = current_datetime_local.strftime('%Y')
256
257
                actual_value = Decimal(0.0) if row_submeters_periodically[1] is None else row_submeters_periodically[1]
258
259
                reporting['submeters_values'].append(actual_value)
260
                reporting['submeters_total_in_category'] += actual_value
261
262
        ################################################################################################################
263
        # Step 6: calculate reporting period difference between master meter and submeters
264
        ################################################################################################################
265
        if len(submeter_list) > 0:
266
            for i in range(len(reporting['timestamps'])):
267
                reporting['difference_values'].append(reporting['master_meter_values'][i] -
268
                                                      reporting['submeters_values'][i])
269
        else:
270
            for i in range(len(reporting['timestamps'])):
271
                reporting['difference_values'].append(reporting['master_meter_values'][i])
272
273
        reporting['total_difference_in_category'] = \
274
            reporting['master_meter_total_in_category'] - reporting['submeters_total_in_category']
275
276
        if abs(reporting['master_meter_total_in_category']) > Decimal(0.0):
277
            reporting['percentage_difference'] = \
278
                reporting['total_difference_in_category'] / reporting['master_meter_total_in_category']
279
        elif abs(reporting['master_meter_total_in_category']) == Decimal(0.0) and \
280
                abs(reporting['submeters_total_in_category']) > Decimal(0.0):
281
            reporting['percentage_difference'] = Decimal(-1.0)
282
283
        ################################################################################################################
284
        # Step 7: query submeter values as parameter data
285
        ################################################################################################################
286
        for submeter in submeter_list:
287
            submeter_timestamps = list()
288
            submeter_values = list()
289
290
            query = (" SELECT start_datetime_utc, actual_value "
291
                     " FROM tbl_meter_hourly "
292
                     " WHERE meter_id = %s "
293
                     " AND start_datetime_utc >= %s "
294
                     " AND start_datetime_utc < %s "
295
                     " ORDER BY start_datetime_utc ")
296
            cursor_energy.execute(query, (submeter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
297
            rows_meter_hourly = cursor_energy.fetchall()
298
299
            rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly,
300
                                                                                reporting_start_datetime_utc,
301
                                                                                reporting_end_datetime_utc,
302
                                                                                period_type)
303
304
            for row_meter_periodically in rows_meter_periodically:
305
                current_datetime_local = row_meter_periodically[0].replace(tzinfo=timezone.utc) + \
306
                                         timedelta(minutes=timezone_offset)
307
                if period_type == 'hourly':
308
                    current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
309
                elif period_type == 'daily':
310
                    current_datetime = current_datetime_local.strftime('%Y-%m-%d')
311
                elif period_type == 'weekly':
312
                    current_datetime = current_datetime_local.strftime('%Y-%m-%d')
313
                elif period_type == 'monthly':
314
                    current_datetime = current_datetime_local.strftime('%Y-%m')
315
                elif period_type == 'yearly':
316
                    current_datetime = current_datetime_local.strftime('%Y')
317
318
                actual_value = Decimal(0.0) if row_meter_periodically[1] is None else row_meter_periodically[1]
319
320
                submeter_timestamps.append(current_datetime)
321
                submeter_values.append(actual_value)
322
323
            parameters_data['names'].append(submeter['name'])
324
            parameters_data['timestamps'].append(submeter_timestamps)
325
            parameters_data['values'].append(submeter_values)
326
327
        ################################################################################################################
328
        # Step 8: construct the report
329
        ################################################################################################################
330
        if cursor_system:
331
            cursor_system.close()
332
        if cnx_system:
333
            cnx_system.disconnect()
334
335
        if cursor_energy:
336
            cursor_energy.close()
337
        if cnx_energy:
338
            cnx_energy.disconnect()
339
340
        result = {
341
            "meter": {
342
                "cost_center_id": master_meter['cost_center_id'],
343
                "energy_category_id": master_meter['energy_category_id'],
344
                "energy_category_name": master_meter['energy_category_name'],
345
                "unit_of_measure": master_meter['unit_of_measure'],
346
            },
347
            "reporting_period": {
348
                "master_meter_consumption_in_category": reporting['master_meter_total_in_category'],
349
                "submeters_consumption_in_category": reporting['submeters_total_in_category'],
350
                "difference_in_category": reporting['total_difference_in_category'],
351
                "percentage_difference": reporting['percentage_difference'],
352
                "timestamps": reporting['timestamps'],
353
                "difference_values": reporting['difference_values'],
354
            },
355
            "parameters": {
356
                "names": parameters_data['names'],
357
                "timestamps": parameters_data['timestamps'],
358
                "values": parameters_data['values']
359
            },
360
        }
361
362
        # export result to Excel file and then encode the file to base64 string
363
        result['excel_bytes_base64'] = \
364
            excelexporters.metersubmetersbalance.export(result,
365
                                                        master_meter['name'],
366
                                                        reporting_period_start_datetime_local,
367
                                                        reporting_period_end_datetime_local,
368
                                                        period_type)
369
370
        resp.text = json.dumps(result)
371