Passed
Push — master ( 36895d...ea4a7c )
by Guangyu
01:51 queued 10s
created

dashboard   F

Complexity

Total Complexity 173

Size/Duplication

Total Lines 943
Duplicated Lines 40.93 %

Importance

Changes 0
Metric Value
wmc 173
eloc 708
dl 386
loc 943
rs 1.892
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
F Reporting.on_get() 386 909 171
A Reporting.__init__() 0 3 1
A Reporting.on_options() 0 3 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like dashboard often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
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 input
28
    # Step 8: query reporting period energy input
29
    # Step 9: query tariff data
30
    # Step 10: query associated sensors and points data
31
    # Step 11: query child spaces energy input
32
    # Step 12: construct the report
33
    ####################################################################################################################
34
    @staticmethod
35
    def on_get(req, resp):
36
        print(req.params)
37
        user_uuid = req.params.get('useruuid')
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 user_uuid is None:
48
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_USER_UUID')
49
        else:
50
            user_uuid = str.strip(user_uuid)
51
            if len(user_uuid) != 36:
52
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_USER_UUID')
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
126
        cnx_user = mysql.connector.connect(**config.myems_user_db)
127
        cursor_user = cnx_user.cursor()
128
129
        cursor_user.execute(" SELECT id, is_admin, privilege_id "
130
                            " FROM tbl_users "
131
                            " WHERE uuid = %s ", (user_uuid,))
132
        row_user = cursor_user.fetchone()
133
        if row_user is None:
134
            if cursor_user:
135
                cursor_user.close()
136
            if cnx_user:
137
                cnx_user.disconnect()
138
139
            raise falcon.HTTPError(falcon.HTTP_404, 'API.NOT_FOUND', 'API.USER_NOT_FOUND')
140
141
        user = {'id': row_user[0], 'is_admin': row_user[1], 'privilege_id': row_user[2]}
142
        if user['is_admin']:
143
            # todo: make sure the space id is always 1 for admin
144
            space_id = 1
145
        else:
146
            cursor_user.execute(" SELECT data "
147
                                " FROM tbl_privileges "
148
                                " WHERE id = %s ", (user['privilege_id'],))
149
            row_privilege = cursor_user.fetchone()
150
            if row_privilege is None:
151
                if cursor_user:
152
                    cursor_user.close()
153
                if cnx_user:
154
                    cnx_user.disconnect()
155
156
                raise falcon.HTTPError(falcon.HTTP_404, 'API.NOT_FOUND', 'API.USER_PRIVILEGE_NOT_FOUND')
157
158
            privilege_data = json.loads(row_privilege[0], encoding='utf-8')
159
            if 'spaces' not in privilege_data.keys() \
160
                    or privilege_data['spaces'] is None \
161
                    or len(privilege_data['spaces']) == 0:
162
                if cursor_user:
163
                    cursor_user.close()
164
                if cnx_user:
165
                    cnx_user.disconnect()
166
167
                raise falcon.HTTPError(falcon.HTTP_404, 'API.NOT_FOUND', 'API.USER_PRIVILEGE_NOT_FOUND')
168
            # todo: how to deal with multiple spaces in privilege data
169
            space_id = privilege_data['spaces'][0]
170
171
        if cursor_user:
172
            cursor_user.close()
173
        if cnx_user:
174
            cnx_user.disconnect()
175
176
        cnx_system = mysql.connector.connect(**config.myems_system_db)
177
        cursor_system = cnx_system.cursor()
178
179
        cursor_system.execute(" SELECT id, name, area, cost_center_id "
180
                              " FROM tbl_spaces "
181
                              " WHERE id = %s ", (space_id,))
182
        row_space = cursor_system.fetchone()
183
        if row_space is None:
184
            if cursor_system:
185
                cursor_system.close()
186
            if cnx_system:
187
                cnx_system.disconnect()
188
189
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.SPACE_NOT_FOUND')
190
191
        space = dict()
192
        space['id'] = row_space[0]
193
        space['name'] = row_space[1]
194
        space['area'] = row_space[2]
195
        space['cost_center_id'] = row_space[3]
196
197
        ################################################################################################################
198
        # Step 3: query energy categories
199
        ################################################################################################################
200
        cnx_energy = mysql.connector.connect(**config.myems_energy_db)
201
        cursor_energy = cnx_energy.cursor()
202
203
        cnx_billing = mysql.connector.connect(**config.myems_billing_db)
204
        cursor_billing = cnx_billing.cursor()
205
206
        energy_category_set = set()
207
        # query energy categories in base period
208
        cursor_energy.execute(" SELECT DISTINCT(energy_category_id) "
209
                              " FROM tbl_space_input_category_hourly "
210
                              " WHERE space_id = %s "
211
                              "     AND start_datetime_utc >= %s "
212
                              "     AND start_datetime_utc < %s ",
213
                              (space['id'], base_start_datetime_utc, base_end_datetime_utc))
214
        rows_energy_categories = cursor_energy.fetchall()
215
        if rows_energy_categories is not None or len(rows_energy_categories) > 0:
216
            for row_energy_category in rows_energy_categories:
217
                energy_category_set.add(row_energy_category[0])
218
219
        # query energy categories in reporting period
