| Total Complexity | 46 |
| Total Lines | 330 |
| Duplicated Lines | 96.97 % |
| 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 offlinemeterenergy 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 | import utilities |
||
| 7 | from decimal import * |
||
| 8 | |||
| 9 | |||
| 10 | View Code Duplication | class Reporting: |
|
|
|
|||
| 11 | @staticmethod |
||
| 12 | def __init__(): |
||
| 13 | pass |
||
| 14 | |||
| 15 | @staticmethod |
||
| 16 | def on_options(req, resp): |
||
| 17 | resp.status = falcon.HTTP_200 |
||
| 18 | |||
| 19 | #################################################################################################################### |
||
| 20 | # PROCEDURES |
||
| 21 | # Step 1: valid parameters |
||
| 22 | # Step 2: query the offline meter and energy category |
||
| 23 | # Step 3: query base period energy consumption |
||
| 24 | # Step 4: query reporting period energy consumption |
||
| 25 | # Step 5: query tariff data |
||
| 26 | # Step 6: construct the report |
||
| 27 | #################################################################################################################### |
||
| 28 | @staticmethod |
||
| 29 | def on_get(req, resp): |
||
| 30 | print(req.params) |
||
| 31 | offline_meter_id = req.params.get('offlinemeterid') |
||
| 32 | period_type = req.params.get('periodtype') |
||
| 33 | base_period_start_datetime = req.params.get('baseperiodstartdatetime') |
||
| 34 | base_period_end_datetime = req.params.get('baseperiodenddatetime') |
||
| 35 | reporting_period_start_datetime = req.params.get('reportingperiodstartdatetime') |
||
| 36 | reporting_period_end_datetime = req.params.get('reportingperiodenddatetime') |
||
| 37 | |||
| 38 | ################################################################################################################ |
||
| 39 | # Step 1: valid parameters |
||
| 40 | ################################################################################################################ |
||
| 41 | if offline_meter_id is None: |
||
| 42 | raise falcon.HTTPError(falcon.HTTP_400, |
||
| 43 | title='API.BAD_REQUEST', |
||
| 44 | description='API.INVALID_OFFLINE_METER_ID') |
||
| 45 | else: |
||
| 46 | offline_meter_id = str.strip(offline_meter_id) |
||
| 47 | if not offline_meter_id.isdigit() or int(offline_meter_id) <= 0: |
||
| 48 | raise falcon.HTTPError(falcon.HTTP_400, |
||
| 49 | title='API.BAD_REQUEST', |
||
| 50 | description='API.INVALID_OFFLINE_METER_ID') |
||
| 51 | |||
| 52 | if period_type is None: |
||
| 53 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
| 54 | else: |
||
| 55 | period_type = str.strip(period_type) |
||
| 56 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
||
| 57 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
| 58 | |||
| 59 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
| 60 | if config.utc_offset[0] == '-': |
||
| 61 | timezone_offset = -timezone_offset |
||
| 62 | |||
| 63 | base_start_datetime_utc = None |
||
| 64 | if base_period_start_datetime is not None and len(str.strip(base_period_start_datetime)) > 0: |
||
| 65 | base_period_start_datetime = str.strip(base_period_start_datetime) |
||
| 66 | try: |
||
| 67 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime, '%Y-%m-%dT%H:%M:%S') |
||
| 68 | except ValueError: |
||
| 69 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 70 | description="API.INVALID_BASE_PERIOD_BEGINS_DATETIME") |
||
| 71 | base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
| 72 | timedelta(minutes=timezone_offset) |
||
| 73 | |||
| 74 | base_end_datetime_utc = None |
||
| 75 | if base_period_end_datetime is not None and len(str.strip(base_period_end_datetime)) > 0: |
||
| 76 | base_period_end_datetime = str.strip(base_period_end_datetime) |
||
| 77 | try: |
||
| 78 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime, '%Y-%m-%dT%H:%M:%S') |
||
| 79 | except ValueError: |
||
| 80 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 81 | description="API.INVALID_BASE_PERIOD_ENDS_DATETIME") |
||
| 82 | base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
| 83 | timedelta(minutes=timezone_offset) |
||
| 84 | |||
| 85 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
||
| 86 | base_start_datetime_utc >= base_end_datetime_utc: |
||
| 87 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 88 | description='API.INVALID_BASE_PERIOD_ENDS_DATETIME') |
||
| 89 | |||
| 90 | if reporting_period_start_datetime is None: |
||
| 91 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 92 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
||
| 93 | else: |
||
| 94 | reporting_period_start_datetime = str.strip(reporting_period_start_datetime) |
||
| 95 | try: |
||
| 96 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime, '%Y-%m-%dT%H:%M:%S') |
||
| 97 | except ValueError: |
||
| 98 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 99 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
||
| 100 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
| 101 | timedelta(minutes=timezone_offset) |
||
| 102 | |||
| 103 | if reporting_period_end_datetime is None: |
||
| 104 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 105 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
||
| 106 | else: |
||
| 107 | reporting_period_end_datetime = str.strip(reporting_period_end_datetime) |
||
| 108 | try: |
||
| 109 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime, '%Y-%m-%dT%H:%M:%S') |
||
| 110 | except ValueError: |
||
| 111 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 112 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
||
| 113 | reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
| 114 | timedelta(minutes=timezone_offset) |
||
| 115 | |||
| 116 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
||
| 117 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 118 | description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME') |
||
| 119 | |||
| 120 | ################################################################################################################ |
||
| 121 | # Step 2: query the offline meter and energy category |
||
| 122 | ################################################################################################################ |
||
| 123 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
||
| 124 | cursor_system = cnx_system.cursor() |
||
| 125 | |||
| 126 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
||
| 127 | cursor_energy = cnx_energy.cursor() |
||
| 128 | |||
| 129 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
||
| 130 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
||
| 131 | " FROM tbl_offline_meters m, tbl_energy_categories ec " |
||
| 132 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (offline_meter_id,)) |
||
| 133 | row_offline_meter = cursor_system.fetchone() |
||
| 134 | if row_offline_meter is None: |
||
| 135 | if cursor_system: |
||
| 136 | cursor_system.close() |
||
| 137 | if cnx_system: |
||
| 138 | cnx_system.disconnect() |
||
| 139 | |||
| 140 | if cursor_energy: |
||
| 141 | cursor_energy.close() |
||
| 142 | if cnx_energy: |
||
| 143 | cnx_energy.disconnect() |
||
| 144 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.OFFLINE_METER_NOT_FOUND') |
||
| 145 | |||
| 146 | offline_meter = dict() |
||
| 147 | offline_meter['id'] = row_offline_meter[0] |
||
| 148 | offline_meter['name'] = row_offline_meter[1] |
||
| 149 | offline_meter['cost_center_id'] = row_offline_meter[2] |
||
| 150 | offline_meter['energy_category_id'] = row_offline_meter[3] |
||
| 151 | offline_meter['energy_category_name'] = row_offline_meter[4] |
||
| 152 | offline_meter['unit_of_measure'] = row_offline_meter[5] |
||
| 153 | offline_meter['kgce'] = row_offline_meter[6] |
||
| 154 | offline_meter['kgco2e'] = row_offline_meter[7] |
||
| 155 | |||
| 156 | ################################################################################################################ |
||
| 157 | # Step 3: query base period energy consumption |
||
| 158 | ################################################################################################################ |
||
| 159 | query = (" SELECT start_datetime_utc, actual_value " |
||
| 160 | " FROM tbl_offline_meter_hourly " |
||
| 161 | " WHERE offline_meter_id = %s " |
||
| 162 | " AND start_datetime_utc >= %s " |
||
| 163 | " AND start_datetime_utc < %s " |
||
| 164 | " ORDER BY start_datetime_utc ") |
||
| 165 | cursor_energy.execute(query, (offline_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
| 166 | rows_offline_meter_hourly = cursor_energy.fetchall() |
||
| 167 | |||
| 168 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
||
| 169 | base_start_datetime_utc, |
||
| 170 | base_end_datetime_utc, |
||
| 171 | period_type) |
||
| 172 | base = dict() |
||
| 173 | base['timestamps'] = list() |
||
| 174 | base['values_in_category'] = list() |
||
| 175 | base['total_in_category'] = Decimal(0.0) |
||
| 176 | base['values_in_kgce'] = list() |
||
| 177 | base['total_in_kgce'] = Decimal(0.0) |
||
| 178 | base['values_in_kgco2e'] = list() |
||
| 179 | base['total_in_kgco2e'] = Decimal(0.0) |
||
| 180 | |||
| 181 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
||
| 182 | current_datetime_local = row_offline_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
| 183 | timedelta(minutes=timezone_offset) |
||
| 184 | if period_type == 'hourly': |
||
| 185 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
| 186 | elif period_type == 'daily': |
||
| 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_offline_meter_periodically[1] is None \ |
||
| 194 | else row_offline_meter_periodically[1] |
||
| 195 | base['timestamps'].append(current_datetime) |
||
| 196 | base['values_in_category'].append(actual_value) |
||
| 197 | base['total_in_category'] += actual_value |
||
| 198 | base['values_in_kgce'].append(actual_value * offline_meter['kgce']) |
||
| 199 | base['total_in_kgce'] += actual_value * offline_meter['kgce'] |
||
| 200 | base['values_in_kgco2e'].append(actual_value * offline_meter['kgco2e']) |
||
| 201 | base['total_in_kgco2e'] += actual_value * offline_meter['kgco2e'] |
||
| 202 | ################################################################################################################ |
||
| 203 | # Step 4: query reporting period energy consumption |
||
| 204 | ################################################################################################################ |
||
| 205 | |||
| 206 | query = (" SELECT start_datetime_utc, actual_value " |
||
| 207 | " FROM tbl_offline_meter_hourly " |
||
| 208 | " WHERE offline_meter_id = %s " |
||
| 209 | " AND start_datetime_utc >= %s " |
||
| 210 | " AND start_datetime_utc < %s " |
||
| 211 | " ORDER BY start_datetime_utc ") |
||
| 212 | cursor_energy.execute(query, (offline_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
| 213 | rows_offline_meter_hourly = cursor_energy.fetchall() |
||
| 214 | |||
| 215 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
||
| 216 | reporting_start_datetime_utc, |
||
| 217 | reporting_end_datetime_utc, |
||
| 218 | period_type) |
||
| 219 | reporting = dict() |
||
| 220 | reporting['timestamps'] = list() |
||
| 221 | reporting['values_in_category'] = list() |
||
| 222 | reporting['total_in_category'] = Decimal(0.0) |
||
| 223 | reporting['values_in_kgce'] = list() |
||
| 224 | reporting['total_in_kgce'] = Decimal(0.0) |
||
| 225 | reporting['values_in_kgco2e'] = list() |
||
| 226 | reporting['total_in_kgco2e'] = Decimal(0.0) |
||
| 227 | |||
| 228 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
||
| 229 | current_datetime_local = row_offline_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
| 230 | timedelta(minutes=timezone_offset) |
||
| 231 | if period_type == 'hourly': |
||
| 232 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
| 233 | elif period_type == 'daily': |
||
| 234 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
| 235 | elif period_type == 'monthly': |
||
| 236 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
| 237 | elif period_type == 'yearly': |
||
| 238 | current_datetime = current_datetime_local.strftime('%Y') |
||
| 239 | |||
| 240 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
||
| 241 | else row_offline_meter_periodically[1] |
||
| 242 | |||
| 243 | reporting['timestamps'].append(current_datetime) |
||
| 244 | reporting['values_in_category'].append(actual_value) |
||
| 245 | reporting['total_in_category'] += actual_value |
||
| 246 | reporting['values_in_kgce'].append(actual_value * offline_meter['kgce']) |
||
| 247 | reporting['total_in_kgce'] += actual_value * offline_meter['kgce'] |
||
| 248 | reporting['values_in_kgco2e'].append(actual_value * offline_meter['kgco2e']) |
||
| 249 | reporting['total_in_kgco2e'] += actual_value * offline_meter['kgco2e'] |
||
| 250 | |||
| 251 | ################################################################################################################ |
||
| 252 | # Step 5: query tariff data |
||
| 253 | ################################################################################################################ |
||
| 254 | parameters_data = dict() |
||
| 255 | parameters_data['names'] = list() |
||
| 256 | parameters_data['timestamps'] = list() |
||
| 257 | parameters_data['values'] = list() |
||
| 258 | |||
| 259 | tariff_dict = utilities.get_energy_category_tariffs(offline_meter['cost_center_id'], |
||
| 260 | offline_meter['energy_category_id'], |
||
| 261 | reporting_start_datetime_utc, |
||
| 262 | reporting_end_datetime_utc) |
||
| 263 | tariff_timestamp_list = list() |
||
| 264 | tariff_value_list = list() |
||
| 265 | for k, v in tariff_dict.items(): |
||
| 266 | # convert k from utc to local |
||
| 267 | k = k + timedelta(minutes=timezone_offset) |
||
| 268 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
||
| 269 | tariff_value_list.append(v) |
||
| 270 | |||
| 271 | parameters_data['names'].append('TARIFF-' + offline_meter['energy_category_name']) |
||
| 272 | parameters_data['timestamps'].append(tariff_timestamp_list) |
||
| 273 | parameters_data['values'].append(tariff_value_list) |
||
| 274 | |||
| 275 | ################################################################################################################ |
||
| 276 | # Step 6: construct the report |
||
| 277 | ################################################################################################################ |
||
| 278 | if cursor_system: |
||
| 279 | cursor_system.close() |
||
| 280 | if cnx_system: |
||
| 281 | cnx_system.disconnect() |
||
| 282 | |||
| 283 | if cursor_energy: |
||
| 284 | cursor_energy.close() |
||
| 285 | if cnx_energy: |
||
| 286 | cnx_energy.disconnect() |
||
| 287 | |||
| 288 | result = { |
||
| 289 | "offline_meter": { |
||
| 290 | "cost_center_id": offline_meter['cost_center_id'], |
||
| 291 | "energy_category_id": offline_meter['energy_category_id'], |
||
| 292 | "energy_category_name": offline_meter['energy_category_name'], |
||
| 293 | "unit_of_measure": offline_meter['unit_of_measure'], |
||
| 294 | "kgce": offline_meter['kgce'], |
||
| 295 | "kgco2e": offline_meter['kgco2e'], |
||
| 296 | }, |
||
| 297 | "reporting_period": { |
||
| 298 | "increment_rate": |
||
| 299 | (reporting['total_in_category'] - base['total_in_category'])/base['total_in_category'] |
||
| 300 | if base['total_in_category'] > 0 else None, |
||
| 301 | "total_in_category": reporting['total_in_category'], |
||
| 302 | "total_in_kgce": reporting['total_in_kgce'], |
||
| 303 | "total_in_kgco2e": reporting['total_in_kgco2e'], |
||
| 304 | "timestamps": [reporting['timestamps'], |
||
| 305 | reporting['timestamps'], |
||
| 306 | reporting['timestamps']], |
||
| 307 | "values": [reporting['values_in_category'], |
||
| 308 | reporting['values_in_kgce'], |
||
| 309 | reporting['values_in_kgco2e']], |
||
| 310 | }, |
||
| 311 | "base_period": { |
||
| 312 | "total_in_category": base['total_in_category'], |
||
| 313 | "total_in_kgce": base['total_in_kgce'], |
||
| 314 | "total_in_kgco2e": base['total_in_kgco2e'], |
||
| 315 | "timestamps": [base['timestamps'], |
||
| 316 | base['timestamps'], |
||
| 317 | base['timestamps']], |
||
| 318 | "values": [base['values_in_category'], |
||
| 319 | base['values_in_kgce'], |
||
| 320 | base['values_in_kgco2e']], |
||
| 321 | }, |
||
| 322 | "parameters": { |
||
| 323 | "names": parameters_data['names'], |
||
| 324 | "timestamps": parameters_data['timestamps'], |
||
| 325 | "values": parameters_data['values'] |
||
| 326 | }, |
||
| 327 | } |
||
| 328 | |||
| 329 | resp.body = json.dumps(result) |
||
| 330 |