@@ 11-386 (lines=376) @@ | ||
8 | import excelexporters.offlinemetercost |
|
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 offline meter and energy category |
|
24 | # Step 3: query base period energy consumption |
|
25 | # Step 4: query base period energy cost |
|
26 | # Step 5: query reporting period energy consumption |
|
27 | # Step 6: query reporting period energy cost |
|
28 | # Step 7: query tariff data |
|
29 | # Step 8: construct the report |
|
30 | #################################################################################################################### |
|
31 | @staticmethod |
|
32 | def on_get(req, resp): |
|
33 | print(req.params) |
|
34 | offline_meter_id = req.params.get('offlinemeterid') |
|
35 | period_type = req.params.get('periodtype') |
|
36 | base_period_start_datetime = req.params.get('baseperiodstartdatetime') |
|
37 | base_period_end_datetime = req.params.get('baseperiodenddatetime') |
|
38 | reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
|
39 | reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') |
|
40 | ||
41 | ################################################################################################################ |
|
42 | # Step 1: valid parameters |
|
43 | ################################################################################################################ |
|
44 | if offline_meter_id is None: |
|
45 | raise falcon.HTTPError(falcon.HTTP_400, |
|
46 | title='API.BAD_REQUEST', |
|
47 | description='API.INVALID_OFFLINE_METER_ID') |
|
48 | else: |
|
49 | offline_meter_id = str.strip(offline_meter_id) |
|
50 | if not offline_meter_id.isdigit() or int(offline_meter_id) <= 0: |
|
51 | raise falcon.HTTPError(falcon.HTTP_400, |
|
52 | title='API.BAD_REQUEST', |
|
53 | description='API.INVALID_OFFLINE_METER_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_period_end_datetime is not None and len(str.strip(base_period_end_datetime)) > 0: |
|
68 | base_period_start_datetime = str.strip(base_period_start_datetime) |
|
69 | try: |
|
70 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime, '%Y-%m-%dT%H:%M:%S') |
|
71 | except ValueError: |
|
72 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
73 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
74 | base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
75 | timedelta(minutes=timezone_offset) |
|
76 | ||
77 | base_end_datetime_utc = None |
|
78 | if base_period_end_datetime is not None and len(str.strip(base_period_end_datetime)) > 0: |
|
79 | base_period_end_datetime = str.strip(base_period_end_datetime) |
|
80 | try: |
|
81 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime, '%Y-%m-%dT%H:%M:%S') |
|
82 | except ValueError: |
|
83 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
84 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
85 | base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
86 | timedelta(minutes=timezone_offset) |
|
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_period_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_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
98 | try: |
|
99 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
100 | '%Y-%m-%dT%H:%M:%S') |
|
101 | except ValueError: |
|
102 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
103 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
104 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
105 | timedelta(minutes=timezone_offset) |
|
106 | ||
107 | if reporting_period_end_datetime_local is None: |
|
108 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
109 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
110 | else: |
|
111 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
112 | try: |
|
113 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
114 | '%Y-%m-%dT%H:%M:%S') |
|
115 | except ValueError: |
|
116 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
117 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
118 | reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
119 | timedelta(minutes=timezone_offset) |
|
120 | ||
121 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
122 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
123 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
124 | ||
125 | ################################################################################################################ |
|
126 | # Step 2: query the offline meter and energy category |
|
127 | ################################################################################################################ |
|
128 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
129 | cursor_system = cnx_system.cursor() |
|
130 | ||
131 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
132 | cursor_energy = cnx_energy.cursor() |
|
133 | ||
134 | cnx_billing = mysql.connector.connect(**config.myems_billing_db) |
|
135 | cursor_billing = cnx_billing.cursor() |
|
136 | ||
137 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
|
138 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
|
139 | " FROM tbl_offline_meters m, tbl_energy_categories ec " |
|
140 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (offline_meter_id,)) |
|
141 | row_offline_meter = cursor_system.fetchone() |
|
142 | if row_offline_meter is None: |
|
143 | if cursor_system: |
|
144 | cursor_system.close() |
|
145 | if cnx_system: |
|
146 | cnx_system.disconnect() |
|
147 | ||
148 | if cursor_energy: |
|
149 | cursor_energy.close() |
|
150 | if cnx_energy: |
|
151 | cnx_energy.disconnect() |
|
152 | ||
153 | if cursor_billing: |
|
154 | cursor_billing.close() |
|
155 | if cnx_billing: |
|
156 | cnx_billing.disconnect() |
|
157 | ||
158 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.OFFLINE_METER_NOT_FOUND') |
|
159 | ||
160 | offline_meter = dict() |
|
161 | offline_meter['id'] = row_offline_meter[0] |
|
162 | offline_meter['name'] = row_offline_meter[1] |
|
163 | offline_meter['cost_center_id'] = row_offline_meter[2] |
|
164 | offline_meter['energy_category_id'] = row_offline_meter[3] |
|
165 | offline_meter['energy_category_name'] = row_offline_meter[4] |
|
166 | offline_meter['unit_of_measure'] = config.currency_unit |
|
167 | offline_meter['kgce'] = row_offline_meter[6] |
|
168 | offline_meter['kgco2e'] = row_offline_meter[7] |
|
169 | ||
170 | ################################################################################################################ |
|
171 | # Step 3: query base period energy consumption |
|
172 | ################################################################################################################ |
|
173 | query = (" SELECT start_datetime_utc, actual_value " |
|
174 | " FROM tbl_offline_meter_hourly " |
|
175 | " WHERE offline_meter_id = %s " |
|
176 | " AND start_datetime_utc >= %s " |
|
177 | " AND start_datetime_utc < %s " |
|
178 | " ORDER BY start_datetime_utc ") |
|
179 | cursor_energy.execute(query, (offline_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
180 | rows_offline_meter_hourly = cursor_energy.fetchall() |
|
181 | ||
182 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
|
183 | base_start_datetime_utc, |
|
184 | base_end_datetime_utc, |
|
185 | period_type) |
|
186 | base = dict() |
|
187 | base['timestamps'] = list() |
|
188 | base['values'] = list() |
|
189 | base['total_in_category'] = Decimal(0.0) |
|
190 | base['total_in_kgce'] = Decimal(0.0) |
|
191 | base['total_in_kgco2e'] = Decimal(0.0) |
|
192 | ||
193 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
|
194 | current_datetime_local = row_offline_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
195 | timedelta(minutes=timezone_offset) |
|
196 | if period_type == 'hourly': |
|
197 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
198 | elif period_type == 'daily': |
|
199 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
200 | elif period_type == 'monthly': |
|
201 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
202 | elif period_type == 'yearly': |
|
203 | current_datetime = current_datetime_local.strftime('%Y') |
|
204 | ||
205 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
|
206 | else row_offline_meter_periodically[1] |
|
207 | base['timestamps'].append(current_datetime) |
|
208 | base['total_in_kgce'] += actual_value * offline_meter['kgce'] |
|
209 | base['total_in_kgco2e'] += actual_value * offline_meter['kgco2e'] |
|
210 | ||
211 | ################################################################################################################ |
|
212 | # Step 4: query base period energy cost |
|
213 | ################################################################################################################ |
|
214 | query = (" SELECT start_datetime_utc, actual_value " |
|
215 | " FROM tbl_offline_meter_hourly " |
|
216 | " WHERE offline_meter_id = %s " |
|
217 | " AND start_datetime_utc >= %s " |
|
218 | " AND start_datetime_utc < %s " |
|
219 | " ORDER BY start_datetime_utc ") |
|
220 | cursor_billing.execute(query, (offline_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
221 | rows_offline_meter_hourly = cursor_billing.fetchall() |
|
222 | ||
223 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
|
224 | base_start_datetime_utc, |
|
225 | base_end_datetime_utc, |
|
226 | period_type) |
|
227 | ||
228 | base['values'] = list() |
|
229 | base['total_in_category'] = Decimal(0.0) |
|
230 | ||
231 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
|
232 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
|
233 | else row_offline_meter_periodically[1] |
|
234 | base['values'].append(actual_value) |
|
235 | base['total_in_category'] += actual_value |
|
236 | ||
237 | ################################################################################################################ |
|
238 | # Step 5: query reporting period energy consumption |
|
239 | ################################################################################################################ |
|
240 | query = (" SELECT start_datetime_utc, actual_value " |
|
241 | " FROM tbl_offline_meter_hourly " |
|
242 | " WHERE offline_meter_id = %s " |
|
243 | " AND start_datetime_utc >= %s " |
|
244 | " AND start_datetime_utc < %s " |
|
245 | " ORDER BY start_datetime_utc ") |
|
246 | cursor_energy.execute(query, (offline_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
247 | rows_offline_meter_hourly = cursor_energy.fetchall() |
|
248 | ||
249 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
|
250 | reporting_start_datetime_utc, |
|
251 | reporting_end_datetime_utc, |
|
252 | period_type) |
|
253 | reporting = dict() |
|
254 | reporting['timestamps'] = list() |
|
255 | reporting['values'] = list() |
|
256 | reporting['total_in_category'] = Decimal(0.0) |
|
257 | reporting['total_in_kgce'] = Decimal(0.0) |
|
258 | reporting['total_in_kgco2e'] = Decimal(0.0) |
|
259 | ||
260 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
|
261 | current_datetime_local = row_offline_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
262 | timedelta(minutes=timezone_offset) |
|
263 | if period_type == 'hourly': |
|
264 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
265 | elif period_type == 'daily': |
|
266 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
267 | elif period_type == 'monthly': |
|
268 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
269 | elif period_type == 'yearly': |
|
270 | current_datetime = current_datetime_local.strftime('%Y') |
|
271 | ||
272 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
|
273 | else row_offline_meter_periodically[1] |
|
274 | ||
275 | reporting['timestamps'].append(current_datetime) |
|
276 | reporting['total_in_kgce'] += actual_value * offline_meter['kgce'] |
|
277 | reporting['total_in_kgco2e'] += actual_value * offline_meter['kgco2e'] |
|
278 | ||
279 | ################################################################################################################ |
|
280 | # Step 6: query reporting period energy cost |
|
281 | ################################################################################################################ |
|
282 | query = (" SELECT start_datetime_utc, actual_value " |
|
283 | " FROM tbl_offline_meter_hourly " |
|
284 | " WHERE offline_meter_id = %s " |
|
285 | " AND start_datetime_utc >= %s " |
|
286 | " AND start_datetime_utc < %s " |
|
287 | " ORDER BY start_datetime_utc ") |
|
288 | cursor_billing.execute(query, (offline_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
289 | rows_offline_meter_hourly = cursor_billing.fetchall() |
|
290 | ||
291 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
|
292 | reporting_start_datetime_utc, |
|
293 | reporting_end_datetime_utc, |
|
294 | period_type) |
|
295 | ||
296 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
|
297 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
|
298 | else row_offline_meter_periodically[1] |
|
299 | ||
300 | reporting['values'].append(actual_value) |
|
301 | reporting['total_in_category'] += actual_value |
|
302 | ||
303 | ################################################################################################################ |
|
304 | # Step 7: query tariff data |
|
305 | ################################################################################################################ |
|
306 | parameters_data = dict() |
|
307 | parameters_data['names'] = list() |
|
308 | parameters_data['timestamps'] = list() |
|
309 | parameters_data['values'] = list() |
|
310 | ||
311 | tariff_dict = utilities.get_energy_category_tariffs(offline_meter['cost_center_id'], |
|
312 | offline_meter['energy_category_id'], |
|
313 | reporting_start_datetime_utc, |
|
314 | reporting_end_datetime_utc) |
|
315 | tariff_timestamp_list = list() |
|
316 | tariff_value_list = list() |
|
317 | for k, v in tariff_dict.items(): |
|
318 | # convert k from utc to local |
|
319 | k = k + timedelta(minutes=timezone_offset) |
|
320 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
321 | tariff_value_list.append(v) |
|
322 | ||
323 | parameters_data['names'].append('TARIFF-' + offline_meter['energy_category_name']) |
|
324 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
325 | parameters_data['values'].append(tariff_value_list) |
|
326 | ||
327 | ################################################################################################################ |
|
328 | # Step 8: construct the report |
|
329 | ################################################################################################################ |
|
330 | if cursor_system: |
|
331 | cursor_system.close() |
|
332 | if cnx_system: |
|
333 | cnx_system.disconnect() |
|
334 | ||
335 | if cursor_energy: |
|
336 | cursor_energy.close() |
|
337 | if cnx_energy: |
|
338 | cnx_energy.disconnect() |
|
339 | ||
340 | if cursor_billing: |
|
341 | cursor_billing.close() |
|
342 | if cnx_billing: |
|
343 | cnx_billing.disconnect() |
|
344 | ||
345 | result = { |
|
346 | "offline_meter": { |
|
347 | "cost_center_id": offline_meter['cost_center_id'], |
|
348 | "energy_category_id": offline_meter['energy_category_id'], |
|
349 | "energy_category_name": offline_meter['energy_category_name'], |
|
350 | "unit_of_measure": config.currency_unit, |
|
351 | "kgce": offline_meter['kgce'], |
|
352 | "kgco2e": offline_meter['kgco2e'], |
|
353 | }, |
|
354 | "base_period": { |
|
355 | "total_in_category": base['total_in_category'], |
|
356 | "total_in_kgce": base['total_in_kgce'], |
|
357 | "total_in_kgco2e": base['total_in_kgco2e'], |
|
358 | "timestamps": base['timestamps'], |
|
359 | "values": base['values'], |
|
360 | }, |
|
361 | "reporting_period": { |
|
362 | "increment_rate": |
|
363 | (reporting['total_in_category'] - base['total_in_category']) / base['total_in_category'] |
|
364 | if base['total_in_category'] > 0 else None, |
|
365 | "total_in_category": reporting['total_in_category'], |
|
366 | "total_in_kgce": reporting['total_in_kgce'], |
|
367 | "total_in_kgco2e": reporting['total_in_kgco2e'], |
|
368 | "timestamps": reporting['timestamps'], |
|
369 | "values": reporting['values'], |
|
370 | }, |
|
371 | "parameters": { |
|
372 | "names": parameters_data['names'], |
|
373 | "timestamps": parameters_data['timestamps'], |
|
374 | "values": parameters_data['values'] |
|
375 | }, |
|
376 | } |
|
377 | ||
378 | # export result to Excel file and then encode the file to base64 string |
|
379 | result['excel_bytes_base64'] = \ |
|
380 | excelexporters.offlinemetercost.export(result, |
|
381 | offline_meter['name'], |
|
382 | reporting_period_start_datetime_local, |
|
383 | reporting_period_end_datetime_local, |
|
384 | period_type) |
|
385 | ||
386 | resp.body = json.dumps(result) |
|
387 |
@@ 11-385 (lines=375) @@ | ||
8 | import excelexporters.virtualmetercost |
|
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 virtual meter and energy category |
|
24 | # Step 3: query base period energy consumption |
|
25 | # Step 4: query base period energy cost |
|
26 | # Step 5: query reporting period energy consumption |
|
27 | # Step 6: query reporting period energy cost |
|
28 | # Step 7: query tariff data |
|
29 | # Step 8: construct the report |
|
30 | #################################################################################################################### |
|
31 | @staticmethod |
|
32 | def on_get(req, resp): |
|
33 | print(req.params) |
|
34 | virtual_meter_id = req.params.get('virtualmeterid') |
|
35 | period_type = req.params.get('periodtype') |
|
36 | base_period_start_datetime_local = req.params.get('baseperiodstartdatetime') |
|
37 | base_period_end_datetime_local = req.params.get('baseperiodenddatetime') |
|
38 | reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
|
39 | reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') |
|
40 | ||
41 | ################################################################################################################ |
|
42 | # Step 1: valid parameters |
|
43 | ################################################################################################################ |
|
44 | if virtual_meter_id is None: |
|
45 | raise falcon.HTTPError(falcon.HTTP_400, |
|
46 | title='API.BAD_REQUEST', |
|
47 | description='API.INVALID_VIRTUAL_METER_ID') |
|
48 | else: |
|
49 | virtual_meter_id = str.strip(virtual_meter_id) |
|
50 | if not virtual_meter_id.isdigit() or int(virtual_meter_id) <= 0: |
|
51 | raise falcon.HTTPError(falcon.HTTP_400, |
|
52 | title='API.BAD_REQUEST', |
|
53 | description='API.INVALID_VIRTUAL_METER_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_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
|
68 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
|
69 | try: |
|
70 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
71 | except ValueError: |
|
72 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
73 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
74 | base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
75 | timedelta(minutes=timezone_offset) |
|
76 | ||
77 | base_end_datetime_utc = None |
|
78 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
|
79 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
|
80 | try: |
|
81 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
82 | except ValueError: |
|
83 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
84 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
85 | base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
86 | timedelta(minutes=timezone_offset) |
|
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_period_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_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
98 | try: |
|
99 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
100 | '%Y-%m-%dT%H:%M:%S') |
|
101 | except ValueError: |
|
102 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
103 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
104 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
105 | timedelta(minutes=timezone_offset) |
|
106 | ||
107 | if reporting_period_end_datetime_local is None: |
|
108 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
109 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
110 | else: |
|
111 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
112 | try: |
|
113 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
114 | '%Y-%m-%dT%H:%M:%S') |
|
115 | except ValueError: |
|
116 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
117 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
118 | reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
119 | timedelta(minutes=timezone_offset) |
|
120 | ||
121 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
122 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
123 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
124 | ||
125 | ################################################################################################################ |
|
126 | # Step 2: query the virtual meter and energy category |
|
127 | ################################################################################################################ |
|
128 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
129 | cursor_system = cnx_system.cursor() |
|
130 | ||
131 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
132 | cursor_energy = cnx_energy.cursor() |
|
133 | ||
134 | cnx_billing = mysql.connector.connect(**config.myems_billing_db) |
|
135 | cursor_billing = cnx_billing.cursor() |
|
136 | ||
137 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
|
138 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
|
139 | " FROM tbl_virtual_meters m, tbl_energy_categories ec " |
|
140 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (virtual_meter_id,)) |
|
141 | row_virtual_meter = cursor_system.fetchone() |
|
142 | if row_virtual_meter is None: |
|
143 | if cursor_system: |
|
144 | cursor_system.close() |
|
145 | if cnx_system: |
|
146 | cnx_system.disconnect() |
|
147 | ||
148 | if cursor_energy: |
|
149 | cursor_energy.close() |
|
150 | if cnx_energy: |
|
151 | cnx_energy.disconnect() |
|
152 | ||
153 | if cursor_billing: |
|
154 | cursor_billing.close() |
|
155 | if cnx_billing: |
|
156 | cnx_billing.disconnect() |
|
157 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.VIRTUAL_METER_NOT_FOUND') |
|
158 | ||
159 | virtual_meter = dict() |
|
160 | virtual_meter['id'] = row_virtual_meter[0] |
|
161 | virtual_meter['name'] = row_virtual_meter[1] |
|
162 | virtual_meter['cost_center_id'] = row_virtual_meter[2] |
|
163 | virtual_meter['energy_category_id'] = row_virtual_meter[3] |
|
164 | virtual_meter['energy_category_name'] = row_virtual_meter[4] |
|
165 | virtual_meter['unit_of_measure'] = config.currency_unit |
|
166 | virtual_meter['kgce'] = row_virtual_meter[6] |
|
167 | virtual_meter['kgco2e'] = row_virtual_meter[7] |
|
168 | ||
169 | ################################################################################################################ |
|
170 | # Step 3: query base period energy consumption |
|
171 | ################################################################################################################ |
|
172 | query = (" SELECT start_datetime_utc, actual_value " |
|
173 | " FROM tbl_virtual_meter_hourly " |
|
174 | " WHERE virtual_meter_id = %s " |
|
175 | " AND start_datetime_utc >= %s " |
|
176 | " AND start_datetime_utc < %s " |
|
177 | " ORDER BY start_datetime_utc ") |
|
178 | cursor_energy.execute(query, (virtual_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
179 | rows_virtual_meter_hourly = cursor_energy.fetchall() |
|
180 | ||
181 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
|
182 | base_start_datetime_utc, |
|
183 | base_end_datetime_utc, |
|
184 | period_type) |
|
185 | base = dict() |
|
186 | base['timestamps'] = list() |
|
187 | base['values'] = list() |
|
188 | base['total_in_category'] = Decimal(0.0) |
|
189 | base['total_in_kgce'] = Decimal(0.0) |
|
190 | base['total_in_kgco2e'] = Decimal(0.0) |
|
191 | ||
192 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
|
193 | current_datetime_local = row_virtual_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
194 | timedelta(minutes=timezone_offset) |
|
195 | if period_type == 'hourly': |
|
196 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
197 | elif period_type == 'daily': |
|
198 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
199 | elif period_type == 'monthly': |
|
200 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
201 | elif period_type == 'yearly': |
|
202 | current_datetime = current_datetime_local.strftime('%Y') |
|
203 | ||
204 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
|
205 | else row_virtual_meter_periodically[1] |
|
206 | base['timestamps'].append(current_datetime) |
|
207 | base['total_in_kgce'] += actual_value * virtual_meter['kgce'] |
|
208 | base['total_in_kgco2e'] += actual_value * virtual_meter['kgco2e'] |
|
209 | ||
210 | ################################################################################################################ |
|
211 | # Step 4: query base period energy cost |
|
212 | ################################################################################################################ |
|
213 | query = (" SELECT start_datetime_utc, actual_value " |
|
214 | " FROM tbl_virtual_meter_hourly " |
|
215 | " WHERE virtual_meter_id = %s " |
|
216 | " AND start_datetime_utc >= %s " |
|
217 | " AND start_datetime_utc < %s " |
|
218 | " ORDER BY start_datetime_utc ") |
|
219 | cursor_billing.execute(query, (virtual_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
220 | rows_virtual_meter_hourly = cursor_billing.fetchall() |
|
221 | ||
222 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
|
223 | base_start_datetime_utc, |
|
224 | base_end_datetime_utc, |
|
225 | period_type) |
|
226 | ||
227 | base['values'] = list() |
|
228 | base['total_in_category'] = Decimal(0.0) |
|
229 | ||
230 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
|
231 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
|
232 | else row_virtual_meter_periodically[1] |
|
233 | base['values'].append(actual_value) |
|
234 | base['total_in_category'] += actual_value |
|
235 | ||
236 | ################################################################################################################ |
|
237 | # Step 5: query reporting period energy consumption |
|
238 | ################################################################################################################ |
|
239 | query = (" SELECT start_datetime_utc, actual_value " |
|
240 | " FROM tbl_virtual_meter_hourly " |
|
241 | " WHERE virtual_meter_id = %s " |
|
242 | " AND start_datetime_utc >= %s " |
|
243 | " AND start_datetime_utc < %s " |
|
244 | " ORDER BY start_datetime_utc ") |
|
245 | cursor_billing.execute(query, (virtual_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
246 | rows_virtual_meter_hourly = cursor_billing.fetchall() |
|
247 | ||
248 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
|
249 | reporting_start_datetime_utc, |
|
250 | reporting_end_datetime_utc, |
|
251 | period_type) |
|
252 | reporting = dict() |
|
253 | reporting['timestamps'] = list() |
|
254 | reporting['values'] = list() |
|
255 | reporting['total_in_category'] = Decimal(0.0) |
|
256 | reporting['total_in_kgce'] = Decimal(0.0) |
|
257 | reporting['total_in_kgco2e'] = Decimal(0.0) |
|
258 | ||
259 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
|
260 | current_datetime_local = row_virtual_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
261 | timedelta(minutes=timezone_offset) |
|
262 | if period_type == 'hourly': |
|
263 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
264 | elif period_type == 'daily': |
|
265 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
266 | elif period_type == 'monthly': |
|
267 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
268 | elif period_type == 'yearly': |
|
269 | current_datetime = current_datetime_local.strftime('%Y') |
|
270 | ||
271 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
|
272 | else row_virtual_meter_periodically[1] |
|
273 | ||
274 | reporting['timestamps'].append(current_datetime) |
|
275 | reporting['total_in_kgce'] += actual_value * virtual_meter['kgce'] |
|
276 | reporting['total_in_kgco2e'] += actual_value * virtual_meter['kgco2e'] |
|
277 | ||
278 | ################################################################################################################ |
|
279 | # Step 6: query reporting period energy cost |
|
280 | ################################################################################################################ |
|
281 | query = (" SELECT start_datetime_utc, actual_value " |
|
282 | " FROM tbl_virtual_meter_hourly " |
|
283 | " WHERE virtual_meter_id = %s " |
|
284 | " AND start_datetime_utc >= %s " |
|
285 | " AND start_datetime_utc < %s " |
|
286 | " ORDER BY start_datetime_utc ") |
|
287 | cursor_billing.execute(query, (virtual_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
288 | rows_virtual_meter_hourly = cursor_billing.fetchall() |
|
289 | ||
290 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
|
291 | reporting_start_datetime_utc, |
|
292 | reporting_end_datetime_utc, |
|
293 | period_type) |
|
294 | ||
295 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
|
296 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
|
297 | else row_virtual_meter_periodically[1] |
|
298 | ||
299 | reporting['values'].append(actual_value) |
|
300 | reporting['total_in_category'] += actual_value |
|
301 | ||
302 | ################################################################################################################ |
|
303 | # Step 7: query tariff data |
|
304 | ################################################################################################################ |
|
305 | parameters_data = dict() |
|
306 | parameters_data['names'] = list() |
|
307 | parameters_data['timestamps'] = list() |
|
308 | parameters_data['values'] = list() |
|
309 | ||
310 | tariff_dict = utilities.get_energy_category_tariffs(virtual_meter['cost_center_id'], |
|
311 | virtual_meter['energy_category_id'], |
|
312 | reporting_start_datetime_utc, |
|
313 | reporting_end_datetime_utc) |
|
314 | tariff_timestamp_list = list() |
|
315 | tariff_value_list = list() |
|
316 | for k, v in tariff_dict.items(): |
|
317 | # convert k from utc to local |
|
318 | k = k + timedelta(minutes=timezone_offset) |
|
319 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
320 | tariff_value_list.append(v) |
|
321 | ||
322 | parameters_data['names'].append('TARIFF-' + virtual_meter['energy_category_name']) |
|
323 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
324 | parameters_data['values'].append(tariff_value_list) |
|
325 | ||
326 | ################################################################################################################ |
|
327 | # Step 8: construct the report |
|
328 | ################################################################################################################ |
|
329 | if cursor_system: |
|
330 | cursor_system.close() |
|
331 | if cnx_system: |
|
332 | cnx_system.disconnect() |
|
333 | ||
334 | if cursor_energy: |
|
335 | cursor_energy.close() |
|
336 | if cnx_energy: |
|
337 | cnx_energy.disconnect() |
|
338 | ||
339 | if cursor_billing: |
|
340 | cursor_billing.close() |
|
341 | if cnx_billing: |
|
342 | cnx_billing.disconnect() |
|
343 | ||
344 | result = { |
|
345 | "virtual_meter": { |
|
346 | "cost_center_id": virtual_meter['cost_center_id'], |
|
347 | "energy_category_id": virtual_meter['energy_category_id'], |
|
348 | "energy_category_name": virtual_meter['energy_category_name'], |
|
349 | "unit_of_measure": config.currency_unit, |
|
350 | "kgce": virtual_meter['kgce'], |
|
351 | "kgco2e": virtual_meter['kgco2e'], |
|
352 | }, |
|
353 | "base_period": { |
|
354 | "total_in_category": base['total_in_category'], |
|
355 | "total_in_kgce": base['total_in_kgce'], |
|
356 | "total_in_kgco2e": base['total_in_kgco2e'], |
|
357 | "timestamps": base['timestamps'], |
|
358 | "values": base['values'], |
|
359 | }, |
|
360 | "reporting_period": { |
|
361 | "increment_rate": |
|
362 | (reporting['total_in_category'] - base['total_in_category']) / base['total_in_category'] |
|
363 | if base['total_in_category'] > 0 else None, |
|
364 | "total_in_category": reporting['total_in_category'], |
|
365 | "total_in_kgce": reporting['total_in_kgce'], |
|
366 | "total_in_kgco2e": reporting['total_in_kgco2e'], |
|
367 | "timestamps": reporting['timestamps'], |
|
368 | "values": reporting['values'], |
|
369 | }, |
|
370 | "parameters": { |
|
371 | "names": parameters_data['names'], |
|
372 | "timestamps": parameters_data['timestamps'], |
|
373 | "values": parameters_data['values'] |
|
374 | }, |
|
375 | } |
|
376 | ||
377 | # export result to Excel file and then encode the file to base64 string |
|
378 | result['excel_bytes_base64'] = \ |
|
379 | excelexporters.virtualmetercost.export(result, |
|
380 | virtual_meter['name'], |
|
381 | reporting_period_start_datetime_local, |
|
382 | reporting_period_end_datetime_local, |
|
383 | period_type) |
|
384 | ||
385 | resp.body = json.dumps(result) |
|
386 |