220
        cursor_energy.execute(" SELECT DISTINCT(energy_category_id) "
221
                              " FROM tbl_space_input_category_hourly "
222
                              " WHERE space_id = %s "
223
                              "     AND start_datetime_utc >= %s "
224
                              "     AND start_datetime_utc < %s ",
225
                              (space['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
226
        rows_energy_categories = cursor_energy.fetchall()
227
        if rows_energy_categories is not None or len(rows_energy_categories) > 0:
228
            for row_energy_category in rows_energy_categories:
229
                energy_category_set.add(row_energy_category[0])
230
231
        # query all energy categories in base period and reporting period
232
        cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e "
233
                              " FROM tbl_energy_categories "
234
                              " ORDER BY id ", )
235
        rows_energy_categories = cursor_system.fetchall()
236
        if rows_energy_categories is None or len(rows_energy_categories) == 0:
237
            if cursor_system:
238
                cursor_system.close()
239
            if cnx_system:
240
                cnx_system.disconnect()
241
242
            if cursor_energy:
243
                cursor_energy.close()
244
            if cnx_energy:
245
                cnx_energy.disconnect()
246
247
            if cursor_billing:
248
                cursor_billing.close()
249
            if cnx_billing:
250
                cnx_billing.disconnect()
251
252
            raise falcon.HTTPError(falcon.HTTP_404,
253
                                   title='API.NOT_FOUND',
254
                                   description='API.ENERGY_CATEGORY_NOT_FOUND')
255
        energy_category_dict = dict()
256
        for row_energy_category in rows_energy_categories:
257
            if row_energy_category[0] in energy_category_set:
258
                energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1],
259
                                                                "unit_of_measure": row_energy_category[2],
260
                                                                "kgce": row_energy_category[3],
261
                                                                "kgco2e": row_energy_category[4]}
262
263
        ################################################################################################################
264
        # Step 4: query associated sensors
265
        ################################################################################################################
266
        point_list = list()
267
        cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type  "
268
                              " FROM tbl_spaces sp, tbl_sensors se, tbl_spaces_sensors spse, "
269
                              "      tbl_points po, tbl_sensors_points sepo "
270
                              " WHERE sp.id = %s AND sp.id = spse.space_id AND spse.sensor_id = se.id "
271
                              "       AND se.id = sepo.sensor_id AND sepo.point_id = po.id "
272
                              " ORDER BY po.id ", (space['id'], ))
273
        rows_points = cursor_system.fetchall()
274
        if rows_points is not None and len(rows_points) > 0:
275
            for row in rows_points:
276
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
277
278
        ################################################################################################################
279
        # Step 5: query associated points
280
        ################################################################################################################
281
        cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type  "
282
                              " FROM tbl_spaces sp, tbl_spaces_points sppo, tbl_points po "
283
                              " WHERE sp.id = %s AND sp.id = sppo.space_id AND sppo.point_id = po.id "
284
                              " ORDER BY po.id ", (space['id'], ))
285
        rows_points = cursor_system.fetchall()
286
        if rows_points is not None and len(rows_points) > 0:
287
            for row in rows_points:
288
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
289
290
        ################################################################################################################
291
        # Step 6: query child spaces
292
        ################################################################################################################
293
        child_space_list = list()
294
        cursor_system.execute(" SELECT id, name  "
295
                              " FROM tbl_spaces "
296
                              " WHERE parent_space_id = %s "
297
                              " ORDER BY id ", (space['id'], ))
298
        rows_child_spaces = cursor_system.fetchall()
299
        if rows_child_spaces is not None and len(rows_child_spaces) > 0:
300
            for row in rows_child_spaces:
301
                child_space_list.append({"id": row[0], "name": row[1]})
302
303
        ################################################################################################################
304
        # Step 7: query base period energy input
305
        ################################################################################################################
306
        base_input = dict()
307 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
308
            for energy_category_id in energy_category_set:
309
                kgce = energy_category_dict[energy_category_id]['kgce']
310
                kgco2e = energy_category_dict[energy_category_id]['kgco2e']
311
312
                base_input[energy_category_id] = dict()
313
                base_input[energy_category_id]['timestamps'] = list()
314
                base_input[energy_category_id]['values'] = list()
315
                base_input[energy_category_id]['subtotal'] = Decimal(0.0)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable Decimal does not seem to be defined.
Loading history...
316
                base_input[energy_category_id]['subtotal_in_kgce'] = Decimal(0.0)
317
                base_input[energy_category_id]['subtotal_in_kgco2e'] = Decimal(0.0)
318
319
                cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
320
                                      " FROM tbl_space_input_category_hourly "
321
                                      " WHERE space_id = %s "
322
                                      "     AND energy_category_id = %s "
323
                                      "     AND start_datetime_utc >= %s "
324
                                      "     AND start_datetime_utc < %s "
325
                                      " ORDER BY start_datetime_utc ",
326
                                      (space['id'],
327
                                       energy_category_id,
328
                                       base_start_datetime_utc,
329
                                       base_end_datetime_utc))
330
                rows_space_hourly = cursor_energy.fetchall()
331
332
                rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly,
333
                                                                                    base_start_datetime_utc,
334
                                                                                    base_end_datetime_utc,
335
                                                                                    period_type)
336
                for row_space_periodically in rows_space_periodically:
337
                    current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \
