| Conditions | 109 | 
| Total Lines | 515 | 
| Code Lines | 389 | 
| Lines | 515 | 
| Ratio | 100 % | 
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like reports.equipmentcarbon.Reporting.on_get() 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  | 
            ||
| 34 | @staticmethod  | 
            ||
| 35 | def on_get(req, resp):  | 
            ||
| 36 | print(req.params)  | 
            ||
| 37 |         equipment_id = req.params.get('equipmentid') | 
            ||
| 38 |         equipment_uuid = req.params.get('equipmentuuid') | 
            ||
| 39 |         period_type = req.params.get('periodtype') | 
            ||
| 40 |         base_start_datetime_local = req.params.get('baseperiodstartdatetime') | 
            ||
| 41 |         base_end_datetime_local = req.params.get('baseperiodenddatetime') | 
            ||
| 42 |         reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime') | 
            ||
| 43 |         reporting_end_datetime_local = req.params.get('reportingperiodenddatetime') | 
            ||
| 44 | |||
| 45 | ################################################################################################################  | 
            ||
| 46 | # Step 1: valid parameters  | 
            ||
| 47 | ################################################################################################################  | 
            ||
| 48 | if equipment_id is None and equipment_uuid is None:  | 
            ||
| 49 | raise falcon.HTTPError(falcon.HTTP_400,  | 
            ||
| 50 | title='API.BAD_REQUEST',  | 
            ||
| 51 | description='API.INVALID_EQUIPMENT_ID')  | 
            ||
| 52 | |||
| 53 | if equipment_id is not None:  | 
            ||
| 54 | equipment_id = str.strip(equipment_id)  | 
            ||
| 55 | if not equipment_id.isdigit() or int(equipment_id) <= 0:  | 
            ||
| 56 | raise falcon.HTTPError(falcon.HTTP_400,  | 
            ||
| 57 | title='API.BAD_REQUEST',  | 
            ||
| 58 | description='API.INVALID_EQUIPMENT_ID')  | 
            ||
| 59 | |||
| 60 | if equipment_uuid is not None:  | 
            ||
| 61 |             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) | 
            ||
| 62 | match = regex.match(str.strip(equipment_uuid))  | 
            ||
| 63 | if not bool(match):  | 
            ||
| 64 | raise falcon.HTTPError(falcon.HTTP_400,  | 
            ||
| 65 | title='API.BAD_REQUEST',  | 
            ||
| 66 | description='API.INVALID_EQUIPMENT_UUID')  | 
            ||
| 67 | |||
| 68 | if period_type is None:  | 
            ||
| 69 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')  | 
            ||
| 70 | else:  | 
            ||
| 71 | period_type = str.strip(period_type)  | 
            ||
| 72 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']:  | 
            ||
| 73 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')  | 
            ||
| 74 | |||
| 75 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])  | 
            ||
| 76 | if config.utc_offset[0] == '-':  | 
            ||
| 77 | timezone_offset = -timezone_offset  | 
            ||
| 78 | |||
| 79 | base_start_datetime_utc = None  | 
            ||
| 80 | if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0:  | 
            ||
| 81 | base_start_datetime_local = str.strip(base_start_datetime_local)  | 
            ||
| 82 | try:  | 
            ||
| 83 | base_start_datetime_utc = datetime.strptime(base_start_datetime_local,  | 
            ||
| 84 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \  | 
            ||
| 85 | timedelta(minutes=timezone_offset)  | 
            ||
| 86 | except ValueError:  | 
            ||
| 87 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',  | 
            ||
| 88 | description="API.INVALID_BASE_PERIOD_START_DATETIME")  | 
            ||
| 89 | |||
| 90 | base_end_datetime_utc = None  | 
            ||
| 91 | if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0:  | 
            ||
| 92 | base_end_datetime_local = str.strip(base_end_datetime_local)  | 
            ||
| 93 | try:  | 
            ||
| 94 | base_end_datetime_utc = datetime.strptime(base_end_datetime_local,  | 
            ||
| 95 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \  | 
            ||
| 96 | timedelta(minutes=timezone_offset)  | 
            ||
| 97 | except ValueError:  | 
            ||
| 98 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',  | 
            ||
| 99 | description="API.INVALID_BASE_PERIOD_END_DATETIME")  | 
            ||
