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.tenantsaving |
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 tenant |
24
|
|
|
# Step 3: query energy categories |
25
|
|
|
# Step 4: query associated sensors |
26
|
|
|
# Step 5: query associated points |
27
|
|
|
# Step 6: query base period energy saving |
28
|
|
|
# Step 7: query reporting period energy saving |
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_energy_baseline = mysql.connector.connect(**config.myems_energy_baseline_db) |
131
|
|
|
cursor_energy_baseline = cnx_energy_baseline.cursor() |
132
|
|
|
|
133
|
|
|
cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
134
|
|
|
cursor_historical = cnx_historical.cursor() |
135
|
|
|
|
136
|
|
|
cursor_system.execute(" SELECT id, name, area, cost_center_id " |
137
|
|
|
" FROM tbl_tenants " |
138
|
|
|
" WHERE id = %s ", (tenant_id,)) |
139
|
|
|
row_tenant = cursor_system.fetchone() |
140
|
|
|
if row_tenant is None: |
141
|
|
|
if cursor_system: |
142
|
|
|
cursor_system.close() |
143
|
|
|
if cnx_system: |
144
|
|
|
cnx_system.disconnect() |
145
|
|
|
|
146
|
|
|
if cursor_energy: |
147
|
|
|
cursor_energy.close() |
148
|
|
|
if cnx_energy: |
149
|
|
|
cnx_energy.disconnect() |
150
|
|
|
|
151
|
|
|
if cursor_energy_baseline: |
152
|
|
|
cursor_energy_baseline.close() |
153
|
|
|
if cnx_energy_baseline: |
154
|
|
|
cnx_energy_baseline.disconnect() |
155
|
|
|
|
156
|
|
|
if cnx_historical: |
157
|
|
|
cnx_historical.close() |
158
|
|
|
if cursor_historical: |
159
|
|
|
cursor_historical.disconnect() |
160
|
|
|
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.TENANT_NOT_FOUND') |
161
|
|
|
|
162
|
|
|
tenant = dict() |
163
|
|
|
tenant['id'] = row_tenant[0] |
164
|
|
|
tenant['name'] = row_tenant[1] |
165
|
|
|
tenant['area'] = row_tenant[2] |
166
|
|
|
tenant['cost_center_id'] = row_tenant[3] |
167
|
|
|
|
168
|
|
|
################################################################################################################ |
169
|
|
|
# Step 3: query energy categories |
170
|
|
|
################################################################################################################ |
171
|
|
|
energy_category_set = set() |
172
|
|
|
# query energy categories in base period |
173
|
|
|
cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
174
|
|
|
" FROM tbl_tenant_input_category_hourly " |
175
|
|
|
" WHERE tenant_id = %s " |
176
|
|
|
" AND start_datetime_utc >= %s " |
177
|
|
|
" AND start_datetime_utc < %s ", |
178
|
|
|
(tenant['id'], base_start_datetime_utc, base_end_datetime_utc)) |
179
|
|
|
rows_energy_categories = cursor_energy.fetchall() |
180
|
|
|
if rows_energy_categories is not None or len(rows_energy_categories) > 0: |
181
|
|
|
for row_energy_category in rows_energy_categories: |
182
|
|
|
energy_category_set.add(row_energy_category[0]) |
183
|
|
|
|
184
|
|
|
# query energy categories in reporting period |
185
|
|
|
cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
186
|
|
|
" FROM tbl_tenant_input_category_hourly " |
187
|
|
|
" WHERE tenant_id = %s " |
188
|
|
|
" AND start_datetime_utc >= %s " |
189
|
|
|
" AND start_datetime_utc < %s ", |
190
|
|
|
(tenant['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
191
|
|
|
rows_energy_categories = cursor_energy.fetchall() |
192
|
|
|
if rows_energy_categories is not None or len(rows_energy_categories) > 0: |
193
|
|
|
for row_energy_category in rows_energy_categories: |
194
|
|
|
energy_category_set.add(row_energy_category[0]) |
195
|
|
|
|
196
|
|
|
# query all energy categories in base period and reporting period |
197
|
|
|
cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
198
|
|
|
" FROM tbl_energy_categories " |
199
|
|
|
" ORDER BY id ", ) |
200
|
|
|
rows_energy_categories = cursor_system.fetchall() |
201
|
|
|
if rows_energy_categories is None or len(rows_energy_categories) == 0: |
202
|
|
|
if cursor_system: |
203
|
|
|
cursor_system.close() |
204
|
|
|
if cnx_system: |
205
|
|
|
cnx_system.disconnect() |
206
|
|
|
|
207
|
|
|
if cursor_energy: |
208
|
|
|
cursor_energy.close() |
209
|
|
|
if cnx_energy: |
210
|
|
|
cnx_energy.disconnect() |
211
|
|
|
|
212
|
|
|
if cursor_energy_baseline: |
213
|
|
|
cursor_energy_baseline.close() |
214
|
|
|
if cnx_energy_baseline: |
215
|
|
|
cnx_energy_baseline.disconnect() |
216
|
|
|
|
217
|
|
|
if cnx_historical: |
218
|
|
|
cnx_historical.close() |
219
|
|
|
if cursor_historical: |
220
|
|
|
cursor_historical.disconnect() |
221
|
|
|
raise falcon.HTTPError(falcon.HTTP_404, |
222
|
|
|
title='API.NOT_FOUND', |
223
|
|
|
description='API.ENERGY_CATEGORY_NOT_FOUND') |
224
|
|
|
energy_category_dict = dict() |
225
|
|
|
for row_energy_category in rows_energy_categories: |
226
|
|
|
if row_energy_category[0] in energy_category_set: |
227
|
|
|
energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
228
|
|
|
"unit_of_measure": row_energy_category[2], |
229
|
|
|
"kgce": row_energy_category[3], |
230
|
|
|
"kgco2e": row_energy_category[4]} |
231
|
|
|
|
232
|
|
|
################################################################################################################ |
233
|
|
|
# Step 4: query associated sensors |
234
|
|
|
################################################################################################################ |
235
|
|
|
point_list = list() |
236
|
|
|
cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
237
|
|
|
" FROM tbl_tenants t, tbl_sensors s, tbl_tenants_sensors ts, " |
238
|
|
|
" tbl_points p, tbl_sensors_points sp " |
239
|
|
|
" WHERE t.id = %s AND t.id = ts.tenant_id AND ts.sensor_id = s.id " |
240
|
|
|
" AND s.id = sp.sensor_id AND sp.point_id = p.id " |
241
|
|
|
" ORDER BY p.id ", (tenant['id'], )) |
242
|
|
|
rows_points = cursor_system.fetchall() |
243
|
|
|
if rows_points is not None and len(rows_points) > 0: |
244
|
|
|
for row in rows_points: |
245
|
|
|
point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
246
|
|
|
|
247
|
|
|
################################################################################################################ |
248
|
|
|
# Step 5: query associated points |
249
|
|
|
################################################################################################################ |
250
|
|
|
cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
251
|
|
|
" FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p " |
252
|
|
|
" WHERE t.id = %s AND t.id = tp.tenant_id AND tp.point_id = p.id " |
253
|
|
|
" ORDER BY p.id ", (tenant['id'], )) |
254
|
|
|
rows_points = cursor_system.fetchall() |
255
|
|
|
if rows_points is not None and len(rows_points) > 0: |
256
|
|
|
for row in rows_points: |
257
|
|
|
point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
258
|
|
|
|
259
|
|
|
################################################################################################################ |
260
|
|
|
# Step 6: query base period energy saving |
261
|
|
|
################################################################################################################ |
262
|
|
|
base = dict() |
263
|
|
|
if energy_category_set is not None and len(energy_category_set) > 0: |
264
|
|
|
for energy_category_id in energy_category_set: |
265
|
|
|
kgce = energy_category_dict[energy_category_id]['kgce'] |
266
|
|
|
kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
267
|
|
|
|
268
|
|
|
base[energy_category_id] = dict() |
269
|
|
|
base[energy_category_id]['timestamps'] = list() |
270
|
|
|
base[energy_category_id]['values_baseline'] = list() |
271
|
|
|
base[energy_category_id]['values_actual'] = list() |
272
|
|
|
base[energy_category_id]['values_saving'] = list() |
273
|
|
|
base[energy_category_id]['subtotal_baseline'] = Decimal(0.0) |
274
|
|
|
base[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
275
|
|
|
base[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
276
|
|
|
base[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0) |
277
|
|
|
base[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
278
|
|
|
base[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
279
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0) |
280
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
281
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
282
|
|
|
# query base period's energy baseline |
283
|
|
|
cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value " |
284
|
|
|
" FROM tbl_tenant_input_category_hourly " |
285
|
|
|
" WHERE tenant_id = %s " |
286
|
|
|
" AND energy_category_id = %s " |
287
|
|
|
" AND start_datetime_utc >= %s " |
288
|
|
|
" AND start_datetime_utc < %s " |
289
|
|
|
" ORDER BY start_datetime_utc ", |
290
|
|
|
(tenant['id'], |
291
|
|
|
energy_category_id, |
292
|
|
|
base_start_datetime_utc, |
293
|
|
|
base_end_datetime_utc)) |
294
|
|
|
rows_tenant_hourly = cursor_energy_baseline.fetchall() |
295
|
|
|
|
296
|
|
|
rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
297
|
|
|
base_start_datetime_utc, |
298
|
|
|
base_end_datetime_utc, |
299
|
|
|
period_type) |
300
|
|
|
for row_tenant_periodically in rows_tenant_periodically: |
301
|
|
|
current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
302
|
|
|
timedelta(minutes=timezone_offset) |
303
|
|
|
if period_type == 'hourly': |
304
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
305
|
|
|
elif period_type == 'daily': |
306
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
307
|
|
|
elif period_type == 'monthly': |
308
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m') |
309
|
|
|
elif period_type == 'yearly': |
310
|
|
|
current_datetime = current_datetime_local.strftime('%Y') |
311
|
|
|
|
312
|
|
|
baseline_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
313
|
|
|
base[energy_category_id]['timestamps'].append(current_datetime) |
|
|
|
|
314
|
|
|
base[energy_category_id]['values_baseline'].append(baseline_value) |
315
|
|
|
base[energy_category_id]['subtotal_baseline'] += baseline_value |
316
|
|
|
base[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce |
317
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e |
318
|
|
|
|
319
|
|
|
# query base period's energy actual |
320
|
|
|
cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
321
|
|
|
" FROM tbl_tenant_input_category_hourly " |
322
|
|
|
" WHERE tenant_id = %s " |
323
|
|
|
" AND energy_category_id = %s " |
324
|
|
|
" AND start_datetime_utc >= %s " |
325
|
|
|
" AND start_datetime_utc < %s " |
326
|
|
|
" ORDER BY start_datetime_utc ", |
327
|
|
|
(tenant['id'], |
328
|
|
|
energy_category_id, |
329
|
|
|
base_start_datetime_utc, |
330
|
|
|
base_end_datetime_utc)) |
331
|
|
|
rows_tenant_hourly = cursor_energy.fetchall() |
332
|
|
|
|
333
|
|
|
rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
334
|
|
|
base_start_datetime_utc, |
335
|
|
|
base_end_datetime_utc, |
336
|
|
|
period_type) |
337
|
|
|
for row_tenant_periodically in rows_tenant_periodically: |
338
|
|
|
current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
339
|
|
|
timedelta(minutes=timezone_offset) |
340
|
|
|
if period_type == 'hourly': |
341
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
342
|
|
|
elif period_type == 'daily': |
343
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
344
|
|
|
elif period_type == 'monthly': |
345
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m') |
346
|
|
|
elif period_type == 'yearly': |
347
|
|
|
current_datetime = current_datetime_local.strftime('%Y') |
348
|
|
|
|
349
|
|
|
actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
350
|
|
|
base[energy_category_id]['values_actual'].append(actual_value) |
351
|
|
|
base[energy_category_id]['subtotal_actual'] += actual_value |
352
|
|
|
base[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
353
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
354
|
|
|
|
355
|
|
|
# calculate base period's energy savings |
356
|
|
|
for i in range(len(base[energy_category_id]['values_baseline'])): |
357
|
|
|
base[energy_category_id]['values_saving'].append( |
358
|
|
|
base[energy_category_id]['values_baseline'][i] - |
359
|
|
|
base[energy_category_id]['values_actual'][i]) |
360
|
|
|
|
361
|
|
|
base[energy_category_id]['subtotal_saving'] = \ |
362
|
|
|
base[energy_category_id]['subtotal_baseline'] - \ |
363
|
|
|
base[energy_category_id]['subtotal_actual'] |
364
|
|
|
base[energy_category_id]['subtotal_in_kgce_saving'] = \ |
365
|
|
|
base[energy_category_id]['subtotal_in_kgce_baseline'] - \ |
366
|
|
|
base[energy_category_id]['subtotal_in_kgce_actual'] |
367
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
368
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_baseline'] - \ |
369
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_actual'] |
370
|
|
|
################################################################################################################ |
371
|
|
|
# Step 7: query reporting period energy saving |
372
|
|
|
################################################################################################################ |
373
|
|
|
reporting = dict() |
374
|
|
|
if energy_category_set is not None and len(energy_category_set) > 0: |
375
|
|
|
for energy_category_id in energy_category_set: |
376
|
|
|
kgce = energy_category_dict[energy_category_id]['kgce'] |
377
|
|
|
kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
378
|
|
|
|
379
|
|
|
reporting[energy_category_id] = dict() |
380
|
|
|
reporting[energy_category_id]['timestamps'] = list() |
381
|
|
|
reporting[energy_category_id]['values_baseline'] = list() |
382
|
|
|
reporting[energy_category_id]['values_actual'] = list() |
383
|
|
|
reporting[energy_category_id]['values_saving'] = list() |
384
|
|
|
reporting[energy_category_id]['subtotal_baseline'] = Decimal(0.0) |
385
|
|
|
reporting[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
386
|
|
|
reporting[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
387
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0) |
388
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
389
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
390
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0) |
391
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
392
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
393
|
|
|
# query reporting period's energy baseline |
394
|
|
|
cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value " |
395
|
|
|
" FROM tbl_tenant_input_category_hourly " |
396
|
|
|
" WHERE tenant_id = %s " |
397
|
|
|
" AND energy_category_id = %s " |
398
|
|
|
" AND start_datetime_utc >= %s " |
399
|
|
|
" AND start_datetime_utc < %s " |
400
|
|
|
" ORDER BY start_datetime_utc ", |
401
|
|
|
(tenant['id'], |
402
|
|
|
energy_category_id, |
403
|
|
|
reporting_start_datetime_utc, |
404
|
|
|
reporting_end_datetime_utc)) |
405
|
|
|
rows_tenant_hourly = cursor_energy_baseline.fetchall() |
406
|
|
|
|
407
|
|
|
rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
408
|
|
|
reporting_start_datetime_utc, |
409
|
|
|
reporting_end_datetime_utc, |
410
|
|
|
period_type) |
411
|
|
|
for row_tenant_periodically in rows_tenant_periodically: |
412
|
|
|
current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
413
|
|
|
timedelta(minutes=timezone_offset) |
414
|
|
|
if period_type == 'hourly': |
415
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
416
|
|
|
elif period_type == 'daily': |
417
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
418
|
|
|
elif period_type == 'monthly': |
419
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m') |
420
|
|
|
elif period_type == 'yearly': |
421
|
|
|
current_datetime = current_datetime_local.strftime('%Y') |
422
|
|
|
|
423
|
|
|
baseline_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
424
|
|
|
reporting[energy_category_id]['timestamps'].append(current_datetime) |
425
|
|
|
reporting[energy_category_id]['values_baseline'].append(baseline_value) |
426
|
|
|
reporting[energy_category_id]['subtotal_baseline'] += baseline_value |
427
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce |
428
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e |
429
|
|
|
|
430
|
|
|
# query reporting period's energy actual |
431
|
|
|
cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
432
|
|
|
" FROM tbl_tenant_input_category_hourly " |
433
|
|
|
" WHERE tenant_id = %s " |
434
|
|
|
" AND energy_category_id = %s " |
435
|
|
|
" AND start_datetime_utc >= %s " |
436
|
|
|
" AND start_datetime_utc < %s " |
437
|
|
|
" ORDER BY start_datetime_utc ", |
438
|
|
|
(tenant['id'], |
439
|
|
|
energy_category_id, |
440
|
|
|
reporting_start_datetime_utc, |
441
|
|
|
reporting_end_datetime_utc)) |
442
|
|
|
rows_tenant_hourly = cursor_energy.fetchall() |
443
|
|
|
|
444
|
|
|
rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
445
|
|
|
reporting_start_datetime_utc, |
446
|
|
|
reporting_end_datetime_utc, |
447
|
|
|
period_type) |
448
|
|
|
for row_tenant_periodically in rows_tenant_periodically: |
449
|
|
|
current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
450
|
|
|
timedelta(minutes=timezone_offset) |
451
|
|
|
if period_type == 'hourly': |
452
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
453
|
|
|
elif period_type == 'daily': |
454
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
455
|
|
|
elif period_type == 'monthly': |
456
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m') |
457
|
|
|
elif period_type == 'yearly': |
458
|
|
|
current_datetime = current_datetime_local.strftime('%Y') |
459
|
|
|
|
460
|
|
|
actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
461
|
|
|
reporting[energy_category_id]['values_actual'].append(actual_value) |
462
|
|
|
reporting[energy_category_id]['subtotal_actual'] += actual_value |
463
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
464
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
465
|
|
|
|
466
|
|
|
# calculate reporting period's energy savings |
467
|
|
|
for i in range(len(reporting[energy_category_id]['values_baseline'])): |
468
|
|
|
reporting[energy_category_id]['values_saving'].append( |
469
|
|
|
reporting[energy_category_id]['values_baseline'][i] - |
470
|
|
|
reporting[energy_category_id]['values_actual'][i]) |
471
|
|
|
|
472
|
|
|
reporting[energy_category_id]['subtotal_saving'] = \ |
473
|
|
|
reporting[energy_category_id]['subtotal_baseline'] - \ |
474
|
|
|
reporting[energy_category_id]['subtotal_actual'] |
475
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_saving'] = \ |
476
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_baseline'] - \ |
477
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_actual'] |
478
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
479
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] - \ |
480
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_actual'] |
481
|
|
|
################################################################################################################ |
482
|
|
|
# Step 8: query tariff data |
483
|
|
|
################################################################################################################ |
484
|
|
|
parameters_data = dict() |
485
|
|
|
parameters_data['names'] = list() |
486
|
|
|
parameters_data['timestamps'] = list() |
487
|
|
|
parameters_data['values'] = list() |
488
|
|
|
if energy_category_set is not None and len(energy_category_set) > 0: |
489
|
|
|
for energy_category_id in energy_category_set: |
490
|
|
|
energy_category_tariff_dict = utilities.get_energy_category_tariffs(tenant['cost_center_id'], |
491
|
|
|
energy_category_id, |
492
|
|
|
reporting_start_datetime_utc, |
493
|
|
|
reporting_end_datetime_utc) |
494
|
|
|
tariff_timestamp_list = list() |
495
|
|
|
tariff_value_list = list() |
496
|
|
|
for k, v in energy_category_tariff_dict.items(): |
497
|
|
|
# convert k from utc to local |
498
|
|
|
k = k + timedelta(minutes=timezone_offset) |
499
|
|
|
tariff_timestamp_list.append(k.isoformat()[0:19][0:19]) |
500
|
|
|
tariff_value_list.append(v) |
501
|
|
|
|
502
|
|
|
parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name']) |
503
|
|
|
parameters_data['timestamps'].append(tariff_timestamp_list) |
504
|
|
|
parameters_data['values'].append(tariff_value_list) |
505
|
|
|
|
506
|
|
|
################################################################################################################ |
507
|
|
|
# Step 9: query associated sensors and points data |
508
|
|
|
################################################################################################################ |
509
|
|
|
for point in point_list: |
510
|
|
|
point_values = [] |
511
|
|
|
point_timestamps = [] |
512
|
|
|
if point['object_type'] == 'ANALOG_VALUE': |
513
|
|
|
query = (" SELECT utc_date_time, actual_value " |
514
|
|
|
" FROM tbl_analog_value " |
515
|
|
|
" WHERE point_id = %s " |
516
|
|
|
" AND utc_date_time BETWEEN %s AND %s " |
517
|
|
|
" ORDER BY utc_date_time ") |
518
|
|
|
cursor_historical.execute(query, (point['id'], |
519
|
|
|
reporting_start_datetime_utc, |
520
|
|
|
reporting_end_datetime_utc)) |
521
|
|
|
rows = cursor_historical.fetchall() |
522
|
|
|
|
523
|
|
|
if rows is not None and len(rows) > 0: |
524
|
|
|
for row in rows: |
525
|
|
|
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
526
|
|
|
timedelta(minutes=timezone_offset) |
527
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
528
|
|
|
point_timestamps.append(current_datetime) |
529
|
|
|
point_values.append(row[1]) |
530
|
|
|
|
531
|
|
|
elif point['object_type'] == 'ENERGY_VALUE': |
532
|
|
|
query = (" SELECT utc_date_time, actual_value " |
533
|
|
|
" FROM tbl_energy_value " |
534
|
|
|
" WHERE point_id = %s " |
535
|
|
|
" AND utc_date_time BETWEEN %s AND %s " |
536
|
|
|
" ORDER BY utc_date_time ") |
537
|
|
|
cursor_historical.execute(query, (point['id'], |
538
|
|
|
reporting_start_datetime_utc, |
539
|
|
|
reporting_end_datetime_utc)) |
540
|
|
|
rows = cursor_historical.fetchall() |
541
|
|
|
|
542
|
|
|
if rows is not None and len(rows) > 0: |
543
|
|
|
for row in rows: |
544
|
|
|
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
545
|
|
|
timedelta(minutes=timezone_offset) |
546
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
547
|
|
|
point_timestamps.append(current_datetime) |
548
|
|
|
point_values.append(row[1]) |
549
|
|
|
elif point['object_type'] == 'DIGITAL_VALUE': |
550
|
|
|
query = (" SELECT utc_date_time, actual_value " |
551
|
|
|
" FROM tbl_digital_value " |
552
|
|
|
" WHERE point_id = %s " |
553
|
|
|
" AND utc_date_time BETWEEN %s AND %s ") |
554
|
|
|
cursor_historical.execute(query, (point['id'], |
555
|
|
|
reporting_start_datetime_utc, |
556
|
|
|
reporting_end_datetime_utc)) |
557
|
|
|
rows = cursor_historical.fetchall() |
558
|
|
|
|
559
|
|
|
if rows is not None and len(rows) > 0: |
560
|
|
|
for row in rows: |
561
|
|
|
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
562
|
|
|
timedelta(minutes=timezone_offset) |
563
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
564
|
|
|
point_timestamps.append(current_datetime) |
565
|
|
|
point_values.append(row[1]) |
566
|
|
|
|
567
|
|
|
parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
568
|
|
|
parameters_data['timestamps'].append(point_timestamps) |
569
|
|
|
parameters_data['values'].append(point_values) |
570
|
|
|
|
571
|
|
|
################################################################################################################ |
572
|
|
|
# Step 10: construct the report |
573
|
|
|
################################################################################################################ |
574
|
|
|
if cursor_system: |
575
|
|
|
cursor_system.close() |
576
|
|
|
if cnx_system: |
577
|
|
|
cnx_system.disconnect() |
578
|
|
|
|
579
|
|
|
if cursor_energy: |
580
|
|
|
cursor_energy.close() |
581
|
|
|
if cnx_energy: |
582
|
|
|
cnx_energy.disconnect() |
583
|
|
|
|
584
|
|
|
if cursor_energy_baseline: |
585
|
|
|
cursor_energy_baseline.close() |
586
|
|
|
if cnx_energy_baseline: |
587
|
|
|
cnx_energy_baseline.disconnect() |
588
|
|
|
|
589
|
|
|
result = dict() |
590
|
|
|
|
591
|
|
|
result['tenant'] = dict() |
592
|
|
|
result['tenant']['name'] = tenant['name'] |
593
|
|
|
result['tenant']['area'] = tenant['area'] |
594
|
|
|
|
595
|
|
|
result['base_period'] = dict() |
596
|
|
|
result['base_period']['names'] = list() |
597
|
|
|
result['base_period']['units'] = list() |
598
|
|
|
result['base_period']['timestamps'] = list() |
599
|
|
|
result['base_period']['values_saving'] = list() |
600
|
|
|
result['base_period']['subtotals_saving'] = list() |
601
|
|
|
result['base_period']['subtotals_in_kgce_saving'] = list() |
602
|
|
|
result['base_period']['subtotals_in_kgco2e_saving'] = list() |
603
|
|
|
result['base_period']['total_in_kgce_saving'] = Decimal(0.0) |
604
|
|
|
result['base_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
605
|
|
|
if energy_category_set is not None and len(energy_category_set) > 0: |
606
|
|
|
for energy_category_id in energy_category_set: |
607
|
|
|
result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
608
|
|
|
result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
609
|
|
|
result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
610
|
|
|
result['base_period']['values_saving'].append(base[energy_category_id]['values_saving']) |
611
|
|
|
result['base_period']['subtotals_saving'].append(base[energy_category_id]['subtotal_saving']) |
612
|
|
|
result['base_period']['subtotals_in_kgce_saving'].append( |
613
|
|
|
base[energy_category_id]['subtotal_in_kgce_saving']) |
614
|
|
|
result['base_period']['subtotals_in_kgco2e_saving'].append( |
615
|
|
|
base[energy_category_id]['subtotal_in_kgco2e_saving']) |
616
|
|
|
result['base_period']['total_in_kgce_saving'] += base[energy_category_id]['subtotal_in_kgce_saving'] |
617
|
|
|
result['base_period']['total_in_kgco2e_saving'] += base[energy_category_id]['subtotal_in_kgco2e_saving'] |
618
|
|
|
|
619
|
|
|
result['reporting_period'] = dict() |
620
|
|
|
result['reporting_period']['names'] = list() |
621
|
|
|
result['reporting_period']['energy_category_ids'] = list() |
622
|
|
|
result['reporting_period']['units'] = list() |
623
|
|
|
result['reporting_period']['timestamps'] = list() |
624
|
|
|
result['reporting_period']['values_saving'] = list() |
625
|
|
|
result['reporting_period']['subtotals_saving'] = list() |
626
|
|
|
result['reporting_period']['subtotals_in_kgce_saving'] = list() |
627
|
|
|
result['reporting_period']['subtotals_in_kgco2e_saving'] = list() |
628
|
|
|
result['reporting_period']['subtotals_per_unit_area_saving'] = list() |
629
|
|
|
result['reporting_period']['increment_rates_saving'] = list() |
630
|
|
|
result['reporting_period']['total_in_kgce_saving'] = Decimal(0.0) |
631
|
|
|
result['reporting_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
632
|
|
|
result['reporting_period']['increment_rate_in_kgce_saving'] = Decimal(0.0) |
633
|
|
|
result['reporting_period']['increment_rate_in_kgco2e_saving'] = Decimal(0.0) |
634
|
|
|
|
635
|
|
|
if energy_category_set is not None and len(energy_category_set) > 0: |
636
|
|
|
for energy_category_id in energy_category_set: |
637
|
|
|
result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
638
|
|
|
result['reporting_period']['energy_category_ids'].append(energy_category_id) |
639
|
|
|
result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
640
|
|
|
result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
641
|
|
|
result['reporting_period']['values_saving'].append(reporting[energy_category_id]['values_saving']) |
642
|
|
|
result['reporting_period']['subtotals_saving'].append(reporting[energy_category_id]['subtotal_saving']) |
643
|
|
|
result['reporting_period']['subtotals_in_kgce_saving'].append( |
644
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_saving']) |
645
|
|
|
result['reporting_period']['subtotals_in_kgco2e_saving'].append( |
646
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_saving']) |
647
|
|
|
result['reporting_period']['subtotals_per_unit_area_saving'].append( |
648
|
|
|
reporting[energy_category_id]['subtotal_saving'] / tenant['area'] if tenant['area'] > 0.0 else None) |
649
|
|
|
result['reporting_period']['increment_rates_saving'].append( |
650
|
|
|
(reporting[energy_category_id]['subtotal_saving'] - base[energy_category_id]['subtotal_saving']) / |
651
|
|
|
base[energy_category_id]['subtotal_saving'] |
652
|
|
|
if base[energy_category_id]['subtotal_saving'] > 0.0 else None) |
653
|
|
|
result['reporting_period']['total_in_kgce_saving'] += \ |
654
|
|
|
reporting[energy_category_id]['subtotal_in_kgce_saving'] |
655
|
|
|
result['reporting_period']['total_in_kgco2e_saving'] += \ |
656
|
|
|
reporting[energy_category_id]['subtotal_in_kgco2e_saving'] |
657
|
|
|
|
658
|
|
|
result['reporting_period']['total_in_kgco2e_per_unit_area_saving'] = \ |
659
|
|
|
result['reporting_period']['total_in_kgce_saving'] / tenant['area'] if tenant['area'] > 0.0 else None |
660
|
|
|
|
661
|
|
|
result['reporting_period']['increment_rate_in_kgce_saving'] = \ |
662
|
|
|
(result['reporting_period']['total_in_kgce_saving'] - result['base_period']['total_in_kgce_saving']) / \ |
663
|
|
|
result['base_period']['total_in_kgce_saving'] \ |
664
|
|
|
if result['base_period']['total_in_kgce_saving'] > Decimal(0.0) else None |
665
|
|
|
|
666
|
|
|
result['reporting_period']['total_in_kgce_per_unit_area_saving'] = \ |
667
|
|
|
result['reporting_period']['total_in_kgco2e_saving'] / tenant['area'] if tenant['area'] > 0.0 else None |
668
|
|
|
|
669
|
|
|
result['reporting_period']['increment_rate_in_kgco2e_saving'] = \ |
670
|
|
|
(result['reporting_period']['total_in_kgco2e_saving'] - result['base_period']['total_in_kgco2e_saving']) / \ |
671
|
|
|
result['base_period']['total_in_kgco2e_saving'] \ |
672
|
|
|
if result['base_period']['total_in_kgco2e_saving'] > Decimal(0.0) else None |
673
|
|
|
|
674
|
|
|
result['parameters'] = { |
675
|
|
|
"names": parameters_data['names'], |
676
|
|
|
"timestamps": parameters_data['timestamps'], |
677
|
|
|
"values": parameters_data['values'] |
678
|
|
|
} |
679
|
|
|
|
680
|
|
|
# export result to Excel file and then encode the file to base64 string |
681
|
|
|
result['excel_bytes_base64'] = excelexporters.tenantsaving.export(result, |
682
|
|
|
tenant['name'], |
683
|
|
|
reporting_start_datetime_local, |
684
|
|
|
reporting_end_datetime_local, |
685
|
|
|
period_type) |
686
|
|
|
|
687
|
|
|
resp.body = json.dumps(result) |
688
|
|
|
|