Issues (1656)

myems-api/reports/equipmentincome.py (3 issues)

1
import re
2
from datetime import datetime, timedelta, timezone
3
from decimal import Decimal
4
import falcon
5
import mysql.connector
6
import simplejson as json
7
import config
8
import excelexporters.equipmentincome
9
from core import utilities
10
from core.useractivity import access_control, api_key_control
11
12
13
class Reporting:
14
    def __init__(self):
15
        """"Initializes Reporting"""
16
        pass
17
18
    @staticmethod
19
    def on_options(req, resp):
20
        _ = req
21
        resp.status = falcon.HTTP_200
22
23
    ####################################################################################################################
24
    # PROCEDURES
25
    # Step 1: valid parameters
26
    # Step 2: query the equipment
27
    # Step 3: query energy categories
28
    # Step 4: query associated points
29
    # Step 5: query base period energy income
30
    # Step 6: query reporting period energy income
31
    # Step 7: query tariff data
32
    # Step 8: query associated points data
33
    # Step 9: construct the report
34
    ####################################################################################################################
35
    @staticmethod
36
    def on_get(req, resp):
37
        if 'API-KEY' not in req.headers or \
38
                not isinstance(req.headers['API-KEY'], str) or \
39
                len(str.strip(req.headers['API-KEY'])) == 0:
40
            access_control(req)
41
        else:
42
            api_key_control(req)
43
        print(req.params)
44
        equipment_id = req.params.get('equipmentid')
45
        equipment_uuid = req.params.get('equipmentuuid')
46
        period_type = req.params.get('periodtype')
47
        base_period_start_datetime_local = req.params.get('baseperiodstartdatetime')
48
        base_period_end_datetime_local = req.params.get('baseperiodenddatetime')
49
        reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime')
50
        reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime')
51
        language = req.params.get('language')
52
        quick_mode = req.params.get('quickmode')
53
54
        ################################################################################################################
55
        # Step 1: valid parameters
56
        ################################################################################################################
57
        if equipment_id is None and equipment_uuid is None:
58
            raise falcon.HTTPError(status=falcon.HTTP_400,
59
                                   title='API.BAD_REQUEST',
60
                                   description='API.INVALID_EQUIPMENT_ID')
61
62
        if equipment_id is not None:
63
            equipment_id = str.strip(equipment_id)
64
            if not equipment_id.isdigit() or int(equipment_id) <= 0:
65
                raise falcon.HTTPError(status=falcon.HTTP_400,
66
                                       title='API.BAD_REQUEST',
67
                                       description='API.INVALID_EQUIPMENT_ID')
68
69
        if equipment_uuid is not None:
70
            regex = re.compile(r'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
71
            match = regex.match(str.strip(equipment_uuid))
72
            if not bool(match):
73
                raise falcon.HTTPError(status=falcon.HTTP_400,
74
                                       title='API.BAD_REQUEST',
75
                                       description='API.INVALID_EQUIPMENT_UUID')
76
77
        if period_type is None:
78
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
79
                                   description='API.INVALID_PERIOD_TYPE')
80
        else:
81
            period_type = str.strip(period_type)
82
            if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']:
83
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
84
                                       description='API.INVALID_PERIOD_TYPE')
85
86
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
87
        if config.utc_offset[0] == '-':
88
            timezone_offset = -timezone_offset
89
90
        base_start_datetime_utc = None
91
        if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0:
92
            base_period_start_datetime_local = str.strip(base_period_start_datetime_local)
93
            try:
94
                base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S')
95
            except ValueError:
96
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
97
                                       description="API.INVALID_BASE_PERIOD_START_DATETIME")
98
            base_start_datetime_utc = \
99
                base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset)
100
            # nomalize the start datetime
101
            if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30:
102
                base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0)
103
            else:
104
                base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0)
105
106
        base_end_datetime_utc = None
107
        if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0:
108
            base_period_end_datetime_local = str.strip(base_period_end_datetime_local)
109
            try:
110
                base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S')