338
                                             timedelta(minutes=timezone_offset)
339
                    if period_type == 'hourly':
340
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
341
                    elif period_type == 'daily':
342
                        current_datetime = current_datetime_local.strftime('%Y-%m-%d')
343
                    elif period_type == 'monthly':
344
                        current_datetime = current_datetime_local.strftime('%Y-%m')
345
                    elif period_type == 'yearly':
346
                        current_datetime = current_datetime_local.strftime('%Y')
347
348
                    actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1]
349
                    base_input[energy_category_id]['timestamps'].append(current_datetime)
0 ignored issues
show
introduced by
The variable current_datetime does not seem to be defined for all execution paths.
Loading history...
350
                    base_input[energy_category_id]['values'].append(actual_value)
351
                    base_input[energy_category_id]['subtotal'] += actual_value
352
                    base_input[energy_category_id]['subtotal_in_kgce'] += actual_value * kgce
353
                    base_input[energy_category_id]['subtotal_in_kgco2e'] += actual_value * kgco2e
354
355
        ################################################################################################################
356
        # Step 8: query base period energy cost
357
        ################################################################################################################
358
        base_cost = dict()
359 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
360
            for energy_category_id in energy_category_set:
361
                base_cost[energy_category_id] = dict()
362
                base_cost[energy_category_id]['timestamps'] = list()
363
                base_cost[energy_category_id]['values'] = list()
364
                base_cost[energy_category_id]['subtotal'] = Decimal(0.0)
365
366
                cursor_billing.execute(" SELECT start_datetime_utc, actual_value "
367
                                       " FROM tbl_space_input_category_hourly "
368
                                       " WHERE space_id = %s "
369
                                       "     AND energy_category_id = %s "
370
                                       "     AND start_datetime_utc >= %s "
371
                                       "     AND start_datetime_utc < %s "
372
                                       " ORDER BY start_datetime_utc ",
373
                                       (space['id'],
374
                                        energy_category_id,
375
                                        base_start_datetime_utc,
376
                                        base_end_datetime_utc))
377
                rows_space_hourly = cursor_billing.fetchall()
378
379
                rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly,
380
                                                                                    base_start_datetime_utc,
381
                                                                                    base_end_datetime_utc,
382
                                                                                    period_type)
383
                for row_space_periodically in rows_space_periodically:
384
                    current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \
385
                                             timedelta(minutes=timezone_offset)
386
                    if period_type == 'hourly':
387
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
388
                    elif period_type == 'daily':
389
                        current_datetime = current_datetime_local.strftime('%Y-%m-%d')
390
                    elif period_type == 'monthly':
391
                        current_datetime = current_datetime_local.strftime('%Y-%m')
392
                    elif period_type == 'yearly':
393
                        current_datetime = current_datetime_local.strftime('%Y')
394
395
                    actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1]
396
                    base_cost[energy_category_id]['timestamps'].append(current_datetime)
397
                    base_cost[energy_category_id]['values'].append(actual_value)
398
                    base_cost[energy_category_id]['subtotal'] += actual_value
399
400
        ################################################################################################################
401
        # Step 9: query reporting period energy input
402
        ################################################################################################################
403
        reporting_input = dict()
404 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
405
            for energy_category_id in energy_category_set:
406
                kgce = energy_category_dict[energy_category_id]['kgce']
407
                kgco2e = energy_category_dict[energy_category_id]['kgco2e']
408
409
                reporting_input[energy_category_id] = dict()
410
                reporting_input[energy_category_id]['timestamps'] = list()
411
                reporting_input[energy_category_id]['values'] = list()
412
                reporting_input[energy_category_id]['subtotal'] = Decimal(0.0)
413
                reporting_input[energy_category_id]['subtotal_in_kgce'] = Decimal(0.0)
414
                reporting_input[energy_category_id]['subtotal_in_kgco2e'] = Decimal(0.0)
415
                reporting_input[energy_category_id]['toppeak'] = Decimal(0.0)
416
                reporting_input[energy_category_id]['onpeak'] = Decimal(0.0)
417
                reporting_input[energy_category_id]['midpeak'] = Decimal(0.0)
418
                reporting_input[energy_category_id]['offpeak'] = Decimal(0.0)
419
420
                cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
421
                                      " FROM tbl_space_input_category_hourly "
422
                                      " WHERE space_id = %s "
423
                                      "     AND energy_category_id = %s "
424
                                      "     AND start_datetime_utc >= %s "
425
                                      "     AND start_datetime_utc < %s "
426
                                      " ORDER BY start_datetime_utc ",
427
                                      (space['id'],
428
                                       energy_category_id,
429
                                       reporting_start_datetime_utc,
430
                                       reporting_end_datetime_utc))
431
                rows_space_hourly = cursor_energy.fetchall()
432
433
                rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly,
434
                                                                                    reporting_start_datetime_utc,
435
                                                                                    reporting_end_datetime_utc,
436
                                                                                    period_type)
437
                for row_space_periodically in rows_space_periodically:
438
                    current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \
439
                                             timedelta(minutes=timezone_offset)
440
                    if period_type == 'hourly':
441
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
442
                    elif period_type == 'daily':
443
                        current_datetime = current_datetime_local.strftime('%Y-%m-%d')
444
                    elif period_type == 'monthly':
