Total Complexity | 117 |
Total Lines | 598 |
Duplicated Lines | 2.68 % |
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.spacecost 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.spacecost |
||
9 | |||
10 | |||
11 | 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 space |
||
24 | # Step 3: query energy categories |
||
25 | # Step 4: query associated sensors |
||
26 | # Step 5: query associated points |
||
27 | # Step 6: query child spaces |
||
28 | # Step 7: query base period energy cost |
||
29 | # Step 8: query reporting period energy cost |
||
30 | # Step 9: query tariff data |
||
31 | # Step 10: query associated sensors and points data |
||
32 | # Step 11: query child spaces energy cost |
||
33 | # Step 12: construct the report |
||
34 | #################################################################################################################### |
||
35 | @staticmethod |
||
36 | def on_get(req, resp): |
||
37 | print(req.params) |
||
38 | space_id = req.params.get('spaceid') |
||
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 space_id is None: |
||
49 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') |
||
50 | else: |
||
51 | space_id = str.strip(space_id) |
||
52 | if not space_id.isdigit() or int(space_id) <= 0: |
||
53 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') |
||
54 | |||
55 | if period_type is None: |
||
56 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
57 | else: |
||
58 | period_type = str.strip(period_type) |
||
59 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
||
60 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
61 | |||
62 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
63 | if config.utc_offset[0] == '-': |
||
64 | timezone_offset = -timezone_offset |
||
65 | |||
66 | base_start_datetime_utc = None |
||
67 | if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0: |
||
68 | base_start_datetime_local = str.strip(base_start_datetime_local) |
||
69 | try: |
||
70 | base_start_datetime_utc = datetime.strptime(base_start_datetime_local, |
||
71 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
72 | timedelta(minutes=timezone_offset) |
||
73 | except ValueError: |
||
74 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
75 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
||
76 | |||
77 | base_end_datetime_utc = None |
||
78 | if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0: |
||
79 | base_end_datetime_local = str.strip(base_end_datetime_local) |
||
80 | try: |
||
81 | base_end_datetime_utc = datetime.strptime(base_end_datetime_local, |
||
82 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
83 | timedelta(minutes=timezone_offset) |
||
84 | except ValueError: |
||
85 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
86 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
||
87 | |||
88 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
||
89 | base_start_datetime_utc >= base_end_datetime_utc: |
||
90 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
91 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
||
92 | |||
93 | if reporting_start_datetime_local is None: |
||
94 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
95 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
||
96 | else: |
||
97 | reporting_start_datetime_local = str.strip(reporting_start_datetime_local) |
||
98 | try: |
||
99 | reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local, |
||
100 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
101 | timedelta(minutes=timezone_offset) |
||
102 | except ValueError: |
||
103 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
104 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
||
105 | |||
106 | if reporting_end_datetime_local is None: |
||
107 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
108 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
||
109 | else: |
||
110 | reporting_end_datetime_local = str.strip(reporting_end_datetime_local) |
||
111 | try: |
||
112 | reporting_end_datetime_utc = datetime.strptime(reporting_end_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_END_DATETIME") |
||
118 | |||
119 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
||
120 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
121 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
||
122 | |||
123 | ################################################################################################################ |
||
124 | # Step 2: query the space |
||
125 | ################################################################################################################ |
||
126 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
||
127 | cursor_system = cnx_system.cursor() |
||
128 | |||
129 | cnx_billing = mysql.connector.connect(**config.myems_billing_db) |
||
130 | cursor_billing = cnx_billing.cursor() |
||
131 | |||
132 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
||
133 | cursor_historical = cnx_historical.cursor() |
||
134 | |||
135 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
||
136 | " FROM tbl_spaces " |
||
137 | " WHERE id = %s ", (space_id,)) |
||
138 | row_space = cursor_system.fetchone() |
||
139 | View Code Duplication | if row_space is None: |
|
|
|||
140 | if cursor_system: |
||
141 | cursor_system.close() |
||
142 | if cnx_system: |
||
143 | cnx_system.disconnect() |
||
144 | |||
145 | if cursor_billing: |
||
146 | cursor_billing.close() |
||
147 | if cnx_billing: |
||
148 | cnx_billing.disconnect() |
||
149 | |||
150 | if cnx_historical: |
||
151 | cnx_historical.close() |
||
152 | if cursor_historical: |
||
153 | cursor_historical.disconnect() |
||
154 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.SPACE_NOT_FOUND') |
||
155 | |||
156 | space = dict() |
||
157 | space['id'] = row_space[0] |
||
158 | space['name'] = row_space[1] |
||
159 | space['area'] = row_space[2] |
||
160 | space['cost_center_id'] = row_space[3] |
||
161 | |||
162 | ################################################################################################################ |
||
163 | # Step 3: query energy categories |
||
164 | ################################################################################################################ |
||
165 | energy_category_set = set() |
||
166 | # query energy categories in base period |
||
167 | cursor_billing.execute(" SELECT DISTINCT(energy_category_id) " |
||
168 | " FROM tbl_space_input_category_hourly " |
||
169 | " WHERE space_id = %s " |
||
170 | " AND start_datetime_utc >= %s " |
||
171 | " AND start_datetime_utc < %s ", |
||
172 | (space['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
173 | rows_energy_categories = cursor_billing.fetchall() |
||
174 | if rows_energy_categories is not None or len(rows_energy_categories) > 0: |
||
175 | for row_energy_category in rows_energy_categories: |
||
176 | energy_category_set.add(row_energy_category[0]) |
||
177 | |||
178 | # query energy categories in reporting period |
||
179 | cursor_billing.execute(" SELECT DISTINCT(energy_category_id) " |
||
180 | " FROM tbl_space_input_category_hourly " |
||
181 | " WHERE space_id = %s " |
||
182 | " AND start_datetime_utc >= %s " |
||
183 | " AND start_datetime_utc < %s ", |
||
184 | (space['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
185 | rows_energy_categories = cursor_billing.fetchall() |
||
186 | if rows_energy_categories is not None or len(rows_energy_categories) > 0: |
||
187 | for row_energy_category in rows_energy_categories: |
||
188 | energy_category_set.add(row_energy_category[0]) |
||
189 | |||
190 | # query all energy categories in base period and reporting period |
||
191 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
||
192 | " FROM tbl_energy_categories " |
||
193 | " ORDER BY id ", ) |
||
194 | rows_energy_categories = cursor_system.fetchall() |
||
195 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
||
196 | if cursor_system: |
||
197 | cursor_system.close() |
||
198 | if cnx_system: |
||
199 | cnx_system.disconnect() |
||
200 | |||
201 | if cursor_billing: |
||
202 | cursor_billing.close() |
||
203 | if cnx_billing: |
||
204 | cnx_billing.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_CATEGORY_NOT_FOUND') |
||
213 | energy_category_dict = dict() |
||
214 | for row_energy_category in rows_energy_categories: |
||
215 | if row_energy_category[0] in energy_category_set: |
||
216 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
||
217 | "unit_of_measure": row_energy_category[2], |
||
218 | "kgce": row_energy_category[3], |
||
219 | "kgco2e": row_energy_category[4]} |
||
220 | |||
221 | ################################################################################################################ |
||
222 | # Step 4: query associated sensors |
||
223 | ################################################################################################################ |
||
224 | point_list = list() |
||
225 | cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type " |
||
226 | " FROM tbl_spaces sp, tbl_sensors se, tbl_spaces_sensors spse, " |
||
227 | " tbl_points po, tbl_sensors_points sepo " |
||
228 | " WHERE sp.id = %s AND sp.id = spse.space_id AND spse.sensor_id = se.id " |
||
229 | " AND se.id = sepo.sensor_id AND sepo.point_id = po.id " |
||
230 | " ORDER BY po.id ", (space['id'], )) |
||
231 | rows_points = cursor_system.fetchall() |
||
232 | if rows_points is not None and len(rows_points) > 0: |
||
233 | for row in rows_points: |
||
234 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
||
235 | |||
236 | ################################################################################################################ |
||
237 | # Step 5: query associated points |
||
238 | ################################################################################################################ |
||
239 | cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type " |
||
240 | " FROM tbl_spaces sp, tbl_spaces_points sppo, tbl_points po " |
||
241 | " WHERE sp.id = %s AND sp.id = sppo.space_id AND sppo.point_id = po.id " |
||
242 | " ORDER BY po.id ", (space['id'], )) |
||
243 | rows_points = cursor_system.fetchall() |
||
244 | if rows_points is not None and len(rows_points) > 0: |
||
245 | for row in rows_points: |
||
246 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
||
247 | |||
248 | ################################################################################################################ |
||
249 | # Step 6: query child spaces |
||
250 | ################################################################################################################ |
||
251 | child_space_list = list() |
||
252 | cursor_system.execute(" SELECT id, name " |
||
253 | " FROM tbl_spaces " |
||
254 | " WHERE parent_space_id = %s " |
||
255 | " ORDER BY id ", (space['id'], )) |
||
256 | rows_child_spaces = cursor_system.fetchall() |
||
257 | if rows_child_spaces is not None and len(rows_child_spaces) > 0: |
||
258 | for row in rows_child_spaces: |
||
259 | child_space_list.append({"id": row[0], "name": row[1]}) |
||
260 | |||
261 | ################################################################################################################ |
||
262 | # Step 7: query base period energy cost |
||
263 | ################################################################################################################ |
||
264 | base = dict() |
||
265 | if energy_category_set is not None and len(energy_category_set) > 0: |
||
266 | for energy_category_id in energy_category_set: |
||
267 | base[energy_category_id] = dict() |
||
268 | base[energy_category_id]['timestamps'] = list() |
||
269 | base[energy_category_id]['values'] = list() |
||
270 | base[energy_category_id]['subtotal'] = Decimal(0.0) |
||
271 | |||
272 | cursor_billing.execute(" SELECT start_datetime_utc, actual_value " |
||
273 | " FROM tbl_space_input_category_hourly " |
||
274 | " WHERE space_id = %s " |
||
275 | " AND energy_category_id = %s " |
||
276 | " AND start_datetime_utc >= %s " |
||
277 | " AND start_datetime_utc < %s " |
||
278 | " ORDER BY start_datetime_utc ", |
||
279 | (space['id'], |
||
280 | energy_category_id, |
||
281 | base_start_datetime_utc, |
||
282 | base_end_datetime_utc)) |
||
283 | rows_space_hourly = cursor_billing.fetchall() |
||
284 | |||
285 | rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly, |
||
286 | base_start_datetime_utc, |
||
287 | base_end_datetime_utc, |
||
288 | period_type) |
||
289 | for row_space_periodically in rows_space_periodically: |
||
290 | current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
291 | timedelta(minutes=timezone_offset) |
||
292 | if period_type == 'hourly': |
||
293 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
294 | elif period_type == 'daily': |
||
295 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
296 | elif period_type == 'monthly': |
||
297 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
298 | elif period_type == 'yearly': |
||
299 | current_datetime = current_datetime_local.strftime('%Y') |
||
300 | |||
301 | actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1] |
||
302 | base[energy_category_id]['timestamps'].append(current_datetime) |
||
303 | base[energy_category_id]['values'].append(actual_value) |
||
304 | base[energy_category_id]['subtotal'] += actual_value |
||
305 | |||
306 | ################################################################################################################ |
||
307 | # Step 8: query reporting period energy cost |
||
308 | ################################################################################################################ |
||
309 | reporting = dict() |
||
310 | if energy_category_set is not None and len(energy_category_set) > 0: |
||
311 | for energy_category_id in energy_category_set: |
||
312 | reporting[energy_category_id] = dict() |
||
313 | reporting[energy_category_id]['timestamps'] = list() |
||
314 | reporting[energy_category_id]['values'] = list() |
||
315 | reporting[energy_category_id]['subtotal'] = Decimal(0.0) |
||
316 | reporting[energy_category_id]['toppeak'] = Decimal(0.0) |
||
317 | reporting[energy_category_id]['onpeak'] = Decimal(0.0) |
||
318 | reporting[energy_category_id]['midpeak'] = Decimal(0.0) |
||
319 | reporting[energy_category_id]['offpeak'] = Decimal(0.0) |
||
320 | |||
321 | cursor_billing.execute(" SELECT start_datetime_utc, actual_value " |
||
322 | " FROM tbl_space_input_category_hourly " |
||
323 | " WHERE space_id = %s " |
||
324 | " AND energy_category_id = %s " |
||
325 | " AND start_datetime_utc >= %s " |
||
326 | " AND start_datetime_utc < %s " |
||
327 | " ORDER BY start_datetime_utc ", |
||
328 | (space['id'], |
||
329 | energy_category_id, |
||
330 | reporting_start_datetime_utc, |
||
331 | reporting_end_datetime_utc)) |
||
332 | rows_space_hourly = cursor_billing.fetchall() |
||
333 | |||
334 | rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly, |
||
335 | reporting_start_datetime_utc, |
||
336 | reporting_end_datetime_utc, |
||
337 | period_type) |
||
338 | for row_space_periodically in rows_space_periodically: |
||
339 | current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
340 | timedelta(minutes=timezone_offset) |
||
341 | if period_type == 'hourly': |
||
342 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
343 | elif period_type == 'daily': |
||
344 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
345 | elif period_type == 'monthly': |
||
346 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
347 | elif period_type == 'yearly': |
||
348 | current_datetime = current_datetime_local.strftime('%Y') |
||
349 | |||
350 | actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1] |
||
351 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
||
352 | reporting[energy_category_id]['values'].append(actual_value) |
||
353 | reporting[energy_category_id]['subtotal'] += actual_value |
||
354 | |||
355 | energy_category_tariff_dict = utilities.get_energy_category_peak_types(space['cost_center_id'], |
||
356 | energy_category_id, |
||
357 | reporting_start_datetime_utc, |
||
358 | reporting_end_datetime_utc) |
||
359 | for row in rows_space_hourly: |
||
360 | peak_type = energy_category_tariff_dict.get(row[0], None) |
||
361 | if peak_type == 'toppeak': |
||
362 | reporting[energy_category_id]['toppeak'] += row[1] |
||
363 | elif peak_type == 'onpeak': |
||
364 | reporting[energy_category_id]['onpeak'] += row[1] |
||
365 | elif peak_type == 'midpeak': |
||
366 | reporting[energy_category_id]['midpeak'] += row[1] |
||
367 | elif peak_type == 'offpeak': |
||
368 | reporting[energy_category_id]['offpeak'] += row[1] |
||
369 | |||
370 | ################################################################################################################ |
||
371 | # Step 9: query tariff data |
||
372 | ################################################################################################################ |
||
373 | parameters_data = dict() |
||
374 | parameters_data['names'] = list() |
||
375 | parameters_data['timestamps'] = list() |
||
376 | parameters_data['values'] = list() |
||
377 | if energy_category_set is not None and len(energy_category_set) > 0: |
||
378 | for energy_category_id in energy_category_set: |
||
379 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(space['cost_center_id'], |
||
380 | energy_category_id, |
||
381 | reporting_start_datetime_utc, |
||
382 | reporting_end_datetime_utc) |
||
383 | tariff_timestamp_list = list() |
||
384 | tariff_value_list = list() |
||
385 | for k, v in energy_category_tariff_dict.items(): |
||
386 | # convert k from utc to local |
||
387 | k = k + timedelta(minutes=timezone_offset) |
||
388 | tariff_timestamp_list.append(k.isoformat()[0:19][0:19]) |
||
389 | tariff_value_list.append(v) |
||
390 | |||
391 | parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name']) |
||
392 | parameters_data['timestamps'].append(tariff_timestamp_list) |
||
393 | parameters_data['values'].append(tariff_value_list) |
||
394 | |||
395 | ################################################################################################################ |
||
396 | # Step 10: query associated sensors and points data |
||
397 | ################################################################################################################ |
||
398 | for point in point_list: |
||
399 | point_values = [] |
||
400 | point_timestamps = [] |
||
401 | if point['object_type'] == 'ANALOG_VALUE': |
||
402 | query = (" SELECT utc_date_time, actual_value " |
||
403 | " FROM tbl_analog_value " |
||
404 | " WHERE point_id = %s " |
||
405 | " AND utc_date_time BETWEEN %s AND %s " |
||
406 | " ORDER BY utc_date_time ") |
||
407 | cursor_historical.execute(query, (point['id'], |
||
408 | reporting_start_datetime_utc, |
||
409 | reporting_end_datetime_utc)) |
||
410 | rows = cursor_historical.fetchall() |
||
411 | |||
412 | if rows is not None and len(rows) > 0: |
||
413 | for row in rows: |
||
414 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
415 | timedelta(minutes=timezone_offset) |
||
416 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
417 | point_timestamps.append(current_datetime) |
||
418 | point_values.append(row[1]) |
||
419 | |||
420 | elif point['object_type'] == 'ENERGY_VALUE': |
||
421 | query = (" SELECT utc_date_time, actual_value " |
||
422 | " FROM tbl_energy_value " |
||
423 | " WHERE point_id = %s " |
||
424 | " AND utc_date_time BETWEEN %s AND %s " |
||
425 | " ORDER BY utc_date_time ") |
||
426 | cursor_historical.execute(query, (point['id'], |
||
427 | reporting_start_datetime_utc, |
||
428 | reporting_end_datetime_utc)) |
||
429 | rows = cursor_historical.fetchall() |
||
430 | |||
431 | if rows is not None and len(rows) > 0: |
||
432 | for row in rows: |
||
433 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
434 | timedelta(minutes=timezone_offset) |
||
435 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
436 | point_timestamps.append(current_datetime) |
||
437 | point_values.append(row[1]) |
||
438 | elif point['object_type'] == 'DIGITAL_VALUE': |
||
439 | query = (" SELECT utc_date_time, actual_value " |
||
440 | " FROM tbl_digital_value " |
||
441 | " WHERE point_id = %s " |
||
442 | " AND utc_date_time BETWEEN %s AND %s ") |
||
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 11: query child spaces energy cost |
||
462 | ################################################################################################################ |
||
463 | child_space_data = dict() |
||
464 | |||
465 | if energy_category_set is not None and len(energy_category_set) > 0: |
||
466 | for energy_category_id in energy_category_set: |
||
467 | child_space_data[energy_category_id] = dict() |
||
468 | child_space_data[energy_category_id]['child_space_names'] = list() |
||
469 | child_space_data[energy_category_id]['subtotals'] = list() |
||
470 | for child_space in child_space_list: |
||
471 | child_space_data[energy_category_id]['child_space_names'].append(child_space['name']) |
||
472 | |||
473 | cursor_billing.execute(" SELECT SUM(actual_value) " |
||
474 | " FROM tbl_space_input_category_hourly " |
||
475 | " WHERE space_id = %s " |
||
476 | " AND energy_category_id = %s " |
||
477 | " AND start_datetime_utc >= %s " |
||
478 | " AND start_datetime_utc < %s " |
||
479 | " ORDER BY start_datetime_utc ", |
||
480 | (child_space['id'], |
||
481 | energy_category_id, |
||
482 | reporting_start_datetime_utc, |
||
483 | reporting_end_datetime_utc)) |
||
484 | row_subtotal = cursor_billing.fetchone() |
||
485 | |||
486 | subtotal = Decimal(0.0) if (row_subtotal is None or row_subtotal[0] is None) else row_subtotal[0] |
||
487 | child_space_data[energy_category_id]['subtotals'].append(subtotal) |
||
488 | |||
489 | ################################################################################################################ |
||
490 | # Step 12: construct the report |
||
491 | ################################################################################################################ |
||
492 | if cursor_system: |
||
493 | cursor_system.close() |
||
494 | if cnx_system: |
||
495 | cnx_system.disconnect() |
||
496 | |||
497 | if cursor_billing: |
||
498 | cursor_billing.close() |
||
499 | if cnx_billing: |
||
500 | cnx_billing.disconnect() |
||
501 | |||
502 | result = dict() |
||
503 | |||
504 | result['space'] = dict() |
||
505 | result['space']['name'] = space['name'] |
||
506 | result['space']['area'] = space['area'] |
||
507 | |||
508 | result['base_period'] = dict() |
||
509 | result['base_period']['names'] = list() |
||
510 | result['base_period']['units'] = list() |
||
511 | result['base_period']['timestamps'] = list() |
||
512 | result['base_period']['values'] = list() |
||
513 | result['base_period']['subtotals'] = list() |
||
514 | result['base_period']['total'] = Decimal(0.0) |
||
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['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
||
518 | result['base_period']['units'].append(config.currency_unit) |
||
519 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
||
520 | result['base_period']['values'].append(base[energy_category_id]['values']) |
||
521 | result['base_period']['subtotals'].append(base[energy_category_id]['subtotal']) |
||
522 | result['base_period']['total'] += base[energy_category_id]['subtotal'] |
||
523 | |||
524 | result['reporting_period'] = dict() |
||
525 | result['reporting_period']['names'] = list() |
||
526 | result['reporting_period']['energy_category_ids'] = list() |
||
527 | result['reporting_period']['units'] = list() |
||
528 | result['reporting_period']['timestamps'] = list() |
||
529 | result['reporting_period']['values'] = list() |
||
530 | result['reporting_period']['subtotals'] = list() |
||
531 | result['reporting_period']['subtotals_per_unit_area'] = list() |
||
532 | result['reporting_period']['toppeaks'] = list() |
||
533 | result['reporting_period']['onpeaks'] = list() |
||
534 | result['reporting_period']['midpeaks'] = list() |
||
535 | result['reporting_period']['offpeaks'] = list() |
||
536 | result['reporting_period']['increment_rates'] = list() |
||
537 | result['reporting_period']['total'] = Decimal(0.0) |
||
538 | result['reporting_period']['total_per_unit_area'] = Decimal(0.0) |
||
539 | result['reporting_period']['total_increment_rate'] = Decimal(0.0) |
||
540 | result['reporting_period']['total_unit'] = config.currency_unit |
||
541 | |||
542 | if energy_category_set is not None and len(energy_category_set) > 0: |
||
543 | for energy_category_id in energy_category_set: |
||
544 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
||
545 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
||
546 | result['reporting_period']['units'].append(config.currency_unit) |
||
547 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
||
548 | result['reporting_period']['values'].append(reporting[energy_category_id]['values']) |
||
549 | result['reporting_period']['subtotals'].append(reporting[energy_category_id]['subtotal']) |
||
550 | result['reporting_period']['subtotals_per_unit_area'].append( |
||
551 | reporting[energy_category_id]['subtotal'] / space['area'] if space['area'] > 0.0 else None) |
||
552 | result['reporting_period']['toppeaks'].append(reporting[energy_category_id]['toppeak']) |
||
553 | result['reporting_period']['onpeaks'].append(reporting[energy_category_id]['onpeak']) |
||
554 | result['reporting_period']['midpeaks'].append(reporting[energy_category_id]['midpeak']) |
||
555 | result['reporting_period']['offpeaks'].append(reporting[energy_category_id]['offpeak']) |
||
556 | result['reporting_period']['increment_rates'].append( |
||
557 | (reporting[energy_category_id]['subtotal'] - base[energy_category_id]['subtotal']) / |
||
558 | base[energy_category_id]['subtotal'] |
||
559 | if base[energy_category_id]['subtotal'] > 0.0 else None) |
||
560 | result['reporting_period']['total'] += reporting[energy_category_id]['subtotal'] |
||
561 | |||
562 | result['reporting_period']['total_per_unit_area'] = \ |
||
563 | result['reporting_period']['total'] / space['area'] if space['area'] > 0.0 else None |
||
564 | |||
565 | result['reporting_period']['total_increment_rate'] = \ |
||
566 | (result['reporting_period']['total'] - result['base_period']['total']) / \ |
||
567 | result['base_period']['total'] \ |
||
568 | if result['base_period']['total'] > Decimal(0.0) else None |
||
569 | |||
570 | result['parameters'] = { |
||
571 | "names": parameters_data['names'], |
||
572 | "timestamps": parameters_data['timestamps'], |
||
573 | "values": parameters_data['values'] |
||
574 | } |
||
575 | |||
576 | result['child_space'] = dict() |
||
577 | result['child_space']['energy_category_names'] = list() # 1D array [energy category] |
||
578 | result['child_space']['units'] = list() # 1D array [energy category] |
||
579 | result['child_space']['child_space_names_array'] = list() # 2D array [energy category][child space] |
||
580 | result['child_space']['subtotals_array'] = list() # 2D array [energy category][child space] |
||
581 | result['child_space']['total_unit'] = config.currency_unit |
||
582 | |||
583 | if energy_category_set is not None and len(energy_category_set) > 0: |
||
584 | for energy_category_id in energy_category_set: |
||
585 | result['child_space']['energy_category_names'].append(energy_category_dict[energy_category_id]['name']) |
||
586 | result['child_space']['units'].append(config.currency_unit) |
||
587 | result['child_space']['child_space_names_array'].append( |
||
588 | child_space_data[energy_category_id]['child_space_names']) |
||
589 | result['child_space']['subtotals_array'].append( |
||
590 | child_space_data[energy_category_id]['subtotals']) |
||
591 | # export result to Excel file and then encode the file to base64 string |
||
592 | result['excel_bytes_base64'] = excelexporters.spacecost.export(result, |
||
593 | space['name'], |
||
594 | reporting_start_datetime_local, |
||
595 | reporting_end_datetime_local, |
||
596 | period_type) |
||
597 | resp.body = json.dumps(result) |
||
598 |