111
            except ValueError:
112
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
113
                                       description="API.INVALID_BASE_PERIOD_END_DATETIME")
114
            base_end_datetime_utc = \
115
                base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset)
116
117
        if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \
118
                base_start_datetime_utc >= base_end_datetime_utc:
119
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
120
                                   description='API.INVALID_BASE_PERIOD_END_DATETIME')
121
122
        if reporting_period_start_datetime_local is None:
123
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
124
                                   description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
125
        else:
126
            reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local)
127
            try:
128
                reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local,
129
                                                                 '%Y-%m-%dT%H:%M:%S')
130
            except ValueError:
131
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
132
                                       description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
133
            reporting_start_datetime_utc = \
134
                reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset)
135
            # nomalize the start datetime
136
            if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30:
137
                reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0)
138
            else:
139
                reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0)
140
141
        if reporting_period_end_datetime_local is None:
142
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
143
                                   description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
144
        else:
145
            reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local)
146
            try:
147
                reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local,
148
                                                               '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
149
                                             timedelta(minutes=timezone_offset)
150
            except ValueError:
151
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
152
                                       description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
153
154
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
155
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
156
                                   description='API.INVALID_REPORTING_PERIOD_END_DATETIME')
157
158
        # if turn quick mode on, do not return parameters data and excel file
159
        is_quick_mode = False
160
        if quick_mode is not None and \
161
                len(str.strip(quick_mode)) > 0 and \
162
                str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'):
163
            is_quick_mode = True
164
165
        trans = utilities.get_translation(language)
166
        trans.install()
167
        _ = trans.gettext
168
169
        ################################################################################################################
170
        # Step 2: query the equipment
171
        ################################################################################################################
172
        cnx_system = mysql.connector.connect(**config.myems_system_db)
173
        cursor_system = cnx_system.cursor()
174
175
        cnx_billing = mysql.connector.connect(**config.myems_billing_db)
176
        cursor_billing = cnx_billing.cursor()
177
178
        cnx_historical = mysql.connector.connect(**config.myems_historical_db)
179
        cursor_historical = cnx_historical.cursor()
180
181
        if equipment_id is not None:
182
            cursor_system.execute(" SELECT id, name, cost_center_id "
183
                                  " FROM tbl_equipments "
184
                                  " WHERE id = %s ", (equipment_id,))
185
            row_equipment = cursor_system.fetchone()
186
        elif equipment_uuid is not None:
187
            cursor_system.execute(" SELECT id, name, cost_center_id "
188
                                  " FROM tbl_equipments "
189
                                  " WHERE uuid = %s ", (equipment_uuid,))
190
            row_equipment = cursor_system.fetchone()
191
192
        if row_equipment is None:
0 ignored issues
show
The variable row_equipment does not seem to be defined for all execution paths.
Loading history...
193
            if cursor_system:
194
                cursor_system.close()
195
            if cnx_system:
196
                cnx_system.close()
197
198
            if cursor_billing:
199
                cursor_billing.close()
200
            if cnx_billing:
201
                cnx_billing.close()
202
203
            if cursor_historical:
204
                cursor_historical.close()
205
            if cnx_historical:
206
                cnx_historical.close()
207
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.EQUIPMENT_NOT_FOUND')
208
209
        equipment = dict()
210
        equipment['id'] = row_equipment[0]
211
        equipment['name'] = row_equipment[1]
212
        equipment['cost_center_id'] = row_equipment[2]
213
214
        ################################################################################################################
215
        # Step 3: query energy categories
216
        ################################################################################################################
217
        energy_category_set = set()
218
        # query energy categories in base period
219
        cursor_billing.execute(" SELECT DISTINCT(energy_category_id) "
220
                               " FROM tbl_equipment_output_category_hourly "
221
                               " WHERE equipment_id = %s "
222
                               "     AND start_datetime_utc >= %s "
223
                               "     AND start_datetime_utc < %s ",
224
                               (equipment['id'], base_start_datetime_utc, base_end_datetime_utc))