| 100 | |||
| 101 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \  | 
            ||
| 102 | base_start_datetime_utc >= base_end_datetime_utc:  | 
            ||
| 103 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',  | 
            ||
| 104 | description='API.INVALID_BASE_PERIOD_END_DATETIME')  | 
            ||
| 105 | |||
| 106 | if reporting_start_datetime_local is None:  | 
            ||
| 107 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',  | 
            ||
| 108 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME")  | 
            ||
| 109 | else:  | 
            ||
| 110 | reporting_start_datetime_local = str.strip(reporting_start_datetime_local)  | 
            ||
| 111 | try:  | 
            ||
| 112 | reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local,  | 
            ||
| 113 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \  | 
            ||
| 114 | timedelta(minutes=timezone_offset)  | 
            ||
| 115 | except ValueError:  | 
            ||
| 116 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',  | 
            ||
| 117 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME")  | 
            ||
| 118 | |||
| 119 | if reporting_end_datetime_local is None:  | 
            ||
| 120 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',  | 
            ||
| 121 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME")  | 
            ||
| 122 | else:  | 
            ||
| 123 | reporting_end_datetime_local = str.strip(reporting_end_datetime_local)  | 
            ||
| 124 | try:  | 
            ||
| 125 | reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local,  | 
            ||
| 126 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \  | 
            ||
| 127 | timedelta(minutes=timezone_offset)  | 
            ||
| 128 | except ValueError:  | 
            ||
| 129 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',  | 
            ||
| 130 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME")  | 
            ||
| 131 | |||
| 132 | if reporting_start_datetime_utc >= reporting_end_datetime_utc:  | 
            ||
| 133 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',  | 
            ||
| 134 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME')  | 
            ||
| 135 | |||
| 136 | ################################################################################################################  | 
            ||
| 137 | # Step 2: query the equipment  | 
            ||
| 138 | ################################################################################################################  | 
            ||
| 139 | cnx_system = mysql.connector.connect(**config.myems_system_db)  | 
            ||
| 140 | cursor_system = cnx_system.cursor()  | 
            ||
| 141 | |||
| 142 | cnx_carbon = mysql.connector.connect(**config.myems_carbon_db)  | 
            ||
| 143 | cursor_carbon = cnx_carbon.cursor()  | 
            ||
| 144 | |||
| 145 | cnx_historical = mysql.connector.connect(**config.myems_historical_db)  | 
            ||
| 146 | cursor_historical = cnx_historical.cursor()  | 
            ||
| 147 | |||
| 148 | if equipment_id is not None:  | 
            ||
| 149 |             cursor_system.execute(" SELECT id, name, cost_center_id " | 
            ||
| 150 | " FROM tbl_equipments "  | 
            ||
| 151 | " WHERE id = %s ", (equipment_id,))  | 
            ||
| 152 | row_equipment = cursor_system.fetchone()  | 
            ||
| 153 | elif equipment_uuid is not None:  | 
            ||
| 154 |             cursor_system.execute(" SELECT id, name, cost_center_id " | 
            ||
| 155 | " FROM tbl_equipments "  | 
            ||
| 156 | " WHERE uuid = %s ", (equipment_uuid,))  | 
            ||
| 157 | row_equipment = cursor_system.fetchone()  | 
            ||
| 158 | |||
| 159 | if row_equipment is None:  | 
            ||
| 160 | if cursor_system:  | 
            ||
| 161 | cursor_system.close()  | 
            ||
| 162 | if cnx_system:  | 
            ||
| 163 | cnx_system.close()  | 
            ||
| 164 | |||
| 165 | if cursor_carbon:  | 
            ||
| 166 | cursor_carbon.close()  | 
            ||
| 167 | if cnx_carbon:  | 
            ||
| 168 | cnx_carbon.close()  | 
            ||
| 169 | |||
| 170 | if cursor_historical:  | 
            ||
| 171 | cursor_historical.close()  | 
            ||
| 172 | if cnx_historical:  | 
            ||
