Passed
Push — master ( b7565b...74a776 )
by Guangyu
09:00 queued 11s
created

reports.metersubmetersbalance   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 351
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 55
eloc 238
dl 0
loc 351
rs 6
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 319 53

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