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