| 173 | cnx_historical.close()  | 
            ||
| 174 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.EQUIPMENT_NOT_FOUND')  | 
            ||
| 175 | |||
| 176 | equipment = dict()  | 
            ||
| 177 | equipment['id'] = row_equipment[0]  | 
            ||
| 178 | equipment['name'] = row_equipment[1]  | 
            ||
| 179 | equipment['cost_center_id'] = row_equipment[2]  | 
            ||
| 180 | |||
| 181 | ################################################################################################################  | 
            ||
| 182 | # Step 3: query energy categories  | 
            ||
| 183 | ################################################################################################################  | 
            ||
| 184 | energy_category_set = set()  | 
            ||
| 185 | # query energy categories in base period  | 
            ||
| 186 |         cursor_carbon.execute(" SELECT DISTINCT(energy_category_id) " | 
            ||
| 187 | " FROM tbl_equipment_input_category_hourly "  | 
            ||
| 188 | " WHERE equipment_id = %s "  | 
            ||
| 189 | " AND start_datetime_utc >= %s "  | 
            ||
| 190 | " AND start_datetime_utc < %s ",  | 
            ||
| 191 | (equipment['id'], base_start_datetime_utc, base_end_datetime_utc))  | 
            ||
| 192 | rows_energy_categories = cursor_carbon.fetchall()  | 
            ||
| 193 | if rows_energy_categories is not None or len(rows_energy_categories) > 0:  | 
            ||
| 194 | for row_energy_category in rows_energy_categories:  | 
            ||
| 195 | energy_category_set.add(row_energy_category[0])  | 
            ||
| 196 | |||
| 197 | # query energy categories in reporting period  | 
            ||
| 198 |         cursor_carbon.execute(" SELECT DISTINCT(energy_category_id) " | 
            ||
| 199 | " FROM tbl_equipment_input_category_hourly "  | 
            ||
| 200 | " WHERE equipment_id = %s "  | 
            ||
| 201 | " AND start_datetime_utc >= %s "  | 
            ||
| 202 | " AND start_datetime_utc < %s ",  | 
            ||
| 203 | (equipment['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))  | 
            ||
| 204 | rows_energy_categories = cursor_carbon.fetchall()  | 
            ||
| 205 | if rows_energy_categories is not None or len(rows_energy_categories) > 0:  | 
            ||
| 206 | for row_energy_category in rows_energy_categories:  | 
            ||
| 207 | energy_category_set.add(row_energy_category[0])  | 
            ||
| 208 | |||
| 209 | # query all energy categories in base period and reporting period  | 
            ||
| 210 |         cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " | 
            ||
| 211 | " FROM tbl_energy_categories "  | 
            ||
| 212 | " ORDER BY id ", )  | 
            ||
| 213 | rows_energy_categories = cursor_system.fetchall()  | 
            ||
| 214 | if rows_energy_categories is None or len(rows_energy_categories) == 0:  | 
            ||
| 215 | if cursor_system:  | 
            ||
| 216 | cursor_system.close()  | 
            ||
| 217 | if cnx_system:  | 
            ||
| 218 | cnx_system.close()  | 
            ||
| 219 | |||
| 220 | if cursor_carbon:  | 
            ||
| 221 | cursor_carbon.close()  | 
            ||
| 222 | if cnx_carbon:  | 
            ||
| 223 | cnx_carbon.close()  | 
            ||
| 224 | |||
| 225 | if cursor_historical:  | 
            ||
| 226 | cursor_historical.close()  | 
            ||
| 227 | if cnx_historical:  | 
            ||
| 228 | cnx_historical.close()  | 
            ||
| 229 | raise falcon.HTTPError(falcon.HTTP_404,  | 
            ||
| 230 | title='API.NOT_FOUND',  | 
            ||
| 231 | description='API.ENERGY_CATEGORY_NOT_FOUND')  | 
            ||
| 232 | energy_category_dict = dict()  | 
            ||
| 233 | for row_energy_category in rows_energy_categories:  | 
            ||
| 234 | if row_energy_category[0] in energy_category_set:  | 
            ||
| 235 |                 energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], | 
            ||
| 236 | "unit_of_measure": row_energy_category[2],  | 
            ||
| 237 | "kgce": row_energy_category[3],  | 
            ||
| 238 | "kgco2e": row_energy_category[4]}  | 
            ||