445
                        current_datetime = current_datetime_local.strftime('%Y-%m')
446
                    elif period_type == 'yearly':
447
                        current_datetime = current_datetime_local.strftime('%Y')
448
449
                    actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1]
450
                    reporting_input[energy_category_id]['timestamps'].append(current_datetime)
451
                    reporting_input[energy_category_id]['values'].append(actual_value)
452
                    reporting_input[energy_category_id]['subtotal'] += actual_value
453
                    reporting_input[energy_category_id]['subtotal_in_kgce'] += actual_value * kgce
454
                    reporting_input[energy_category_id]['subtotal_in_kgco2e'] += actual_value * kgco2e
455
456
                energy_category_tariff_dict = utilities.get_energy_category_peak_types(space['cost_center_id'],
457
                                                                                       energy_category_id,
458
                                                                                       reporting_start_datetime_utc,
459
                                                                                       reporting_end_datetime_utc)
460
                for row in rows_space_hourly:
461
                    peak_type = energy_category_tariff_dict.get(row[0], None)
462
                    if peak_type == 'toppeak':
463
                        reporting_input[energy_category_id]['toppeak'] += row[1]
464
                    elif peak_type == 'onpeak':
465
                        reporting_input[energy_category_id]['onpeak'] += row[1]
466
                    elif peak_type == 'midpeak':
467
                        reporting_input[energy_category_id]['midpeak'] += row[1]
468
                    elif peak_type == 'offpeak':
469
                        reporting_input[energy_category_id]['offpeak'] += row[1]
470
471
        ################################################################################################################
472
        # Step 10: query reporting period energy cost
473
        ################################################################################################################
474
        reporting_cost = dict()
475 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
476
            for energy_category_id in energy_category_set:
477
478
                reporting_cost[energy_category_id] = dict()
479
                reporting_cost[energy_category_id]['timestamps'] = list()
480
                reporting_cost[energy_category_id]['values'] = list()
481
                reporting_cost[energy_category_id]['subtotal'] = Decimal(0.0)
482
                reporting_cost[energy_category_id]['toppeak'] = Decimal(0.0)
483
                reporting_cost[energy_category_id]['onpeak'] = Decimal(0.0)
484
                reporting_cost[energy_category_id]['midpeak'] = Decimal(0.0)
485
                reporting_cost[energy_category_id]['offpeak'] = Decimal(0.0)
486
487
                cursor_billing.execute(" SELECT start_datetime_utc, actual_value "
488
                                       " FROM tbl_space_input_category_hourly "
489
                                       " WHERE space_id = %s "
490
                                       "     AND energy_category_id = %s "
491
                                       "     AND start_datetime_utc >= %s "
492
                                       "     AND start_datetime_utc < %s "
493
                                       " ORDER BY start_datetime_utc ",
494
                                       (space['id'],
495
                                        energy_category_id,
496
                                        reporting_start_datetime_utc,
497
                                        reporting_end_datetime_utc))
498
                rows_space_hourly = cursor_billing.fetchall()
499
500
                rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly,
501
                                                                                    reporting_start_datetime_utc,
502
                                                                                    reporting_end_datetime_utc,
503
                                                                                    period_type)
504
                for row_space_periodically in rows_space_periodically:
505
                    current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \
506
                                             timedelta(minutes=timezone_offset)
507
                    if period_type == 'hourly':
508
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
509
                    elif period_type == 'daily':
510
                        current_datetime = current_datetime_local.strftime('%Y-%m-%d')
511
                    elif period_type == 'monthly':
512
                        current_datetime = current_datetime_local.strftime('%Y-%m')
513
                    elif period_type == 'yearly':
514
                        current_datetime = current_datetime_local.strftime('%Y')
515
516
                    actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1]
517
                    reporting_cost[energy_category_id]['timestamps'].append(current_datetime)
518
                    reporting_cost[energy_category_id]['values'].append(actual_value)
519
                    reporting_cost[energy_category_id]['subtotal'] += actual_value
520
521
                energy_category_tariff_dict = utilities.get_energy_category_peak_types(space['cost_center_id'],
522
                                                                                       energy_category_id,
523
                                                                                       reporting_start_datetime_utc,
524
                                                                                       reporting_end_datetime_utc)
525
                for row in rows_space_hourly:
526
                    peak_type = energy_category_tariff_dict.get(row[0], None)
527
                    if peak_type == 'toppeak':
528
                        reporting_cost[energy_category_id]['toppeak'] += row[1]
529
                    elif peak_type == 'onpeak':
530
                        reporting_cost[energy_category_id]['onpeak'] += row[1]
531
                    elif peak_type == 'midpeak':
532
                        reporting_cost[energy_category_id]['midpeak'] += row[1]
533
                    elif peak_type == 'offpeak':
534
                        reporting_cost[energy_category_id]['offpeak'] += row[1]
535
        ################################################################################################################
536
        # Step 9: query tariff data
537
        ################################################################################################################
538
        parameters_data = dict()
539
        parameters_data['names'] = list()
540
        parameters_data['timestamps'] = list()
541
        parameters_data['values'] = list()
542 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
543
            for energy_category_id in energy_category_set:
544
                energy_category_tariff_dict = utilities.get_energy_category_tariffs(space['cost_center_id'],
545
                                                                                    energy_category_id,
546
                                                                                    reporting_start_datetime_utc,
547
                                                                                    reporting_end_datetime_utc)
548
                tariff_timestamp_list = list()
549
                tariff_value_list = list()
550
                for k, v in energy_category_tariff_dict.items():
551
                    # convert k from utc to local
552
                    k = k + timedelta(minutes=timezone_offset)
553
                    tariff_timestamp_list.append(k.isoformat()[0:19][0:19])
554
                    tariff_value_list.append(v)
555
556
                parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name'])
557
                parameters_data['timestamps'].append(tariff_timestamp_list)
558
                parameters_data['values'].append(tariff_value_list)
559
560
        ################################################################################################################
561
        # Step 10: query associated sensors and points data
562
        ################################################################################################################
563
564
        cnx_historical = mysql.connector.connect(**config.myems_historical_db)
565
        cursor_historical = cnx_historical.cursor()
566
567
        for point in point_list:
568
            point_values = []
569
            point_timestamps = []
570 View Code Duplication
            if point['object_type'] == 'ANALOG_VALUE':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
571
                query = (" SELECT utc_date_time, actual_value "
572
                         " FROM tbl_analog_value "
573
                         " WHERE point_id = %s "
574
                         "       AND utc_date_time BETWEEN %s AND %s "
575
                         " ORDER BY utc_date_time ")
576
                cursor_historical.execute(query, (point['id'],
577
                                                  reporting_start_datetime_utc,
578
                                                  reporting_end_datetime_utc))
579
                rows = cursor_historical.fetchall()
580
581
                if rows is not None and len(rows) > 0:
582
                    for row in rows:
583
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
584
                                                 timedelta(minutes=timezone_offset)
585
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
586
                        point_timestamps.append(current_datetime)
587
                        point_values.append(row[1])
588
589
            elif point['object_type'] == 'ENERGY_VALUE':
590
                query = (" SELECT utc_date_time, actual_value "
591
                         " FROM tbl_energy_value "
592
                         " WHERE point_id = %s "
593
                         "       AND utc_date_time BETWEEN %s AND %s "
594
                         " ORDER BY utc_date_time ")
595
                cursor_historical.execute(query, (point['id'],
596
                                                  reporting_start_datetime_utc,
597
                                                  reporting_end_datetime_utc))
598
                rows = cursor_historical.fetchall()
599
600
                if rows is not None and len(rows) > 0:
601
                    for row in rows:
602
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
603
                                                 timedelta(minutes=timezone_offset)
604
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
605
                        point_timestamps.append(current_datetime)
606
                        point_values.append(row[1])
607
            elif point['object_type'] == 'DIGITAL_VALUE':
608
                query = (" SELECT utc_date_time, actual_value "
609
                         " FROM tbl_digital_value "
610
                         " WHERE point_id = %s "
611
                         "       AND utc_date_time BETWEEN %s AND %s ")
612
                cursor_historical.execute(query, (point['id'],
613
                                                  reporting_start_datetime_utc,
614
                                                  reporting_end_datetime_utc))
615
                rows = cursor_historical.fetchall()
616
617
                if rows is not None and len(rows) > 0:
618
                    for row in rows:
619
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
620
                                                 timedelta(minutes=timezone_offset)
621
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
622
                        point_timestamps.append(current_datetime)
623
                        point_values.append(row[1])
624
625
            parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
626
            parameters_data['timestamps'].append(point_timestamps)
627
            parameters_data['values'].append(point_values)
628
629
        ################################################################################################################
630
        # Step 11: query child spaces energy input
631
        ################################################################################################################
632
        child_space_input = dict()
633
634 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
635
            for energy_category_id in energy_category_set:
636
                child_space_input[energy_category_id] = dict()
637
                child_space_input[energy_category_id]['child_space_names'] = list()
638
                child_space_input[energy_category_id]['subtotal'] = Decimal(0.0)
639
                child_space_input[energy_category_id]['subtotal_in_kgce'] = Decimal(0.0)
640
                child_space_input[energy_category_id]['subtotal_in_kgco2e'] = Decimal(0.0)
641
                kgce = energy_category_dict[energy_category_id]['kgce']
642
                kgco2e = energy_category_dict[energy_category_id]['kgco2e']
643
                for child_space in child_space_list:
644
                    child_space_input[energy_category_id]['child_space_names'].append(child_space['name'])
645
646
                    cursor_energy.execute(" SELECT SUM(actual_value) "
647
                                          " FROM tbl_space_input_category_hourly "
648
                                          " WHERE space_id = %s "
649
                                          "     AND energy_category_id = %s "
650
                                          "     AND start_datetime_utc >= %s "
651
                                          "     AND start_datetime_utc < %s "
652
                                          " ORDER BY start_datetime_utc ",
653
                                          (child_space['id'],
654
                                           energy_category_id,
655
                                           reporting_start_datetime_utc,
656
                                           reporting_end_datetime_utc))
657
                    row_subtotal = cursor_energy.fetchone()
658
659
                    subtotal = Decimal(0.0) if (row_subtotal is None or row_subtotal[0] is None) else row_subtotal[0]
660
                    child_space_input[energy_category_id]['subtotal'] = subtotal
