reports.spaceincome   F
last analyzed

Complexity

Total Complexity 112

Size/Duplication

Total Lines 565
Duplicated Lines 5.49 %

Importance

Changes 0
Metric Value
eloc 397
dl 31
loc 565
rs 2
c 0
b 0
f 0
wmc 112

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Reporting.on_options() 0 3 1
A Reporting.__init__() 0 3 1
F Reporting.on_get() 31 531 110

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 reports.spaceincome 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
from core import utilities
7
from decimal import Decimal
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 income
28
    # Step 8: query reporting period energy income
29
    # Step 9: query tariff data
30
    # Step 10: query associated sensors and points data
31
    # Step 11: query child spaces energy income
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_START_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_END_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_END_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_START_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_START_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_END_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_END_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_END_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_billing = mysql.connector.connect(**config.myems_billing_db)
129
        cursor_billing = cnx_billing.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 View Code Duplication
        if row_space is None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
139
            if cursor_system:
140
                cursor_system.close()
141
            if cnx_system:
142
                cnx_system.disconnect()
143
144
            if cursor_billing:
145
                cursor_billing.close()
146
            if cnx_billing:
147
                cnx_billing.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_billing.execute(" SELECT DISTINCT(energy_category_id) "
167
                               " FROM tbl_space_output_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_billing.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_billing.execute(" SELECT DISTINCT(energy_category_id) "
179
                               " FROM tbl_space_output_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_billing.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_billing:
201
                cursor_billing.close()
202
            if cnx_billing:
203
                cnx_billing.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 income
262
        ################################################################################################################
263
        base = dict()
264
        if energy_category_set is not None and len(energy_category_set) > 0:
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_billing.execute(" SELECT start_datetime_utc, actual_value "
272
                                       " FROM tbl_space_output_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_billing.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)
0 ignored issues
show
introduced by
The variable current_datetime does not seem to be defined for all execution paths.
Loading history...
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 income
307
        ################################################################################################################
308
        reporting = dict()
309
        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
316
                cursor_billing.execute(" SELECT start_datetime_utc, actual_value "
317
                                       " FROM tbl_space_output_category_hourly "
318
                                       " WHERE space_id = %s "
319
                                       "     AND energy_category_id = %s "
320
                                       "     AND start_datetime_utc >= %s "
321
                                       "     AND start_datetime_utc < %s "
322
                                       " ORDER BY start_datetime_utc ",
323
                                       (space['id'],
324
                                        energy_category_id,
325
                                        reporting_start_datetime_utc,
326
                                        reporting_end_datetime_utc))
327
                rows_space_hourly = cursor_billing.fetchall()
328
329
                rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly,
330
                                                                                    reporting_start_datetime_utc,
331
                                                                                    reporting_end_datetime_utc,
332
                                                                                    period_type)
333
                for row_space_periodically in rows_space_periodically:
334
                    current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \
335
                                             timedelta(minutes=timezone_offset)
336
                    if period_type == 'hourly':
337
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
338
                    elif period_type == 'daily':
339
                        current_datetime = current_datetime_local.strftime('%Y-%m-%d')
340
                    elif period_type == 'monthly':
341
                        current_datetime = current_datetime_local.strftime('%Y-%m')
342
                    elif period_type == 'yearly':
343
                        current_datetime = current_datetime_local.strftime('%Y')
344
345
                    actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1]
346
                    reporting[energy_category_id]['timestamps'].append(current_datetime)
347
                    reporting[energy_category_id]['values'].append(actual_value)
348
                    reporting[energy_category_id]['subtotal'] += actual_value
349
350
        ################################################################################################################
351
        # Step 9: query tariff data
352
        ################################################################################################################
353
        parameters_data = dict()
354
        parameters_data['names'] = list()
355
        parameters_data['timestamps'] = list()
356
        parameters_data['values'] = list()
357
        if energy_category_set is not None and len(energy_category_set) > 0:
358
            for energy_category_id in energy_category_set:
359
                energy_category_tariff_dict = utilities.get_energy_category_tariffs(space['cost_center_id'],
360
                                                                                    energy_category_id,
361
                                                                                    reporting_start_datetime_utc,
362
                                                                                    reporting_end_datetime_utc)
363
                tariff_timestamp_list = list()
364
                tariff_value_list = list()
365
                for k, v in energy_category_tariff_dict.items():