| 239 | |||
| 240 | ################################################################################################################  | 
            ||
| 241 | # Step 4: query associated points  | 
            ||
| 242 | ################################################################################################################  | 
            ||
| 243 | point_list = list()  | 
            ||
| 244 |         cursor_system.execute(" SELECT p.id, ep.name, p.units, p.object_type  " | 
            ||
| 245 | " FROM tbl_equipments e, tbl_equipments_parameters ep, tbl_points p "  | 
            ||
| 246 | " WHERE e.id = %s AND e.id = ep.equipment_id AND ep.parameter_type = 'point' "  | 
            ||
| 247 | " AND ep.point_id = p.id "  | 
            ||
| 248 | " ORDER BY p.id ", (equipment['id'],))  | 
            ||
| 249 | rows_points = cursor_system.fetchall()  | 
            ||
| 250 | if rows_points is not None and len(rows_points) > 0:  | 
            ||
| 251 | for row in rows_points:  | 
            ||
| 252 |                 point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) | 
            ||
| 253 | |||
| 254 | ################################################################################################################  | 
            ||
| 255 | # Step 5: query base period energy cost  | 
            ||
| 256 | ################################################################################################################  | 
            ||
| 257 | base = dict()  | 
            ||
| 258 | if energy_category_set is not None and len(energy_category_set) > 0:  | 
            ||
| 259 | for energy_category_id in energy_category_set:  | 
            ||
| 260 | base[energy_category_id] = dict()  | 
            ||
| 261 | base[energy_category_id]['timestamps'] = list()  | 
            ||
| 262 | base[energy_category_id]['values'] = list()  | 
            ||
| 263 | base[energy_category_id]['subtotal'] = Decimal(0.0)  | 
            ||
| 264 | |||
| 265 |                 cursor_carbon.execute(" SELECT start_datetime_utc, actual_value " | 
            ||
| 266 | " FROM tbl_equipment_input_category_hourly "  | 
            ||
| 267 | " WHERE equipment_id = %s "  | 
            ||
| 268 | " AND energy_category_id = %s "  | 
            ||
| 269 | " AND start_datetime_utc >= %s "  | 
            ||
| 270 | " AND start_datetime_utc < %s "  | 
            ||
| 271 | " ORDER BY start_datetime_utc ",  | 
            ||
| 272 | (equipment['id'],  | 
            ||
| 273 | energy_category_id,  | 
            ||
| 274 | base_start_datetime_utc,  | 
            ||
| 275 | base_end_datetime_utc))  | 
            ||
| 276 | rows_equipment_hourly = cursor_carbon.fetchall()  | 
            ||
| 277 | |||
| 278 | rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly,  | 
            ||
| 279 | base_start_datetime_utc,  | 
            ||
| 280 | base_end_datetime_utc,  | 
            ||
| 281 | period_type)  | 
            ||
| 282 | for row_equipment_periodically in rows_equipment_periodically:  | 
            ||
| 283 | current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \  | 
            ||
| 284 | timedelta(minutes=timezone_offset)  | 
            ||
| 285 | if period_type == 'hourly':  | 
            ||
| 286 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') | 
            ||
| 287 | elif period_type == 'daily':  | 
            ||
| 288 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%d') | 
            ||
| 289 | elif period_type == 'weekly':  | 
            ||
| 290 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%d') | 
            ||
| 291 | elif period_type == 'monthly':  | 
            ||
| 292 |                         current_datetime = current_datetime_local.strftime('%Y-%m') | 
            ||
| 293 | elif period_type == 'yearly':  | 
            ||
| 294 |                         current_datetime = current_datetime_local.strftime('%Y') | 
            ||
| 295 | |||
| 296 | actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \  | 
            ||
| 297 | else row_equipment_periodically[1]  | 
            ||
| 298 | base[energy_category_id]['timestamps'].append(current_datetime)  | 
            ||
| 299 | base[energy_category_id]['values'].append(actual_value)  | 
            ||