661
                    child_space_input[energy_category_id]['subtotal_in_kgce'] = subtotal * kgce
662
                    child_space_input[energy_category_id]['subtotal_in_kgco2e'] = subtotal * kgco2e
663
664
        ################################################################################################################
665
        # Step 12: query child spaces energy cost
666
        ################################################################################################################
667
        child_space_cost = dict()
668
669
        if energy_category_set is not None and len(energy_category_set) > 0:
670
            for energy_category_id in energy_category_set:
671
                child_space_cost[energy_category_id] = dict()
672
                child_space_cost[energy_category_id]['child_space_names'] = list()
673
                child_space_cost[energy_category_id]['subtotal'] = Decimal(0.0)
674
                for child_space in child_space_list:
675
                    child_space_cost[energy_category_id]['child_space_names'].append(child_space['name'])
676
677
                    cursor_billing.execute(" SELECT SUM(actual_value) "
678
                                           " FROM tbl_space_input_category_hourly "
679
                                           " WHERE space_id = %s "
680
                                           "     AND energy_category_id = %s "
681
                                           "     AND start_datetime_utc >= %s "
682
                                           "     AND start_datetime_utc < %s "
683
                                           " ORDER BY start_datetime_utc ",
684
                                           (child_space['id'],
685
                                            energy_category_id,
686
                                            reporting_start_datetime_utc,
687
                                            reporting_end_datetime_utc))
688
                    row_subtotal = cursor_billing.fetchone()
689
690
                    subtotal = Decimal(0.0) if (row_subtotal is None or row_subtotal[0] is None) else row_subtotal[0]
691
                    child_space_cost[energy_category_id]['subtotal'] = subtotal
692
693
        ################################################################################################################
694
        # Step 12: construct the report
695
        ################################################################################################################
696
        if cursor_system:
697
            cursor_system.close()
698
        if cnx_system:
699
            cnx_system.disconnect()
700
701
        if cursor_energy:
702
            cursor_energy.close()
703
        if cnx_energy:
704
            cnx_energy.disconnect()
705
706
        if cursor_billing:
707
            cursor_billing.close()
708
        if cnx_billing:
709
            cnx_billing.disconnect()
710
711
        if cursor_historical:
712
            cursor_historical.close()
713
        if cnx_historical:
714
            cnx_historical.disconnect()
715
716
        result = dict()
717
718
        result['space'] = dict()
719
        result['space']['name'] = space['name']
720
        result['space']['area'] = space['area']
721
722
        result['base_period_input'] = dict()
723
        result['base_period_input']['names'] = list()
724
        result['base_period_input']['units'] = list()
725
        result['base_period_input']['timestamps'] = list()
726
        result['base_period_input']['values'] = list()
727
        result['base_period_input']['subtotals'] = list()
728
        result['base_period_input']['subtotals_in_kgce'] = list()
729
        result['base_period_input']['subtotals_in_kgco2e'] = list()
730
        result['base_period_input']['total_in_kgce'] = Decimal(0.0)
731
        result['base_period_input']['total_in_kgco2e'] = Decimal(0.0)
732 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
733
            for energy_category_id in energy_category_set:
734
                result['base_period_input']['names'].append(
735
                    energy_category_dict[energy_category_id]['name'])
736
                result['base_period_input']['units'].append(
737
                    energy_category_dict[energy_category_id]['unit_of_measure'])
738
                result['base_period_input']['timestamps'].append(
739
                    base_input[energy_category_id]['timestamps'])
740
                result['base_period_input']['values'].append(
741
                    base_input[energy_category_id]['values'])
742
                result['base_period_input']['subtotals'].append(
743
                    base_input[energy_category_id]['subtotal'])
744
                result['base_period_input']['subtotals_in_kgce'].append(
745
                    base_input[energy_category_id]['subtotal_in_kgce'])
746
                result['base_period_input']['subtotals_in_kgco2e'].append(
747
                    base_input[energy_category_id]['subtotal_in_kgco2e'])
748
                result['base_period_input']['total_in_kgce'] += \
749
                    base_input[energy_category_id]['subtotal_in_kgce']
750
                result['base_period_input']['total_in_kgco2e'] += \
751
                    base_input[energy_category_id]['subtotal_in_kgco2e']
752
753
        result['base_period_cost'] = dict()
754
        result['base_period_cost']['names'] = list()
755
        result['base_period_cost']['units'] = list()
756
        result['base_period_cost']['timestamps'] = list()
757
        result['base_period_cost']['values'] = list()
758
        result['base_period_cost']['subtotals'] = list()
759
        result['base_period_cost']['total'] = Decimal(0.0)
760 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
761
            for energy_category_id in energy_category_set:
762
                result['base_period_cost']['names'].append(
763
                    energy_category_dict[energy_category_id]['name'])
764
                result['base_period_cost']['units'].append(
765
                    energy_category_dict[energy_category_id]['unit_of_measure'])
766
                result['base_period_cost']['timestamps'].append(
767
                    base_cost[energy_category_id]['timestamps'])
768
                result['base_period_cost']['values'].append(
769
                    base_cost[energy_category_id]['values'])
770
                result['base_period_cost']['subtotals'].append(
771
                    base_cost[energy_category_id]['subtotal'])
772
                result['base_period_cost']['total'] += base_cost[energy_category_id]['subtotal']