225
        rows_energy_categories = cursor_billing.fetchall()
226
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
227
            for row_energy_category in rows_energy_categories:
228
                energy_category_set.add(row_energy_category[0])
229
230
        # query energy categories in reporting period
231
        cursor_billing.execute(" SELECT DISTINCT(energy_category_id) "
232
                               " FROM tbl_equipment_output_category_hourly "
233
                               " WHERE equipment_id = %s "
234
                               "     AND start_datetime_utc >= %s "
235
                               "     AND start_datetime_utc < %s ",
236
                               (equipment['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
237
        rows_energy_categories = cursor_billing.fetchall()
238
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
239
            for row_energy_category in rows_energy_categories:
240
                energy_category_set.add(row_energy_category[0])
241
242
        # query all energy categories in base period and reporting period
243
        cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e "
244
                              " FROM tbl_energy_categories "
245
                              " ORDER BY id ", )
246
        rows_energy_categories = cursor_system.fetchall()
247
        if rows_energy_categories is None or len(rows_energy_categories) == 0:
248
            if cursor_system:
249
                cursor_system.close()
250
            if cnx_system:
251
                cnx_system.close()
252
253
            if cursor_billing:
254
                cursor_billing.close()
255
            if cnx_billing:
256
                cnx_billing.close()
257
258
            if cursor_historical:
259
                cursor_historical.close()
260
            if cnx_historical:
261
                cnx_historical.close()
262
            raise falcon.HTTPError(status=falcon.HTTP_404,
263
                                   title='API.NOT_FOUND',
264
                                   description='API.ENERGY_CATEGORY_NOT_FOUND')
265
        energy_category_dict = dict()
266
        for row_energy_category in rows_energy_categories:
267
            if row_energy_category[0] in energy_category_set:
268
                energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1],
269
                                                                "unit_of_measure": row_energy_category[2],
270
                                                                "kgce": row_energy_category[3],
271
                                                                "kgco2e": row_energy_category[4]}
272
273
        ################################################################################################################
274
        # Step 4: query associated points
275
        ################################################################################################################
276
        point_list = list()
277
        cursor_system.execute(" SELECT p.id, ep.name, p.units, p.object_type  "
278
                              " FROM tbl_equipments e, tbl_equipments_parameters ep, tbl_points p "
279
                              " WHERE e.id = %s AND e.id = ep.equipment_id AND ep.parameter_type = 'point' "
280
                              "       AND ep.point_id = p.id "
281
                              " ORDER BY p.id ", (equipment['id'],))
282
        rows_points = cursor_system.fetchall()
283
        if rows_points is not None and len(rows_points) > 0:
284
            for row in rows_points:
285
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
286
287
        ################################################################################################################
288
        # Step 5: query base period energy income
289
        ################################################################################################################
290
        base = dict()
291
        if energy_category_set is not None and len(energy_category_set) > 0:
292
            for energy_category_id in energy_category_set:
293
                base[energy_category_id] = dict()
294
                base[energy_category_id]['timestamps'] = list()
295
                base[energy_category_id]['values'] = list()
296
                base[energy_category_id]['subtotal'] = Decimal(0.0)
297
298
                cursor_billing.execute(" SELECT start_datetime_utc, actual_value "
299
                                       " FROM tbl_equipment_output_category_hourly "
300
                                       " WHERE equipment_id = %s "
301
                                       "     AND energy_category_id = %s "
302
                                       "     AND start_datetime_utc >= %s "
303
                                       "     AND start_datetime_utc < %s "
304
                                       " ORDER BY start_datetime_utc ",
305
                                       (equipment['id'],
306
                                        energy_category_id,
307
                                        base_start_datetime_utc,
308
                                        base_end_datetime_utc))
309
                rows_equipment_hourly = cursor_billing.fetchall()
310
311
                rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly,
312
                                                                                        base_start_datetime_utc,
313
                                                                                        base_end_datetime_utc,
314
                                                                                        period_type)
315
                for row_equipment_periodically in rows_equipment_periodically:
316
                    current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \
317
                                             timedelta(minutes=timezone_offset)
318
                    if period_type == 'hourly':
319
                        current_datetime = current_datetime_local.isoformat()[0:19]
320
                    elif period_type == 'daily':
321
                        current_datetime = current_datetime_local.isoformat()[0:10]
322
                    elif period_type == 'weekly':
323
                        current_datetime = current_datetime_local.isoformat()[0:10]
324
                    elif period_type == 'monthly':
325
                        current_datetime = current_datetime_local.isoformat()[0:7]
326
                    elif period_type == 'yearly':
327
                        current_datetime = current_datetime_local.isoformat()[0:4]
328
329
                    actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \
330
                        else row_equipment_periodically[1]
331
                    base[energy_category_id]['timestamps'].append(current_datetime)
0 ignored issues
show
The variable current_datetime does not seem to be defined for all execution paths.
Loading history...
332
                    base[energy_category_id]['values'].append(actual_value)
333
                    base[energy_category_id]['subtotal'] += actual_value
334
335
        ################################################################################################################
336
        # Step 8: query reporting period energy income
337
        ################################################################################################################
338
        reporting = dict()
339
        if energy_category_set is not None and len(energy_category_set) > 0:
340
            for energy_category_id in energy_category_set:
341
                reporting[energy_category_id] = dict()
342
                reporting[energy_category_id]['timestamps'] = list()
343
                reporting[energy_category_id]['values'] = list()
344
                reporting[energy_category_id]['subtotal'] = Decimal(0.0)
345
346
                cursor_billing.execute(" SELECT start_datetime_utc, actual_value "
347
                                       " FROM tbl_equipment_output_category_hourly "
348
                                       " WHERE equipment_id = %s "
349
                                       "     AND energy_category_id = %s "
350
                                       "     AND start_datetime_utc >= %s "
351
                                       "     AND start_datetime_utc < %s "
352
                                       " ORDER BY start_datetime_utc ",
353
                                       (equipment['id'],
354
                                        energy_category_id,
355
                                        reporting_start_datetime_utc,
356
                                        reporting_end_datetime_utc))
357
                rows_equipment_hourly = cursor_billing.fetchall()
358
359
                rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly,
360
                                                                                        reporting_start_datetime_utc,
361
                                                                                        reporting_end_datetime_utc,
362
                                                                                        period_type)
363
                for row_equipment_periodically in rows_equipment_periodically:
364
                    current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \
365
                                             timedelta(minutes=timezone_offset)
366
                    if period_type == 'hourly':
367
                        current_datetime = current_datetime_local.isoformat()[0:19]
368
                    elif period_type == 'daily':
369
                        current_datetime = current_datetime_local.isoformat()[0:10]
370
                    elif period_type == 'weekly':
371
                        current_datetime = current_datetime_local.isoformat()[0:10]
372
                    elif period_type == 'monthly':
373
                        current_datetime = current_datetime_local.isoformat()[0:7]
374
                    elif period_type == 'yearly':
375
                        current_datetime = current_datetime_local.isoformat()[0:4]
376
377
                    actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \
378
                        else row_equipment_periodically[1]
379
                    reporting[energy_category_id]['timestamps'].append(current_datetime)
380
                    reporting[energy_category_id]['values'].append(actual_value)
381
                    reporting[energy_category_id]['subtotal'] += actual_value
382
383
        ################################################################################################################
384
        # Step 9: query tariff data
385
        ################################################################################################################
386
        parameters_data = dict()
387
        parameters_data['names'] = list()
388
        parameters_data['timestamps'] = list()
389
        parameters_data['values'] = list()
390
        if not is_quick_mode:
391
            if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0:
392
                for energy_category_id in energy_category_set:
393
                    energy_category_tariff_dict = utilities.get_energy_category_tariffs(equipment['cost_center_id'],
394
                                                                                        energy_category_id,
395
                                                                                        reporting_start_datetime_utc,
396
                                                                                        reporting_end_datetime_utc)