| 300 | base[energy_category_id]['subtotal'] += actual_value  | 
            ||
| 301 | |||
| 302 | ################################################################################################################  | 
            ||
| 303 | # Step 6: query reporting period energy cost  | 
            ||
| 304 | ################################################################################################################  | 
            ||
| 305 | reporting = dict()  | 
            ||
| 306 | if energy_category_set is not None and len(energy_category_set) > 0:  | 
            ||
| 307 | for energy_category_id in energy_category_set:  | 
            ||
| 308 | reporting[energy_category_id] = dict()  | 
            ||
| 309 | reporting[energy_category_id]['timestamps'] = list()  | 
            ||
| 310 | reporting[energy_category_id]['values'] = list()  | 
            ||
| 311 | reporting[energy_category_id]['subtotal'] = Decimal(0.0)  | 
            ||
| 312 | reporting[energy_category_id]['toppeak'] = Decimal(0.0)  | 
            ||
| 313 | reporting[energy_category_id]['onpeak'] = Decimal(0.0)  | 
            ||
| 314 | reporting[energy_category_id]['midpeak'] = Decimal(0.0)  | 
            ||
| 315 | reporting[energy_category_id]['offpeak'] = Decimal(0.0)  | 
            ||
| 316 | |||
| 317 |                 cursor_carbon.execute(" SELECT start_datetime_utc, actual_value " | 
            ||
| 318 | " FROM tbl_equipment_input_category_hourly "  | 
            ||
| 319 | " WHERE equipment_id = %s "  | 
            ||
| 320 | " AND energy_category_id = %s "  | 
            ||
| 321 | " AND start_datetime_utc >= %s "  | 
            ||
| 322 | " AND start_datetime_utc < %s "  | 
            ||
| 323 | " ORDER BY start_datetime_utc ",  | 
            ||
| 324 | (equipment['id'],  | 
            ||
| 325 | energy_category_id,  | 
            ||
| 326 | reporting_start_datetime_utc,  | 
            ||
| 327 | reporting_end_datetime_utc))  | 
            ||
| 328 | rows_equipment_hourly = cursor_carbon.fetchall()  | 
            ||
| 329 | |||
| 330 | rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly,  | 
            ||
| 331 | reporting_start_datetime_utc,  | 
            ||
| 332 | reporting_end_datetime_utc,  | 
            ||
| 333 | period_type)  | 
            ||
| 334 | for row_equipment_periodically in rows_equipment_periodically:  | 
            ||
| 335 | current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \  | 
            ||
| 336 | timedelta(minutes=timezone_offset)  | 
            ||
| 337 | if period_type == 'hourly':  | 
            ||
| 338 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') | 
            ||
| 339 | elif period_type == 'daily':  | 
            ||
| 340 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%d') | 
            ||
| 341 | elif period_type == 'weekly':  | 
            ||
| 342 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%d') | 
            ||
| 343 | elif period_type == 'monthly':  | 
            ||
| 344 |                         current_datetime = current_datetime_local.strftime('%Y-%m') | 
            ||
| 345 | elif period_type == 'yearly':  | 
            ||
| 346 |                         current_datetime = current_datetime_local.strftime('%Y') | 
            ||
| 347 | |||
| 348 | actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \  | 
            ||
| 349 | else row_equipment_periodically[1]  | 
            ||
| 350 | reporting[energy_category_id]['timestamps'].append(current_datetime)  | 
            ||
| 351 | reporting[energy_category_id]['values'].append(actual_value)  | 
            ||
| 352 | reporting[energy_category_id]['subtotal'] += actual_value  | 
            ||
| 353 | |||
| 354 | energy_category_tariff_dict = utilities.get_energy_category_peak_types(equipment['cost_center_id'],  | 
            ||
| 355 | energy_category_id,  | 
            ||
| 356 | reporting_start_datetime_utc,  | 
            ||
| 357 | reporting_end_datetime_utc)  | 
            ||
| 358 | for row in rows_equipment_hourly:  | 
            ||
| 359 | peak_type = energy_category_tariff_dict.get(row[0], None)  | 
            ||
