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