Total Complexity | 54 |
Total Lines | 386 |
Duplicated Lines | 97.15 % |
Changes | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like reports.virtualmetercost 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.virtualmetercost |
||
9 | |||
10 | |||
11 | View Code Duplication | class Reporting: |
|
|
|||
12 | @staticmethod |
||
13 | def __init__(): |
||
14 | pass |
||
15 | |||
16 | @staticmethod |
||
17 | def on_options(req, resp): |
||
18 | resp.status = falcon.HTTP_200 |
||
19 | |||
20 | #################################################################################################################### |
||
21 | # PROCEDURES |
||
22 | # Step 1: valid parameters |
||
23 | # Step 2: query the virtual meter and energy category |
||
24 | # Step 3: query base period energy consumption |
||
25 | # Step 4: query base period energy cost |
||
26 | # Step 5: query reporting period energy consumption |
||
27 | # Step 6: query reporting period energy cost |
||
28 | # Step 7: query tariff data |
||
29 | # Step 8: construct the report |
||
30 | #################################################################################################################### |
||
31 | @staticmethod |
||
32 | def on_get(req, resp): |
||
33 | print(req.params) |
||
34 | virtual_meter_id = req.params.get('virtualmeterid') |
||
35 | period_type = req.params.get('periodtype') |
||
36 | base_period_start_datetime_local = req.params.get('baseperiodstartdatetime') |
||
37 | base_period_end_datetime_local = req.params.get('baseperiodenddatetime') |
||
38 | reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
||
39 | reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') |
||
40 | |||
41 | ################################################################################################################ |
||
42 | # Step 1: valid parameters |
||
43 | ################################################################################################################ |
||
44 | if virtual_meter_id is None: |
||
45 | raise falcon.HTTPError(falcon.HTTP_400, |
||
46 | title='API.BAD_REQUEST', |
||
47 | description='API.INVALID_VIRTUAL_METER_ID') |
||
48 | else: |
||
49 | virtual_meter_id = str.strip(virtual_meter_id) |
||
50 | if not virtual_meter_id.isdigit() or int(virtual_meter_id) <= 0: |
||
51 | raise falcon.HTTPError(falcon.HTTP_400, |
||
52 | title='API.BAD_REQUEST', |
||
53 | description='API.INVALID_VIRTUAL_METER_ID') |
||
54 | |||
55 | if period_type is None: |
||
56 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
57 | else: |
||
58 | period_type = str.strip(period_type) |
||
59 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
||
60 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
61 | |||
62 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
63 | if config.utc_offset[0] == '-': |
||
64 | timezone_offset = -timezone_offset |
||
65 | |||
66 | base_start_datetime_utc = None |
||
67 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
||
68 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
||
69 | try: |
||
70 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
||
71 | except ValueError: |
||
72 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
73 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
||
74 | base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
75 | timedelta(minutes=timezone_offset) |
||
76 | |||
77 | base_end_datetime_utc = None |
||
78 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
||
79 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
||
80 | try: |
||
81 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
||
82 | except ValueError: |
||
83 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
84 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
||
85 | base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
86 | timedelta(minutes=timezone_offset) |
||
87 | |||
88 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
||
89 | base_start_datetime_utc >= base_end_datetime_utc: |
||
90 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
91 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
||
92 | |||
93 | if reporting_period_start_datetime_local is None: |
||
94 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
95 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
||
96 | else: |
||
97 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
||
98 | try: |
||
99 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
||
100 | '%Y-%m-%dT%H:%M:%S') |
||
101 | except ValueError: |
||
102 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
103 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
||
104 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
105 | timedelta(minutes=timezone_offset) |
||
106 | |||
107 | if reporting_period_end_datetime_local is None: |
||
108 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
109 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
||
110 | else: |
||
111 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
||
112 | try: |
||
113 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
||
114 | '%Y-%m-%dT%H:%M:%S') |
||
115 | except ValueError: |
||
116 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
117 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
||
118 | reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
119 | timedelta(minutes=timezone_offset) |
||
120 | |||
121 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
||
122 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
123 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
||
124 | |||
125 | ################################################################################################################ |
||
126 | # Step 2: query the virtual meter and energy category |
||
127 | ################################################################################################################ |
||
128 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
||
129 | cursor_system = cnx_system.cursor() |
||
130 | |||
131 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
||
132 | cursor_energy = cnx_energy.cursor() |
||
133 | |||
134 | cnx_billing = mysql.connector.connect(**config.myems_billing_db) |
||
135 | cursor_billing = cnx_billing.cursor() |
||
136 | |||
137 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
||
138 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
||
139 | " FROM tbl_virtual_meters m, tbl_energy_categories ec " |
||
140 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (virtual_meter_id,)) |
||
141 | row_virtual_meter = cursor_system.fetchone() |
||
142 | if row_virtual_meter is None: |
||
143 | if cursor_system: |
||
144 | cursor_system.close() |
||
145 | if cnx_system: |
||
146 | cnx_system.disconnect() |
||
147 | |||
148 | if cursor_energy: |
||
149 | cursor_energy.close() |
||
150 | if cnx_energy: |
||
151 | cnx_energy.disconnect() |
||
152 | |||
153 | if cursor_billing: |
||
154 | cursor_billing.close() |
||
155 | if cnx_billing: |
||
156 | cnx_billing.disconnect() |
||
157 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.VIRTUAL_METER_NOT_FOUND') |
||
158 | |||
159 | virtual_meter = dict() |
||
160 | virtual_meter['id'] = row_virtual_meter[0] |
||
161 | virtual_meter['name'] = row_virtual_meter[1] |
||
162 | virtual_meter['cost_center_id'] = row_virtual_meter[2] |
||
163 | virtual_meter['energy_category_id'] = row_virtual_meter[3] |
||
164 | virtual_meter['energy_category_name'] = row_virtual_meter[4] |
||
165 | virtual_meter['unit_of_measure'] = config.currency_unit |
||
166 | virtual_meter['kgce'] = row_virtual_meter[6] |
||
167 | virtual_meter['kgco2e'] = row_virtual_meter[7] |
||
168 | |||
169 | ################################################################################################################ |
||
170 | # Step 3: query base period energy consumption |
||
171 | ################################################################################################################ |
||
172 | query = (" SELECT start_datetime_utc, actual_value " |
||
173 | " FROM tbl_virtual_meter_hourly " |
||
174 | " WHERE virtual_meter_id = %s " |
||
175 | " AND start_datetime_utc >= %s " |
||
176 | " AND start_datetime_utc < %s " |
||
177 | " ORDER BY start_datetime_utc ") |
||
178 | cursor_energy.execute(query, (virtual_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
179 | rows_virtual_meter_hourly = cursor_energy.fetchall() |
||
180 | |||
181 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
||
182 | base_start_datetime_utc, |
||
183 | base_end_datetime_utc, |
||
184 | period_type) |
||
185 | base = dict() |
||
186 | base['timestamps'] = list() |
||
187 | base['values'] = list() |
||
188 | base['total_in_category'] = Decimal(0.0) |
||
189 | base['total_in_kgce'] = Decimal(0.0) |
||
190 | base['total_in_kgco2e'] = Decimal(0.0) |
||
191 | |||
192 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
||
193 | current_datetime_local = row_virtual_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
194 | timedelta(minutes=timezone_offset) |
||
195 | if period_type == 'hourly': |
||
196 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
197 | elif period_type == 'daily': |
||
198 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
199 | elif period_type == 'monthly': |
||
200 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
201 | elif period_type == 'yearly': |
||
202 | current_datetime = current_datetime_local.strftime('%Y') |
||
203 | |||
204 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
||
205 | else row_virtual_meter_periodically[1] |
||
206 | base['timestamps'].append(current_datetime) |
||
207 | base['total_in_kgce'] += actual_value * virtual_meter['kgce'] |
||
208 | base['total_in_kgco2e'] += actual_value * virtual_meter['kgco2e'] |
||
209 | |||
210 | ################################################################################################################ |
||
211 | # Step 4: query base period energy cost |
||
212 | ################################################################################################################ |
||
213 | query = (" SELECT start_datetime_utc, actual_value " |
||
214 | " FROM tbl_virtual_meter_hourly " |
||
215 | " WHERE virtual_meter_id = %s " |
||
216 | " AND start_datetime_utc >= %s " |
||
217 | " AND start_datetime_utc < %s " |
||
218 | " ORDER BY start_datetime_utc ") |
||
219 | cursor_billing.execute(query, (virtual_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
220 | rows_virtual_meter_hourly = cursor_billing.fetchall() |
||
221 | |||
222 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
||
223 | base_start_datetime_utc, |
||
224 | base_end_datetime_utc, |
||
225 | period_type) |
||
226 | |||
227 | base['values'] = list() |
||
228 | base['total_in_category'] = Decimal(0.0) |
||
229 | |||
230 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
||
231 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
||
232 | else row_virtual_meter_periodically[1] |
||
233 | base['values'].append(actual_value) |
||
234 | base['total_in_category'] += actual_value |
||
235 | |||
236 | ################################################################################################################ |
||
237 | # Step 5: query reporting period energy consumption |
||
238 | ################################################################################################################ |
||
239 | query = (" SELECT start_datetime_utc, actual_value " |
||
240 | " FROM tbl_virtual_meter_hourly " |
||
241 | " WHERE virtual_meter_id = %s " |
||
242 | " AND start_datetime_utc >= %s " |
||
243 | " AND start_datetime_utc < %s " |
||
244 | " ORDER BY start_datetime_utc ") |
||
245 | cursor_billing.execute(query, (virtual_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
246 | rows_virtual_meter_hourly = cursor_billing.fetchall() |
||
247 | |||
248 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
||
249 | reporting_start_datetime_utc, |
||
250 | reporting_end_datetime_utc, |
||
251 | period_type) |
||
252 | reporting = dict() |
||
253 | reporting['timestamps'] = list() |
||
254 | reporting['values'] = list() |
||
255 | reporting['total_in_category'] = Decimal(0.0) |
||
256 | reporting['total_in_kgce'] = Decimal(0.0) |
||
257 | reporting['total_in_kgco2e'] = Decimal(0.0) |
||
258 | |||
259 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
||
260 | current_datetime_local = row_virtual_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
261 | timedelta(minutes=timezone_offset) |
||
262 | if period_type == 'hourly': |
||
263 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
264 | elif period_type == 'daily': |
||
265 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
266 | elif period_type == 'monthly': |
||
267 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
268 | elif period_type == 'yearly': |
||
269 | current_datetime = current_datetime_local.strftime('%Y') |
||
270 | |||
271 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
||
272 | else row_virtual_meter_periodically[1] |
||
273 | |||
274 | reporting['timestamps'].append(current_datetime) |
||
275 | reporting['total_in_kgce'] += actual_value * virtual_meter['kgce'] |
||
276 | reporting['total_in_kgco2e'] += actual_value * virtual_meter['kgco2e'] |
||
277 | |||
278 | ################################################################################################################ |
||
279 | # Step 6: query reporting period energy cost |
||
280 | ################################################################################################################ |
||
281 | query = (" SELECT start_datetime_utc, actual_value " |
||
282 | " FROM tbl_virtual_meter_hourly " |
||
283 | " WHERE virtual_meter_id = %s " |
||
284 | " AND start_datetime_utc >= %s " |
||
285 | " AND start_datetime_utc < %s " |
||
286 | " ORDER BY start_datetime_utc ") |
||
287 | cursor_billing.execute(query, (virtual_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
288 | rows_virtual_meter_hourly = cursor_billing.fetchall() |
||
289 | |||
290 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
||
291 | reporting_start_datetime_utc, |
||
292 | reporting_end_datetime_utc, |
||
293 | period_type) |
||
294 | |||
295 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
||
296 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
||
297 | else row_virtual_meter_periodically[1] |
||
298 | |||
299 | reporting['values'].append(actual_value) |
||
300 | reporting['total_in_category'] += actual_value |
||
301 | |||
302 | ################################################################################################################ |
||
303 | # Step 7: query tariff data |
||
304 | ################################################################################################################ |
||
305 | parameters_data = dict() |
||
306 | parameters_data['names'] = list() |
||
307 | parameters_data['timestamps'] = list() |
||
308 | parameters_data['values'] = list() |
||
309 | |||
310 | tariff_dict = utilities.get_energy_category_tariffs(virtual_meter['cost_center_id'], |
||
311 | virtual_meter['energy_category_id'], |
||
312 | reporting_start_datetime_utc, |
||
313 | reporting_end_datetime_utc) |
||
314 | tariff_timestamp_list = list() |
||
315 | tariff_value_list = list() |
||
316 | for k, v in tariff_dict.items(): |
||
317 | # convert k from utc to local |
||
318 | k = k + timedelta(minutes=timezone_offset) |
||
319 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
||
320 | tariff_value_list.append(v) |
||
321 | |||
322 | parameters_data['names'].append('TARIFF-' + virtual_meter['energy_category_name']) |
||
323 | parameters_data['timestamps'].append(tariff_timestamp_list) |
||
324 | parameters_data['values'].append(tariff_value_list) |
||
325 | |||
326 | ################################################################################################################ |
||
327 | # Step 8: construct the report |
||
328 | ################################################################################################################ |
||
329 | if cursor_system: |
||
330 | cursor_system.close() |
||
331 | if cnx_system: |
||
332 | cnx_system.disconnect() |
||
333 | |||
334 | if cursor_energy: |
||
335 | cursor_energy.close() |
||
336 | if cnx_energy: |
||
337 | cnx_energy.disconnect() |
||
338 | |||
339 | if cursor_billing: |
||
340 | cursor_billing.close() |
||
341 | if cnx_billing: |
||
342 | cnx_billing.disconnect() |
||
343 | |||
344 | result = { |
||
345 | "virtual_meter": { |
||
346 | "cost_center_id": virtual_meter['cost_center_id'], |
||
347 | "energy_category_id": virtual_meter['energy_category_id'], |
||
348 | "energy_category_name": virtual_meter['energy_category_name'], |
||
349 | "unit_of_measure": config.currency_unit, |
||
350 | "kgce": virtual_meter['kgce'], |
||
351 | "kgco2e": virtual_meter['kgco2e'], |
||
352 | }, |
||
353 | "base_period": { |
||
354 | "total_in_category": base['total_in_category'], |
||
355 | "total_in_kgce": base['total_in_kgce'], |
||
356 | "total_in_kgco2e": base['total_in_kgco2e'], |
||
357 | "timestamps": base['timestamps'], |
||
358 | "values": base['values'], |
||
359 | }, |
||
360 | "reporting_period": { |
||
361 | "increment_rate": |
||
362 | (reporting['total_in_category'] - base['total_in_category']) / base['total_in_category'] |
||
363 | if base['total_in_category'] > 0 else None, |
||
364 | "total_in_category": reporting['total_in_category'], |
||
365 | "total_in_kgce": reporting['total_in_kgce'], |
||
366 | "total_in_kgco2e": reporting['total_in_kgco2e'], |
||
367 | "timestamps": reporting['timestamps'], |
||
368 | "values": reporting['values'], |
||
369 | }, |
||
370 | "parameters": { |
||
371 | "names": parameters_data['names'], |
||
372 | "timestamps": parameters_data['timestamps'], |
||
373 | "values": parameters_data['values'] |
||
374 | }, |
||
375 | } |
||
376 | |||
377 | # export result to Excel file and then encode the file to base64 string |
||
378 | result['excel_bytes_base64'] = \ |
||
379 | excelexporters.virtualmetercost.export(result, |
||
380 | virtual_meter['name'], |
||
381 | reporting_period_start_datetime_local, |
||
382 | reporting_period_end_datetime_local, |
||
383 | period_type) |
||
384 | |||
385 | resp.body = json.dumps(result) |
||
386 |