| 360 | if peak_type == 'toppeak':  | 
            ||
| 361 | reporting[energy_category_id]['toppeak'] += row[1]  | 
            ||
| 362 | elif peak_type == 'onpeak':  | 
            ||
| 363 | reporting[energy_category_id]['onpeak'] += row[1]  | 
            ||
| 364 | elif peak_type == 'midpeak':  | 
            ||
| 365 | reporting[energy_category_id]['midpeak'] += row[1]  | 
            ||
| 366 | elif peak_type == 'offpeak':  | 
            ||
| 367 | reporting[energy_category_id]['offpeak'] += row[1]  | 
            ||
| 368 | |||
| 369 | ################################################################################################################  | 
            ||
| 370 | # Step 7: query tariff data  | 
            ||
| 371 | ################################################################################################################  | 
            ||
| 372 | parameters_data = dict()  | 
            ||
| 373 | parameters_data['names'] = list()  | 
            ||
| 374 | parameters_data['timestamps'] = list()  | 
            ||
| 375 | parameters_data['values'] = list()  | 
            ||
| 376 | if energy_category_set is not None and len(energy_category_set) > 0:  | 
            ||
| 377 | for energy_category_id in energy_category_set:  | 
            ||
| 378 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(equipment['cost_center_id'],  | 
            ||
| 379 | energy_category_id,  | 
            ||
| 380 | reporting_start_datetime_utc,  | 
            ||
| 381 | reporting_end_datetime_utc)  | 
            ||
| 382 | tariff_timestamp_list = list()  | 
            ||
| 383 | tariff_value_list = list()  | 
            ||
| 384 | for k, v in energy_category_tariff_dict.items():  | 
            ||
| 385 | # convert k from utc to local  | 
            ||
| 386 | k = k + timedelta(minutes=timezone_offset)  | 
            ||
| 387 | tariff_timestamp_list.append(k.isoformat()[0:19][0:19])  | 
            ||
| 388 | tariff_value_list.append(v)  | 
            ||
| 389 | |||
| 390 |                 parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name']) | 
            ||
| 391 | parameters_data['timestamps'].append(tariff_timestamp_list)  | 
            ||
| 392 | parameters_data['values'].append(tariff_value_list)  | 
            ||
| 393 | |||
| 394 | ################################################################################################################  | 
            ||
| 395 | # Step 8: query associated points data  | 
            ||
| 396 | ################################################################################################################  | 
            ||
| 397 | for point in point_list:  | 
            ||
| 398 | point_values = []  | 
            ||
| 399 | point_timestamps = []  | 
            ||
| 400 | if point['object_type'] == 'ANALOG_VALUE':  | 
            ||
| 401 |                 query = (" SELECT utc_date_time, actual_value " | 
            ||
| 402 | " FROM tbl_analog_value "  | 
            ||
| 403 | " WHERE point_id = %s "  | 
            ||
| 404 | " AND utc_date_time BETWEEN %s AND %s "  | 
            ||
| 405 | " ORDER BY utc_date_time ")  | 
            ||
| 406 | cursor_historical.execute(query, (point['id'],  | 
            ||
| 407 | reporting_start_datetime_utc,  | 
            ||
| 408 | reporting_end_datetime_utc))  | 
            ||
| 409 | rows = cursor_historical.fetchall()  | 
            ||
| 410 | |||
| 411 | if rows is not None and len(rows) > 0:  | 
            ||
| 412 | for row in rows:  | 
            ||
| 413 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \  | 
            ||
| 414 | timedelta(minutes=timezone_offset)  | 
            ||
| 415 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') | 
            ||
| 416 | point_timestamps.append(current_datetime)  | 
            ||
| 417 | point_values.append(row[1])  | 
            ||
| 418 | |||
| 419 | elif point['object_type'] == 'ENERGY_VALUE':  | 
            ||
| 420 |                 query = (" SELECT utc_date_time, actual_value " | 
            ||
| 421 | " FROM tbl_energy_value "  | 
            ||
| 422 | " WHERE point_id = %s "  | 
            ||
| 423 | " AND utc_date_time BETWEEN %s AND %s "  | 
            ||
| 424 | " ORDER BY utc_date_time ")  | 
            ||
