Passed
Push — master ( 910afa...63c214 )
by Guangyu
07:58 queued 11s
created

reports.metertrend   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 296
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 51
eloc 211
dl 0
loc 296
rs 7.92
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 266 49

How to fix   Complexity   

Complexity

Complex classes like reports.metertrend 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
import falcon
3
import simplejson as json
4
import mysql.connector
5
import config
6
from datetime import datetime, timedelta, timezone
7
from core import utilities
8
import excelexporters.metertrend
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 meter and energy category
25
    # Step 3: query associated points
26
    # Step 4: query reporting period points trends
27
    # Step 5: query tariff data
28
    # Step 6: construct the report
29
    ####################################################################################################################
30
    @staticmethod
31
    def on_get(req, resp):
32
        print(req.params)
33
        meter_id = req.params.get('meterid')
34
        meter_uuid = req.params.get('meteruuid')
35
        reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime')
36
        reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime')
37
        quick_mode = req.params.get('quickmode')
38
39
        ################################################################################################################
40
        # Step 1: valid parameters
41
        ################################################################################################################
42
        if meter_id is None and meter_uuid is None:
43
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
44
45
        if meter_id is not None:
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 meter_uuid is not None:
51
            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)
52
            match = regex.match(str.strip(meter_uuid))
53
            if not bool(match):
54
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_UUID')
55
56
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
57
        if config.utc_offset[0] == '-':
58
            timezone_offset = -timezone_offset
59
60
        if reporting_period_start_datetime_local is None:
61
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
62
                                   description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
63
        else:
64
            reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local)
65
            try:
66
                reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local,
67
                                                                 '%Y-%m-%dT%H:%M:%S')
68
            except ValueError:
69
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
70
                                       description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
71
            reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \
72
                timedelta(minutes=timezone_offset)
73
74
        if reporting_period_end_datetime_local is None:
75
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
76
                                   description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
77
        else:
78
            reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local)
79
            try:
80
                reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local,
81
                                                               '%Y-%m-%dT%H:%M:%S')
82
            except ValueError:
83
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
84
                                       description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
85
            reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \
86
                timedelta(minutes=timezone_offset)
87
88
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
89
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
90
                                   description='API.INVALID_REPORTING_PERIOD_END_DATETIME')
91
92
        # if turn quick mode on, do not return parameters data and excel file
93
        is_quick_mode = False
94
        if quick_mode is not None and \
95
                len(str.strip(quick_mode)) > 0 and \
96
                str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'):
97
            is_quick_mode = True
98
99
        ################################################################################################################
100
        # Step 2: query the meter and energy category
101
        ################################################################################################################
102
        cnx_system = mysql.connector.connect(**config.myems_system_db)
103
        cursor_system = cnx_system.cursor()
104
105
        cnx_historical = mysql.connector.connect(**config.myems_historical_db)
106
        cursor_historical = cnx_historical.cursor()
107
        if meter_id is not None:
108
            cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, "
109
                                  "        ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e "
110
                                  " FROM tbl_meters m, tbl_energy_categories ec "
111
                                  " WHERE m.id = %s AND m.energy_category_id = ec.id ", (meter_id,))
112
            row_meter = cursor_system.fetchone()
113
        elif meter_uuid 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, ec.kgce, ec.kgco2e "
116
                                  " FROM tbl_meters m, tbl_energy_categories ec "
117
                                  " WHERE m.uuid = %s AND m.energy_category_id = ec.id ", (meter_uuid,))
118
            row_meter = cursor_system.fetchone()
119
120
        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...
121
            if cursor_system:
122
                cursor_system.close()
123
            if cnx_system:
124
                cnx_system.disconnect()
125
126
            if cursor_historical:
127
                cursor_historical.close()
128
            if cnx_historical:
129
                cnx_historical.disconnect()
130
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND')
131
        meter = dict()
132
        meter['id'] = row_meter[0]
133
        meter['name'] = row_meter[1]
134
        meter['cost_center_id'] = row_meter[2]
135
        meter['energy_category_id'] = row_meter[3]
136
        meter['energy_category_name'] = row_meter[4]
137
        meter['unit_of_measure'] = row_meter[5]
138
        meter['kgce'] = row_meter[6]
139
        meter['kgco2e'] = row_meter[7]
140
141
        ################################################################################################################
142
        # Step 3: query associated points
143
        ################################################################################################################
144
        point_list = list()
145
        cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type  "
146
                              " FROM tbl_meters m, tbl_meters_points mp, tbl_points p "
147
                              " WHERE m.id = %s AND m.id = mp.meter_id AND mp.point_id = p.id "
148
                              " ORDER BY p.id ", (meter['id'],))
149
        rows_points = cursor_system.fetchall()
150
        if rows_points is not None and len(rows_points) > 0:
151
            for row in rows_points:
152
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
153
154
        ################################################################################################################
155
        # Step 4: query reporting period points trends
156
        ################################################################################################################
157
        reporting = dict()
158
        reporting['names'] = list()
159
        reporting['timestamps'] = list()
160
        reporting['values'] = list()
161
162
        for point in point_list:
163
            if is_quick_mode and point['object_type'] != 'ENERGY_VALUE':
164
                continue
165
166
            point_values = []
