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