366
                    # convert k from utc to local
367
                    k = k + timedelta(minutes=timezone_offset)
368
                    tariff_timestamp_list.append(k.isoformat()[0:19][0:19])
369
                    tariff_value_list.append(v)
370
371
                parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name'])
372
                parameters_data['timestamps'].append(tariff_timestamp_list)
373
                parameters_data['values'].append(tariff_value_list)
374
375
        ################################################################################################################
376
        # Step 10: query associated sensors and points data
377
        ################################################################################################################
378
        for point in point_list:
379
            point_values = []
380
            point_timestamps = []
381
            if point['object_type'] == 'ANALOG_VALUE':
382
                query = (" SELECT utc_date_time, actual_value "
383
                         " FROM tbl_analog_value "
384
                         " WHERE point_id = %s "
385
                         "       AND utc_date_time BETWEEN %s AND %s "
386
                         " ORDER BY utc_date_time ")
387
                cursor_historical.execute(query, (point['id'],
388
                                                  reporting_start_datetime_utc,
389
                                                  reporting_end_datetime_utc))
390
                rows = cursor_historical.fetchall()
391
392
                if rows is not None and len(rows) > 0:
393
                    for row in rows:
394
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
395
                                                 timedelta(minutes=timezone_offset)
396
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
397
                        point_timestamps.append(current_datetime)
398
                        point_values.append(row[1])
399
400
            elif point['object_type'] == 'ENERGY_VALUE':