167
            point_timestamps = []
168
            if point['object_type'] == 'ANALOG_VALUE':
169
                query = (" SELECT utc_date_time, actual_value "
170
                         " FROM tbl_analog_value "
171
                         " WHERE point_id = %s "
172
                         "       AND utc_date_time BETWEEN %s AND %s "
173
                         " ORDER BY utc_date_time ")
174
                cursor_historical.execute(query, (point['id'],
175
                                                  reporting_start_datetime_utc,
176
                                                  reporting_end_datetime_utc))
177
                rows = cursor_historical.fetchall()
178
179
                if rows is not None and len(rows) > 0:
180
                    for row in rows:
181
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
182
                                                 timedelta(minutes=timezone_offset)
183
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
184
                        point_timestamps.append(current_datetime)
185
                        point_values.append(row[1])
186
187
            elif point['object_type'] == 'ENERGY_VALUE':
188
                query = (" SELECT utc_date_time, actual_value "
189
                         " FROM tbl_energy_value "
190
                         " WHERE point_id = %s "
191
                         "       AND utc_date_time BETWEEN %s AND %s "
192
                         " ORDER BY utc_date_time ")
193
                cursor_historical.execute(query, (point['id'],
194
                                                  reporting_start_datetime_utc,
195
                                                  reporting_end_datetime_utc))
196
                rows = cursor_historical.fetchall()
197
198
                if rows is not None and len(rows) > 0:
199
                    for row in rows:
200
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
201
                                                 timedelta(minutes=timezone_offset)
202
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
203
                        point_timestamps.append(current_datetime)
204
                        point_values.append(row[1])
205
            elif point['object_type'] == 'DIGITAL_VALUE':
206
                query = (" SELECT utc_date_time, actual_value "
207
                         " FROM tbl_digital_value "
208
                         " WHERE point_id = %s "
209
                         "       AND utc_date_time BETWEEN %s AND %s "
210
                         " ORDER BY utc_date_time ")
211
                cursor_historical.execute(query, (point['id'],
212
                                                  reporting_start_datetime_utc,
213
                                                  reporting_end_datetime_utc))
214
                rows = cursor_historical.fetchall()
215
216
                if rows is not None and len(rows) > 0:
217
                    for row in rows:
218
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
219
                                                 timedelta(minutes=timezone_offset)
220
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
221
                        point_timestamps.append(current_datetime)
222
                        point_values.append(row[1])
223
224
            reporting['names'].append(point['name'] + ' (' + point['units'] + ')')
225
            reporting['timestamps'].append(point_timestamps)
226
            reporting['values'].append(point_values)
227
228
        ################################################################################################################
229
        # Step 5: query tariff data
230
        ################################################################################################################
231
        parameters_data = dict()
232
        parameters_data['names'] = list()
233
        parameters_data['timestamps'] = list()
234
        parameters_data['values'] = list()
235
        if not is_quick_mode:
236
            tariff_dict = utilities.get_energy_category_tariffs(meter['cost_center_id'],
237
                                                                meter['energy_category_id'],
238
                                                                reporting_start_datetime_utc,
239
                                                                reporting_end_datetime_utc)
240
            print(tariff_dict)
241
            tariff_timestamp_list = list()
242
            tariff_value_list = list()
243
            for k, v in tariff_dict.items():
244
                # convert k from utc to local
245
                k = k + timedelta(minutes=timezone_offset)
246
                tariff_timestamp_list.append(k.isoformat()[0:19])
247
                tariff_value_list.append(v)
248
249
            parameters_data['names'].append('TARIFF-' + meter['energy_category_name'])
250
            parameters_data['timestamps'].append(tariff_timestamp_list)
251
            parameters_data['values'].append(tariff_value_list)
252
253
        ################################################################################################################
254
        # Step 6: construct the report
255
        ################################################################################################################
256
        if cursor_system:
257
            cursor_system.close()
258
        if cnx_system:
259
            cnx_system.disconnect()
260
261
        if cursor_historical:
262
            cursor_historical.close()
263
        if cnx_historical:
264
            cnx_historical.disconnect()
265
266
        result = {
267
            "meter": {
268
                "cost_center_id": meter['cost_center_id'],
269
                "energy_category_id": meter['energy_category_id'],
270
                "energy_category_name": meter['energy_category_name'],
271
                "unit_of_measure": meter['unit_of_measure'],
272
                "kgce": meter['kgce'],
273
                "kgco2e": meter['kgco2e'],
274
            },
275
            "reporting_period": {
276
                "names": reporting['names'],
277
                "timestamps": reporting['timestamps'],
278
                "values": reporting['values'],
279
            },
280
            "parameters": {
281
                "names": parameters_data['names'],
282
                "timestamps": parameters_data['timestamps'],
283
                "values": parameters_data['values']
284
            },
285
            "excel_bytes_base64": None
286
        }
287
        # export result to Excel file and then encode the file to base64 string
288
        if not is_quick_mode:
289
            result['excel_bytes_base64'] = excelexporters.metertrend.export(result,
290
                                                                            meter['name'],
291
                                                                            reporting_period_start_datetime_local,
292
                                                                            reporting_period_end_datetime_local,
293
                                                                            None)
294
295
        resp.text = json.dumps(result)
296