397
                    tariff_timestamp_list = list()
398
                    tariff_value_list = list()
399
                    for k, v in energy_category_tariff_dict.items():
400
                        # convert k from utc to local
401
                        k = k + timedelta(minutes=timezone_offset)
402
                        tariff_timestamp_list.append(k.isoformat()[0:19])
403
                        tariff_value_list.append(v)
404
405
                    parameters_data['names'].append(_('Tariff')
406
                                                    + '-' + energy_category_dict[energy_category_id]['name'])
407
                    parameters_data['timestamps'].append(tariff_timestamp_list)
408
                    parameters_data['values'].append(tariff_value_list)
409
410
        ################################################################################################################
411
        # Step 10: query associated points data
412
        ################################################################################################################
413
        if not is_quick_mode:
414
            for point in point_list:
415
                point_values = []
416
                point_timestamps = []
417
                if point['object_type'] == 'ENERGY_VALUE':
418
                    query = (" SELECT utc_date_time, actual_value "
419
                             " FROM tbl_energy_value "
420
                             " WHERE point_id = %s "
421
                             "       AND utc_date_time BETWEEN %s AND %s "
422
                             " ORDER BY utc_date_time ")
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.isoformat()[0:19]
433
                            point_timestamps.append(current_datetime)
434
                            point_values.append(row[1])
435
                elif point['object_type'] == 'ANALOG_VALUE':
436
                    query = (" SELECT utc_date_time, actual_value "
437
                             " FROM tbl_analog_value "
438
                             " WHERE point_id = %s "
439
                             "       AND utc_date_time BETWEEN %s AND %s "
440
                             " ORDER BY utc_date_time ")
441
                    cursor_historical.execute(query, (point['id'],
442
                                                      reporting_start_datetime_utc,
443
                                                      reporting_end_datetime_utc))
444
                    rows = cursor_historical.fetchall()
445
446
                    if rows is not None and len(rows) > 0:
447
                        for row in rows:
448
                            current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
449
                                                     timedelta(minutes=timezone_offset)
450
                            current_datetime = current_datetime_local.isoformat()[0:19]
451
                            point_timestamps.append(current_datetime)
452
                            point_values.append(row[1])
453
                elif point['object_type'] == 'DIGITAL_VALUE':
454
                    query = (" SELECT utc_date_time, actual_value "
455
                             " FROM tbl_digital_value "
456
                             " WHERE point_id = %s "
457
                             "       AND utc_date_time BETWEEN %s AND %s "
458
                             " ORDER BY utc_date_time ")
459
                    cursor_historical.execute(query, (point['id'],
460
                                                      reporting_start_datetime_utc,
461
                                                      reporting_end_datetime_utc))
462
                    rows = cursor_historical.fetchall()
463
464
                    if rows is not None and len(rows) > 0:
465
                        for row in rows:
466
                            current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
467
                                                     timedelta(minutes=timezone_offset)
468
                            current_datetime = current_datetime_local.isoformat()[0:19]
469
                            point_timestamps.append(current_datetime)
470
                            point_values.append(row[1])
471
472
                parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
473
                parameters_data['timestamps'].append(point_timestamps)
474
                parameters_data['values'].append(point_values)
475
476
        ################################################################################################################
477
        # Step 12: construct the report
478
        ################################################################################################################
479
        if cursor_system:
480
            cursor_system.close()
481
        if cnx_system:
482
            cnx_system.close()
483
484
        if cursor_billing:
485
            cursor_billing.close()
486
        if cnx_billing:
487
            cnx_billing.close()
488
489
        if cursor_historical:
490
            cursor_historical.close()
491
        if cnx_historical:
492
            cnx_historical.close()
493
494
        result = dict()
495
496
        result['equipment'] = dict()
497
        result['equipment']['name'] = equipment['name']
498
499
        result['base_period'] = dict()
500
        result['base_period']['names'] = list()
501
        result['base_period']['units'] = list()
502
        result['base_period']['timestamps'] = list()