401
                query = (" SELECT utc_date_time, actual_value "
402
                         " FROM tbl_energy_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
            elif point['object_type'] == 'DIGITAL_VALUE':
419
                query = (" SELECT utc_date_time, actual_value "
420
                         " FROM tbl_digital_value "
421
                         " WHERE point_id = %s "
422
                         "       AND utc_date_time BETWEEN %s AND %s ")
423
                cursor_historical.execute(query, (point['id'],
424
                                                  reporting_start_datetime_utc,
425
                                                  reporting_end_datetime_utc))
426
                rows = cursor_historical.fetchall()
427
428
                if rows is not None and len(rows) > 0:
429
                    for row in rows:
430
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
431
                                                 timedelta(minutes=timezone_offset)
432
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
433
                        point_timestamps.append(current_datetime)
434
                        point_values.append(row[1])
435
436
            parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
437
            parameters_data['timestamps'].append(point_timestamps)
438
            parameters_data['values'].append(point_values)
439
440
        ################################################################################################################
441
        # Step 11: query child spaces energy income
442
        ################################################################################################################
443
        child_space_data = dict()
444
445
        if energy_category_set is not None and len(energy_category_set) > 0:
446
            for energy_category_id in energy_category_set:
447
                child_space_data[energy_category_id] = dict()
448
                child_space_data[energy_category_id]['child_space_names'] = list()
449
                child_space_data[energy_category_id]['subtotals'] = list()
450
                for child_space in child_space_list:
451
                    child_space_data[energy_category_id]['child_space_names'].append(child_space['name'])
452
453
                    cursor_billing.execute(" SELECT SUM(actual_value) "
454
                                           " FROM tbl_space_output_category_hourly "
455
                                           " WHERE space_id = %s "
456
                                           "     AND energy_category_id = %s "
457
                                           "     AND start_datetime_utc >= %s "
458
                                           "     AND start_datetime_utc < %s "
459
                                           " ORDER BY start_datetime_utc ",
460
                                           (child_space['id'],
461
                                            energy_category_id,
462
                                            reporting_start_datetime_utc,
463
                                            reporting_end_datetime_utc))
464
                    row_subtotal = cursor_billing.fetchone()
465
466
                    subtotal = Decimal(0.0) if (row_subtotal is None or row_subtotal[0] is None) else row_subtotal[0]
467
                    child_space_data[energy_category_id]['subtotals'].append(subtotal)
468
469
        ################################################################################################################
470
        # Step 12: construct the report
471
        ################################################################################################################
472
        if cursor_system:
473
            cursor_system.close()
474
        if cnx_system:
475
            cnx_system.disconnect()
476
477
        if cursor_billing:
478
            cursor_billing.close()
479
        if cnx_billing:
480
            cnx_billing.disconnect()
481
482
        result = dict()
483
484
        result['space'] = dict()
485
        result['space']['name'] = space['name']
486
        result['space']['area'] = space['area']
487
488
        result['base_period'] = dict()
489
        result['base_period']['names'] = list()
490
        result['base_period']['units'] = list()
491
        result['base_period']['timestamps'] = list()
492
        result['base_period']['values'] = list()
493
        result['base_period']['subtotals'] = list()
494
        result['base_period']['total'] = Decimal(0.0)
495
        if energy_category_set is not None and len(energy_category_set) > 0:
496
            for energy_category_id in energy_category_set:
497
                result['base_period']['names'].append(energy_category_dict[energy_category_id]['name'])
498
                result['base_period']['units'].append(config.currency_unit)
499
                result['base_period']['timestamps'].append(base[energy_category_id]['timestamps'])
500
                result['base_period']['values'].append(base[energy_category_id]['values'])
501
                result['base_period']['subtotals'].append(base[energy_category_id]['subtotal'])
502
                result['base_period']['total'] += base[energy_category_id]['subtotal']
503
504
        result['reporting_period'] = dict()
505
        result['reporting_period']['names'] = list()
506
        result['reporting_period']['energy_category_ids'] = list()
507
        result['reporting_period']['units'] = list()
508
        result['reporting_period']['timestamps'] = list()
509
        result['reporting_period']['values'] = list()
510
        result['reporting_period']['subtotals'] = list()
511
        result['reporting_period']['subtotals_per_unit_area'] = list()
512
        result['reporting_period']['increment_rates'] = list()
513
        result['reporting_period']['total'] = Decimal(0.0)
514
        result['reporting_period']['total_per_unit_area'] = Decimal(0.0)
515
        result['reporting_period']['total_increment_rate'] = Decimal(0.0)
516
        result['reporting_period']['total_unit'] = config.currency_unit
517
518 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...
519
            for energy_category_id in energy_category_set:
520
                result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name'])
521
                result['reporting_period']['energy_category_ids'].append(energy_category_id)
522
                result['reporting_period']['units'].append(config.currency_unit)
523
                result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps'])
524
                result['reporting_period']['values'].append(reporting[energy_category_id]['values'])
525
                result['reporting_period']['subtotals'].append(reporting[energy_category_id]['subtotal'])
526
                result['reporting_period']['subtotals_per_unit_area'].append(
527
                    reporting[energy_category_id]['subtotal'] / space['area'] if space['area'] > 0.0 else None)
528
                result['reporting_period']['increment_rates'].append(
529
                    (reporting[energy_category_id]['subtotal'] - base[energy_category_id]['subtotal']) /
530
                    base[energy_category_id]['subtotal']
531
                    if base[energy_category_id]['subtotal'] > 0.0 else None)
532
                result['reporting_period']['total'] += reporting[energy_category_id]['subtotal']
533
534
        result['reporting_period']['total_per_unit_area'] = \
535
            result['reporting_period']['total'] / space['area'] if space['area'] > 0.0 else None
536
537
        result['reporting_period']['total_increment_rate'] = \
538
            (result['reporting_period']['total'] - result['base_period']['total']) / \
539
            result['base_period']['total'] \
540
            if result['base_period']['total'] > Decimal(0.0) else None
541
542
        result['parameters'] = {
543
            "names": parameters_data['names'],
544
            "timestamps": parameters_data['timestamps'],
545
            "values": parameters_data['values']
546
        }
547
548
        result['child_space'] = dict()
549
        result['child_space']['energy_category_names'] = list()  # 1D array [energy category]
550
        result['child_space']['units'] = list()  # 1D array [energy category]
551
        result['child_space']['child_space_names_array'] = list()  # 2D array [energy category][child space]
552
        result['child_space']['subtotals_array'] = list()  # 2D array [energy category][child space]
553
        result['child_space']['total_unit'] = config.currency_unit
554
555
        if energy_category_set is not None and len(energy_category_set) > 0:
556
            for energy_category_id in energy_category_set:
557
                result['child_space']['energy_category_names'].append(energy_category_dict[energy_category_id]['name'])
558
                result['child_space']['units'].append(config.currency_unit)
559
                result['child_space']['child_space_names_array'].append(
560
                    child_space_data[energy_category_id]['child_space_names'])
561
                result['child_space']['subtotals_array'].append(
562
                    child_space_data[energy_category_id]['subtotals'])
563
564
        resp.body = json.dumps(result)
565