Passed
Push — master ( e07a89...15a904 )
by Guangyu
01:53 queued 10s
created

reports/spacecost.py (1 issue)

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