| 425 | cursor_historical.execute(query, (point['id'],  | 
            ||
| 426 | reporting_start_datetime_utc,  | 
            ||
| 427 | reporting_end_datetime_utc))  | 
            ||
| 428 | rows = cursor_historical.fetchall()  | 
            ||
| 429 | |||
| 430 | if rows is not None and len(rows) > 0:  | 
            ||
| 431 | for row in rows:  | 
            ||
| 432 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \  | 
            ||
| 433 | timedelta(minutes=timezone_offset)  | 
            ||
| 434 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') | 
            ||
| 435 | point_timestamps.append(current_datetime)  | 
            ||
| 436 | point_values.append(row[1])  | 
            ||
| 437 | elif point['object_type'] == 'DIGITAL_VALUE':  | 
            ||
| 438 |                 query = (" SELECT utc_date_time, actual_value " | 
            ||
| 439 | " FROM tbl_digital_value "  | 
            ||
| 440 | " WHERE point_id = %s "  | 
            ||
| 441 | " AND utc_date_time BETWEEN %s AND %s "  | 
            ||
| 442 | " ORDER BY utc_date_time ")  | 
            ||
| 443 | cursor_historical.execute(query, (point['id'],  | 
            ||
| 444 | reporting_start_datetime_utc,  | 
            ||
| 445 | reporting_end_datetime_utc))  | 
            ||
| 446 | rows = cursor_historical.fetchall()  | 
            ||
| 447 | |||
| 448 | if rows is not None and len(rows) > 0:  | 
            ||
| 449 | for row in rows:  | 
            ||
| 450 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \  | 
            ||
| 451 | timedelta(minutes=timezone_offset)  | 
            ||
| 452 |                         current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') | 
            ||
| 453 | point_timestamps.append(current_datetime)  | 
            ||
| 454 | point_values.append(row[1])  | 
            ||
| 455 | |||
| 456 |             parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') | 
            ||
| 457 | parameters_data['timestamps'].append(point_timestamps)  | 
            ||
| 458 | parameters_data['values'].append(point_values)  | 
            ||
| 459 | |||
| 460 | ################################################################################################################  | 
            ||
| 461 | # Step 9: construct the report  | 
            ||
| 462 | ################################################################################################################  | 
            ||
| 463 | if cursor_system:  | 
            ||
| 464 | cursor_system.close()  | 
            ||
| 465 | if cnx_system:  | 
            ||
| 466 | cnx_system.close()  | 
            ||
| 467 | |||
| 468 | if cursor_carbon:  | 
            ||
| 469 | cursor_carbon.close()  | 
            ||
| 470 | if cnx_carbon:  | 
            ||
| 471 | cnx_carbon.close()  | 
            ||
| 472 | |||
| 473 | if cursor_historical:  | 
            ||
| 474 | cursor_historical.close()  | 
            ||
| 475 | if cnx_historical:  | 
            ||
| 476 | cnx_historical.close()  | 
            ||
| 477 | |||
| 478 | result = dict()  | 
            ||
| 479 | |||
| 480 | result['equipment'] = dict()  | 
            ||
| 481 | result['equipment']['name'] = equipment['name']  | 
            ||
| 482 | |||
| 483 | result['base_period'] = dict()  | 
            ||
| 484 | result['base_period']['names'] = list()  | 
            ||
| 485 | result['base_period']['units'] = list()  | 
            ||
| 486 | result['base_period']['timestamps'] = list()  | 
            ||
| 487 | result['base_period']['values'] = list()  | 
            ||
| 488 | result['base_period']['subtotals'] = list()  | 
            ||
| 489 | result['base_period']['total'] = Decimal(0.0)  | 
            ||
| 490 | if energy_category_set is not None and len(energy_category_set) > 0:  | 
            ||
| 491 | for energy_category_id in energy_category_set:  | 
            ||
| 492 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name'])  | 
            ||
| 493 |                 result['base_period']['units'].append('KG') | 
            ||
| 494 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps'])  | 
            ||
| 495 | result['base_period']['values'].append(base[energy_category_id]['values'])  | 
            ||