773
774
        result['reporting_period_input'] = dict()
775
        result['reporting_period_input']['names'] = list()
776
        result['reporting_period_input']['energy_category_ids'] = list()
777
        result['reporting_period_input']['units'] = list()
778
        result['reporting_period_input']['timestamps'] = list()
779
        result['reporting_period_input']['values'] = list()
780
        result['reporting_period_input']['subtotals'] = list()
781
        result['reporting_period_input']['subtotals_in_kgce'] = list()
782
        result['reporting_period_input']['subtotals_in_kgco2e'] = list()
783
        result['reporting_period_input']['subtotals_per_unit_area'] = list()
784
        result['reporting_period_input']['toppeaks'] = list()
785
        result['reporting_period_input']['onpeaks'] = list()
786
        result['reporting_period_input']['midpeaks'] = list()
787
        result['reporting_period_input']['offpeaks'] = list()
788
        result['reporting_period_input']['increment_rates'] = list()
789
        result['reporting_period_input']['total_in_kgce'] = Decimal(0.0)
790
        result['reporting_period_input']['total_in_kgco2e'] = Decimal(0.0)
791
        result['reporting_period_input']['increment_rate_in_kgce'] = Decimal(0.0)
792
        result['reporting_period_input']['increment_rate_in_kgco2e'] = Decimal(0.0)
793
794
        if energy_category_set is not None and len(energy_category_set) > 0:
795
            for energy_category_id in energy_category_set:
796
                result['reporting_period_input']['names'].append(energy_category_dict[energy_category_id]['name'])
797
                result['reporting_period_input']['energy_category_ids'].append(energy_category_id)
798
                result['reporting_period_input']['units'].append(
799
                    energy_category_dict[energy_category_id]['unit_of_measure'])
800
                result['reporting_period_input']['timestamps'].append(
801
                    reporting_input[energy_category_id]['timestamps'])
802
                result['reporting_period_input']['values'].append(
803
                    reporting_input[energy_category_id]['values'])
804
                result['reporting_period_input']['subtotals'].append(
805
                    reporting_input[energy_category_id]['subtotal'])
806
                result['reporting_period_input']['subtotals_in_kgce'].append(
807
                    reporting_input[energy_category_id]['subtotal_in_kgce'])
808
                result['reporting_period_input']['subtotals_in_kgco2e'].append(
809
                    reporting_input[energy_category_id]['subtotal_in_kgco2e'])
810
                result['reporting_period_input']['subtotals_per_unit_area'].append(
811
                    reporting_input[energy_category_id]['subtotal'] / space['area']
812
                    if space['area'] > 0.0 else None)
813
                result['reporting_period_input']['toppeaks'].append(
814
                    reporting_input[energy_category_id]['toppeak'])
815
                result['reporting_period_input']['onpeaks'].append(
816
                    reporting_input[energy_category_id]['onpeak'])
817
                result['reporting_period_input']['midpeaks'].append(
818
                    reporting_input[energy_category_id]['midpeak'])
819
                result['reporting_period_input']['offpeaks'].append(
820
                    reporting_input[energy_category_id]['offpeak'])
821
                result['reporting_period_input']['increment_rates'].append(
822
                    (reporting_input[energy_category_id]['subtotal'] -
823
                     base_input[energy_category_id]['subtotal']) /
824
                    base_input[energy_category_id]['subtotal']
825
                    if base_input[energy_category_id]['subtotal'] > 0.0 else None)
826
                result['reporting_period_input']['total_in_kgce'] += \
827
                    reporting_input[energy_category_id]['subtotal_in_kgce']
828
                result['reporting_period_input']['total_in_kgco2e'] += \
829
                    reporting_input[energy_category_id]['subtotal_in_kgco2e']
830
831
        result['reporting_period_input']['total_in_kgco2e_per_unit_area'] = \
832
            result['reporting_period_input']['total_in_kgce'] / space['area'] if space['area'] > 0.0 else None
833
834
        result['reporting_period_input']['increment_rate_in_kgce'] = \
835
            (result['reporting_period_input']['total_in_kgce'] - result['base_period_input']['total_in_kgce']) / \
836
            result['base_period_input']['total_in_kgce'] \
837
            if result['base_period_input']['total_in_kgce'] > Decimal(0.0) else None
838
839
        result['reporting_period_input']['total_in_kgce_per_unit_area'] = \
840
            result['reporting_period_input']['total_in_kgco2e'] / space['area'] if space['area'] > 0.0 else None
841
842
        result['reporting_period_input']['increment_rate_in_kgco2e'] = \
843
            (result['reporting_period_input']['total_in_kgco2e'] - result['base_period_input']['total_in_kgco2e']) / \
844
            result['base_period_input']['total_in_kgco2e'] \
845
            if result['base_period_input']['total_in_kgco2e'] > Decimal(0.0) else None
846
847
        result['reporting_period_cost'] = dict()
848
        result['reporting_period_cost']['names'] = list()
849
        result['reporting_period_cost']['energy_category_ids'] = list()
850
        result['reporting_period_cost']['units'] = list()
851
        result['reporting_period_cost']['timestamps'] = list()
852
        result['reporting_period_cost']['values'] = list()
853
        result['reporting_period_cost']['subtotals'] = list()