503
        result['base_period']['values'] = list()
504
        result['base_period']['subtotals'] = list()
505
        result['base_period']['total'] = Decimal(0.0)
506
        if energy_category_set is not None and len(energy_category_set) > 0:
507
            for energy_category_id in energy_category_set:
508
                result['base_period']['names'].append(energy_category_dict[energy_category_id]['name'])
509
                result['base_period']['units'].append(config.currency_unit)
510
                result['base_period']['timestamps'].append(base[energy_category_id]['timestamps'])
511
                result['base_period']['values'].append(base[energy_category_id]['values'])
512
                result['base_period']['subtotals'].append(base[energy_category_id]['subtotal'])
513
                result['base_period']['total'] += base[energy_category_id]['subtotal']
514
515
        result['reporting_period'] = dict()
516
        result['reporting_period']['names'] = list()
517
        result['reporting_period']['energy_category_ids'] = list()
518
        result['reporting_period']['units'] = list()
519
        result['reporting_period']['timestamps'] = list()
520
        result['reporting_period']['values'] = list()
521
        result['reporting_period']['rates'] = list()
522
        result['reporting_period']['subtotals'] = list()
523
        result['reporting_period']['subtotals_per_unit_area'] = list()
524
        result['reporting_period']['increment_rates'] = list()
525
        result['reporting_period']['total'] = Decimal(0.0)
526
        result['reporting_period']['total_per_unit_area'] = Decimal(0.0)
527
        result['reporting_period']['total_increment_rate'] = Decimal(0.0)
528
        result['reporting_period']['total_unit'] = config.currency_unit
529
530 View Code Duplication
        if energy_category_set is not None and len(energy_category_set) > 0:
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
531
            for energy_category_id in energy_category_set:
532
                result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name'])
533
                result['reporting_period']['energy_category_ids'].append(energy_category_id)
534
                result['reporting_period']['units'].append(config.currency_unit)
535
                result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps'])
536
                result['reporting_period']['values'].append(reporting[energy_category_id]['values'])
537
                result['reporting_period']['subtotals'].append(reporting[energy_category_id]['subtotal'])
538
                result['reporting_period']['increment_rates'].append(
539
                    (reporting[energy_category_id]['subtotal'] - base[energy_category_id]['subtotal']) /
540
                    base[energy_category_id]['subtotal']
541
                    if base[energy_category_id]['subtotal'] > 0.0 else None)
542
                result['reporting_period']['total'] += reporting[energy_category_id]['subtotal']
543
544
                rate = list()
545
                for index, value in enumerate(reporting[energy_category_id]['values']):
546
                    if index < len(base[energy_category_id]['values']) \
547
                            and base[energy_category_id]['values'][index] != 0 and value != 0:
548
                        rate.append((value - base[energy_category_id]['values'][index])
549
                                    / base[energy_category_id]['values'][index])
550
                    else:
551
                        rate.append(None)
552
                result['reporting_period']['rates'].append(rate)
553
554
        result['reporting_period']['total_increment_rate'] = \
555
            (result['reporting_period']['total'] - result['base_period']['total']) / \
556
            result['base_period']['total'] \
557
            if result['base_period']['total'] > Decimal(0.0) else None
558
559
        result['parameters'] = {
560
            "names": parameters_data['names'],
561
            "timestamps": parameters_data['timestamps'],
562
            "values": parameters_data['values']
563
        }
564
565
        # export result to Excel file and then encode the file to base64 string
566
        result['excel_bytes_base64'] = None
567
        if not is_quick_mode:
568
            result['excel_bytes_base64'] = excelexporters.equipmentincome.export(result,
569
                                                                                 equipment['name'],
570
                                                                                 base_period_start_datetime_local,
571
                                                                                 base_period_end_datetime_local,
572
                                                                                 reporting_period_start_datetime_local,
573
                                                                                 reporting_period_end_datetime_local,
574
                                                                                 period_type,
575
                                                                                 language)
576
        resp.text = json.dumps(result)
577