| 496 | result['base_period']['subtotals'].append(base[energy_category_id]['subtotal'])  | 
            ||
| 497 | result['base_period']['total'] += base[energy_category_id]['subtotal']  | 
            ||
| 498 | |||
| 499 | result['reporting_period'] = dict()  | 
            ||
| 500 | result['reporting_period']['names'] = list()  | 
            ||
| 501 | result['reporting_period']['energy_category_ids'] = list()  | 
            ||
| 502 | result['reporting_period']['units'] = list()  | 
            ||
| 503 | result['reporting_period']['timestamps'] = list()  | 
            ||
| 504 | result['reporting_period']['values'] = list()  | 
            ||
| 505 | result['reporting_period']['subtotals'] = list()  | 
            ||
| 506 | result['reporting_period']['toppeaks'] = list()  | 
            ||
| 507 | result['reporting_period']['onpeaks'] = list()  | 
            ||
| 508 | result['reporting_period']['midpeaks'] = list()  | 
            ||
| 509 | result['reporting_period']['offpeaks'] = list()  | 
            ||
| 510 | result['reporting_period']['increment_rates'] = list()  | 
            ||
| 511 | result['reporting_period']['total'] = Decimal(0.0)  | 
            ||
| 512 | result['reporting_period']['total_increment_rate'] = Decimal(0.0)  | 
            ||
| 513 | result['reporting_period']['total_unit'] = 'KG'  | 
            ||
| 514 | |||
| 515 | if energy_category_set is not None and len(energy_category_set) > 0:  | 
            ||
| 516 | for energy_category_id in energy_category_set:  | 
            ||
| 517 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name'])  | 
            ||
| 518 | result['reporting_period']['energy_category_ids'].append(energy_category_id)  | 
            ||
| 519 |                 result['reporting_period']['units'].append('KG') | 
            ||
| 520 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps'])  | 
            ||
| 521 | result['reporting_period']['values'].append(reporting[energy_category_id]['values'])  | 
            ||
| 522 | result['reporting_period']['subtotals'].append(reporting[energy_category_id]['subtotal'])  | 
            ||
| 523 | result['reporting_period']['toppeaks'].append(reporting[energy_category_id]['toppeak'])  | 
            ||
| 524 | result['reporting_period']['onpeaks'].append(reporting[energy_category_id]['onpeak'])  | 
            ||
| 525 | result['reporting_period']['midpeaks'].append(reporting[energy_category_id]['midpeak'])  | 
            ||
| 526 | result['reporting_period']['offpeaks'].append(reporting[energy_category_id]['offpeak'])  | 
            ||
| 527 | result['reporting_period']['increment_rates'].append(  | 
            ||
| 528 | (reporting[energy_category_id]['subtotal'] - base[energy_category_id]['subtotal']) /  | 
            ||
| 529 | base[energy_category_id]['subtotal']  | 
            ||
| 530 | if base[energy_category_id]['subtotal'] > 0.0 else None)  | 
            ||
| 531 | result['reporting_period']['total'] += reporting[energy_category_id]['subtotal']  | 
            ||
| 532 | |||
| 533 | result['reporting_period']['total_increment_rate'] = \  | 
            ||
| 534 | (result['reporting_period']['total'] - result['base_period']['total']) / \  | 
            ||
| 535 | result['base_period']['total'] \  | 
            ||
| 536 | if result['base_period']['total'] > Decimal(0.0) else None  | 
            ||
| 537 | |||
| 538 |         result['parameters'] = { | 
            ||
| 539 | "names": parameters_data['names'],  | 
            ||
| 540 | "timestamps": parameters_data['timestamps'],  | 
            ||
| 541 | "values": parameters_data['values']  | 
            ||
| 542 | }  | 
            ||
| 543 | result['excel_bytes_base64'] = excelexporters.equipmentcost.export(result,  | 
            ||
| 544 | equipment['name'],  | 
            ||
| 545 | reporting_start_datetime_local,  | 
            ||
| 546 | reporting_end_datetime_local,  | 
            ||
| 547 | period_type)  | 
            ||
| 548 | resp.text = json.dumps(result)  | 
            ||
| 549 |