854
        result['reporting_period_cost']['subtotals_per_unit_area'] = list()
855
        result['reporting_period_cost']['toppeaks'] = list()
856
        result['reporting_period_cost']['onpeaks'] = list()
857
        result['reporting_period_cost']['midpeaks'] = list()
858
        result['reporting_period_cost']['offpeaks'] = list()
859
        result['reporting_period_cost']['increment_rates'] = list()
860
        result['reporting_period_cost']['total'] = Decimal(0.0)
861
        result['reporting_period_cost']['total_per_unit_area'] = Decimal(0.0)
862
        result['reporting_period_cost']['total_increment_rate'] = Decimal(0.0)
863
        result['reporting_period_cost']['total_unit'] = config.currency_unit
864
865 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
866
            for energy_category_id in energy_category_set:
867
                result['reporting_period_cost']['names'].append(energy_category_dict[energy_category_id]['name'])
868
                result['reporting_period_cost']['energy_category_ids'].append(energy_category_id)
869
                result['reporting_period_cost']['units'].append(config.currency_unit)
870
                result['reporting_period_cost']['timestamps'].append(
871
                    reporting_cost[energy_category_id]['timestamps'])
872
                result['reporting_period_cost']['values'].append(
873
                    reporting_cost[energy_category_id]['values'])
874
                result['reporting_period_cost']['subtotals'].append(
875
                    reporting_cost[energy_category_id]['subtotal'])
876
                result['reporting_period_cost']['subtotals_per_unit_area'].append(
877
                    reporting_cost[energy_category_id]['subtotal'] / space['area']
878
                    if space['area'] > 0.0 else None)
879
                result['reporting_period_cost']['toppeaks'].append(
880
                    reporting_cost[energy_category_id]['toppeak'])
881
                result['reporting_period_cost']['onpeaks'].append(
882
                    reporting_cost[energy_category_id]['onpeak'])
883
                result['reporting_period_cost']['midpeaks'].append(
884
                    reporting_cost[energy_category_id]['midpeak'])
885
                result['reporting_period_cost']['offpeaks'].append(
886
                    reporting_cost[energy_category_id]['offpeak'])
887
                result['reporting_period_cost']['increment_rates'].append(
888
                    (reporting_cost[energy_category_id]['subtotal'] -
889
                     base_cost[energy_category_id]['subtotal']) /
890
                    base_cost[energy_category_id]['subtotal']
891
                    if base_cost[energy_category_id]['subtotal'] > 0.0 else None)
892
                result['reporting_period_cost']['total'] += reporting_cost[energy_category_id]['subtotal']
893
        result['reporting_period_cost']['total_per_unit_area'] = \
894
            result['reporting_period_cost']['total'] / space['area'] if space['area'] > 0.0 else None
895
896
        result['reporting_period_cost']['total_increment_rate'] = \
897
            (result['reporting_period_cost']['total'] - result['base_period_cost']['total']) / \
898
            result['reporting_period_cost']['total'] \
899
            if result['reporting_period_cost']['total'] > Decimal(0.0) else None
900
901
        result['parameters'] = {
902
            "names": parameters_data['names'],
903
            "timestamps": parameters_data['timestamps'],
904
            "values": parameters_data['values']
905
        }
906
907
        result['child_space_input'] = dict()
908
        result['child_space_input']['energy_category_names'] = list()
909
        result['child_space_input']['units'] = list()
910
        result['child_space_input']['child_space_names_array'] = list()
911
        result['child_space_input']['subtotals'] = list()
912
        result['child_space_input']['subtotals_in_kgce'] = list()
913
        result['child_space_input']['subtotals_in_kgco2e'] = list()
914 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
915
            for energy_category_id in energy_category_set:
916
                result['child_space_input']['energy_category_names'].append(energy_category_dict[energy_category_id]['name'])
917
                result['child_space_input']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
918
                result['child_space_input']['child_space_names_array'].append(
919
                    child_space_input[energy_category_id]['child_space_names'])
920
                result['child_space_input']['subtotals'].append(
921
                    child_space_input[energy_category_id]['subtotal'])
922
                result['child_space_input']['subtotals_in_kgce'].append(
923
                    child_space_input[energy_category_id]['subtotal_in_kgce'])
924
                result['child_space_input']['subtotals_in_kgco2e'].append(
925
                    child_space_input[energy_category_id]['subtotal_in_kgco2e'])
926
927
        result['child_space_cost'] = dict()
928
        result['child_space_cost']['energy_category_names'] = list()
929
        result['child_space_cost']['units'] = list()
930
        result['child_space_cost']['child_space_names_array'] = list()
931
        result['child_space_cost']['subtotals'] = list()
932
        if energy_category_set is not None and len(energy_category_set) > 0:
933
            for energy_category_id in energy_category_set:
934
                result['child_space_cost']['energy_category_names'].append(
935
                    energy_category_dict[energy_category_id]['name'])
936
                result['child_space_cost']['units'].append(config.currency_unit)
937
                result['child_space_cost']['child_space_names_array'].append(
938
                    child_space_cost[energy_category_id]['child_space_names'])
939
                result['child_space_cost']['subtotals'].append(
940
                    child_space_cost[energy_category_id]['subtotal'])
941
942
        resp.body = json.dumps(result)
943