EnergyStoragePowerStationUserItem.on_delete()   B
last analyzed

Complexity

Conditions 8

Size

Total Lines 52
Code Lines 42

Duplication

Lines 52
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 42
dl 52
loc 52
rs 7.0053
c 0
b 0
f 0
cc 8
nop 4

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import uuid
2
from datetime import datetime, timedelta
3
import falcon
4
import mysql.connector
5
import simplejson as json
6
from core.useractivity import user_logger, admin_control, access_control
7
import config
8
9
10
class EnergyStoragePowerStationCollection:
11
    def __init__(self):
12
        """"Initializes Class"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    @staticmethod
20
    def on_get(req, resp):
21
        access_control(req)
22
        cnx = mysql.connector.connect(**config.myems_system_db)
23
        cursor = cnx.cursor()
24
25
        # query contact dict
26
        contact_dict = dict()
27
        query = (" SELECT id, name, uuid "
28
                 " FROM tbl_contacts ")
29
        cursor.execute(query)
30
        rows_contacts = cursor.fetchall()
31
        if rows_contacts is not None and len(rows_contacts) > 0:
32
            for row in rows_contacts:
33
                contact_dict[row[0]] = {"id": row[0],
34
                                        "name": row[1],
35
                                        "uuid": row[2]}
36
        # query cost center dict
37
        cost_center_dict = dict()
38
        query = (" SELECT id, name, uuid "
39
                 " FROM tbl_cost_centers ")
40
        cursor.execute(query)
41
        rows_cost_centers = cursor.fetchall()
42
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
43
            for row in rows_cost_centers:
44
                cost_center_dict[row[0]] = {"id": row[0],
45
                                            "name": row[1],
46
                                            "uuid": row[2]}
47
48
        # query svg dict
49
        svg_dict = dict()
50
        query = (" SELECT id, name, uuid "
51
                 " FROM tbl_svgs ")
52
        cursor.execute(query)
53
        rows_svgs = cursor.fetchall()
54
        if rows_svgs is not None and len(rows_svgs) > 0:
55
            for row in rows_svgs:
56
                svg_dict[row[0]] = {"id": row[0],
57
                                    "name": row[1],
58
                                    "uuid": row[2]}
59
60
        # query point dict
61
        point_dict = dict()
62
        query = (" SELECT id, name "
63
                 " FROM tbl_points ")
64
        cursor.execute(query)
65
        rows_points = cursor.fetchall()
66
        if rows_points is not None and len(rows_points) > 0:
67
            for row in rows_points:
68
                point_dict[row[0]] = {"id": row[0],
69
                                      "name": row[1]}
70
71
        query = (" SELECT id, name, uuid, "
72
                 "        address, latitude, longitude, rated_capacity, rated_power, "
73
                 "        contact_id, cost_center_id, svg_id, is_cost_data_displayed, phase_of_lifecycle, description, "
74
                 "        latitude_point_id, longitude_point_id, svg2_id, svg3_id, svg4_id, svg5_id "
75
                 " FROM tbl_energy_storage_power_stations "
76
                 " ORDER BY id ")
77
        cursor.execute(query)
78
        rows_energy_storage_power_stations = cursor.fetchall()
79
80
        result = list()
81
        if rows_energy_storage_power_stations is not None and len(rows_energy_storage_power_stations) > 0:
82
            for row in rows_energy_storage_power_stations:
83
                meta_result = {"id": row[0],
84
                               "name": row[1],
85
                               "uuid": row[2],
86
                               "address": row[3],
87
                               "latitude": row[4],
88
                               "longitude": row[5],
89
                               "rated_capacity": row[6],
90
                               "rated_power": row[7],
91
                               "contact": contact_dict.get(row[8], None),
92
                               "cost_center": cost_center_dict.get(row[9], None),
93
                               "svg": svg_dict.get(row[10], None),
94
                               "is_cost_data_displayed": bool(row[11]),
95
                               "phase_of_lifecycle": row[12],
96
                               "description": row[13],
97
                               "latitude_point": point_dict.get(row[14], None),
98
                               "longitude_point": point_dict.get(row[15], None),
99
                               "svg2": svg_dict.get(row[16], None),
100
                               "svg3": svg_dict.get(row[17], None),
101
                               "svg4": svg_dict.get(row[18], None),
102
                               "svg5": svg_dict.get(row[19], None),
103
                               "qrcode": 'energystoragepowerstation:' + row[2]}
104
                result.append(meta_result)
105
106
        cursor.close()
107
        cnx.close()
108
        resp.text = json.dumps(result)
109
110
    @staticmethod
111
    @user_logger
112
    def on_post(req, resp):
113
        """Handles POST requests"""
114
        admin_control(req)
115
        try:
116
            raw_json = req.stream.read().decode('utf-8')
117
        except Exception as ex:
118
            raise falcon.HTTPError(status=falcon.HTTP_400,
119
                                   title='API.BAD_REQUEST',
120
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
121
122
        new_values = json.loads(raw_json)
123
124
        if 'name' not in new_values['data'].keys() or \
125
                not isinstance(new_values['data']['name'], str) or \
126
                len(str.strip(new_values['data']['name'])) == 0:
127
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
128
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_NAME')
129
        name = str.strip(new_values['data']['name'])
130
131
        if 'address' not in new_values['data'].keys() or \
132
                not isinstance(new_values['data']['address'], str) or \
133
                len(str.strip(new_values['data']['address'])) == 0:
134
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
135
                                   description='API.INVALID_ADDRESS_VALUE')
136
        address = str.strip(new_values['data']['address'])
137
138
        if 'latitude' not in new_values['data'].keys() or \
139
                not (isinstance(new_values['data']['latitude'], float) or
140
                     isinstance(new_values['data']['latitude'], int)) or \
141
                new_values['data']['latitude'] < -90.0 or \
142
                new_values['data']['latitude'] > 90.0:
143
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
144
                                   description='API.INVALID_LATITUDE_VALUE')
145
        latitude = new_values['data']['latitude']
146
147
        if 'longitude' not in new_values['data'].keys() or \
148
                not (isinstance(new_values['data']['longitude'], float) or
149
                     isinstance(new_values['data']['longitude'], int)) or \
150
                new_values['data']['longitude'] < -180.0 or \
151
                new_values['data']['longitude'] > 180.0:
152
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
153
                                   description='API.INVALID_LONGITUDE_VALUE')
154
        longitude = new_values['data']['longitude']
155
156
        if 'rated_capacity' not in new_values['data'].keys() or \
157
                not (isinstance(new_values['data']['rated_capacity'], float) or
158
                     isinstance(new_values['data']['rated_capacity'], int)) or \
159
                new_values['data']['rated_capacity'] < 0.0:
160
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
161
                                   description='API.INVALID_RATED_CAPACITY')
162
        rated_capacity = new_values['data']['rated_capacity']
163
164
        if 'rated_power' not in new_values['data'].keys() or \
165
                not (isinstance(new_values['data']['rated_power'], float) or
166
                     isinstance(new_values['data']['rated_power'], int)) or \
167
                new_values['data']['rated_power'] < 0.0:
168
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
169
                                   description='API.INVALID_RATED_POWER')
170
        rated_power = new_values['data']['rated_power']
171
172
        if 'contact_id' not in new_values['data'].keys() or \
173
                not isinstance(new_values['data']['contact_id'], int) or \
174
                new_values['data']['contact_id'] <= 0:
175
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
176
                                   description='API.INVALID_CONTACT_ID')
177
        contact_id = new_values['data']['contact_id']
178
179
        if 'cost_center_id' not in new_values['data'].keys() or \
180
                not isinstance(new_values['data']['cost_center_id'], int) or \
181
                new_values['data']['cost_center_id'] <= 0:
182
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
183
                                   description='API.INVALID_COST_CENTER_ID')
184
        cost_center_id = new_values['data']['cost_center_id']
185
186
        if 'svg_id' not in new_values['data'].keys() or \
187
                not isinstance(new_values['data']['svg_id'], int) or \
188
                new_values['data']['svg_id'] <= 0:
189
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
190
                                   description='API.INVALID_SVG_ID')
191
        svg_id = new_values['data']['svg_id']
192
193
        if 'is_cost_data_displayed' not in new_values['data'].keys() or \
194
                not isinstance(new_values['data']['is_cost_data_displayed'], bool):
195
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
196
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED')
197
        is_cost_data_displayed = new_values['data']['is_cost_data_displayed']
198
199
        if 'phase_of_lifecycle' not in new_values['data'].keys() or \
200
                not isinstance(new_values['data']['phase_of_lifecycle'], str) or \
201
                len(str.strip(new_values['data']['phase_of_lifecycle'])) == 0:
202
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
203
                                   description='API.INVALID_PHASE_OF_LIFECYCLE')
204
        phase_of_lifecycle = str.strip(new_values['data']['phase_of_lifecycle'])
205
206
        if 'description' in new_values['data'].keys() and \
207
                new_values['data']['description'] is not None and \
208
                len(str(new_values['data']['description'])) > 0:
209
            description = str.strip(new_values['data']['description'])
210
        else:
211
            description = None
212
213
        if 'latitude_point_id' in new_values['data'].keys() and \
214
                isinstance(new_values['data']['latitude_point_id'], int) and \
215
                new_values['data']['latitude_point_id'] > 0:
216
            latitude_point_id = new_values['data']['latitude_point_id']
217
        else:
218
            latitude_point_id = None
219
220
        if 'longitude_point_id' in new_values['data'].keys() and \
221
                isinstance(new_values['data']['longitude_point_id'], int) and \
222
                new_values['data']['longitude_point_id'] > 0:
223
            longitude_point_id = new_values['data']['longitude_point_id']
224
        else:
225
            longitude_point_id = None
226
227
        if 'svg2_id' in new_values['data'].keys() and \
228
                isinstance(new_values['data']['svg2_id'], int) and \
229
                new_values['data']['svg2_id'] > 0:
230
            svg2_id = new_values['data']['svg2_id']
231
        else:
232
            svg2_id = None
233
234
        if 'svg3_id' in new_values['data'].keys() and \
235
                isinstance(new_values['data']['svg3_id'], int) and \
236
                new_values['data']['svg3_id'] > 0:
237
            svg3_id = new_values['data']['svg3_id']
238
        else:
239
            svg3_id = None
240
241
        if 'svg4_id' in new_values['data'].keys() and \
242
                isinstance(new_values['data']['svg4_id'], int) and \
243
                new_values['data']['svg4_id'] > 0:
244
            svg4_id = new_values['data']['svg4_id']
245
        else:
246
            svg4_id = None
247
248
        if 'svg5_id' in new_values['data'].keys() and \
249
                isinstance(new_values['data']['svg5_id'], int) and \
250
                new_values['data']['svg5_id'] > 0:
251
            svg5_id = new_values['data']['svg5_id']
252
        else:
253
            svg5_id = None
254
255
        cnx = mysql.connector.connect(**config.myems_system_db)
256
        cursor = cnx.cursor()
257
258
        cursor.execute(" SELECT name "
259
                       " FROM tbl_energy_storage_power_stations "
260
                       " WHERE name = %s ", (name,))
261
        if cursor.fetchone() is not None:
262
            cursor.close()
263
            cnx.close()
264
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
265
                                   description='API.ENERGY_STORAGE_POWER_STATION_NAME_IS_ALREADY_IN_USE')
266
267
        cursor.execute(" SELECT name "
268
                       " FROM tbl_contacts "
269
                       " WHERE id = %s ",
270
                       (contact_id,))
271
        row = cursor.fetchone()
272
        if row is None:
273
            cursor.close()
274
            cnx.close()
275
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
276
                                   description='API.CONTACT_NOT_FOUND')
277
278
        cursor.execute(" SELECT name "
279
                       " FROM tbl_cost_centers "
280
                       " WHERE id = %s ",
281
                       (cost_center_id,))
282
        row = cursor.fetchone()
283
        if row is None:
284
            cursor.close()
285
            cnx.close()
286
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
287
                                   description='API.COST_CENTER_NOT_FOUND')
288
289
        cursor.execute(" SELECT name "
290
                       " FROM tbl_svgs "
291
                       " WHERE id = %s ",
292
                       (svg_id,))
293
        row = cursor.fetchone()
294
        if row is None:
295
            cursor.close()
296
            cnx.close()
297
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
298
                                   description='API.SVG_NOT_FOUND')
299
300
        add_values = (" INSERT INTO tbl_energy_storage_power_stations "
301
                      " (name, uuid, address, latitude, longitude, rated_capacity, rated_power, "
302
                      "  contact_id, cost_center_id, svg_id, is_cost_data_displayed, phase_of_lifecycle, description, "
303
                      "  latitude_point_id, longitude_point_id, svg2_id, svg3_id, svg4_id, svg5_id ) "
304
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
305
        cursor.execute(add_values, (name,
306
                                    str(uuid.uuid4()),
307
                                    address,
308
                                    latitude,
309
                                    longitude,
310
                                    rated_capacity,
311
                                    rated_power,
312
                                    contact_id,
313
                                    cost_center_id,
314
                                    svg_id,
315
                                    is_cost_data_displayed,
316
                                    phase_of_lifecycle,
317
                                    description,
318
                                    latitude_point_id,
319
                                    longitude_point_id,
320
                                    svg2_id,
321
                                    svg3_id,
322
                                    svg4_id,
323
                                    svg5_id))
324
        new_id = cursor.lastrowid
325
        cnx.commit()
326
        cursor.close()
327
        cnx.close()
328
329
        resp.status = falcon.HTTP_201
330
        resp.location = '/energystoragepowerstations/' + str(new_id)
331
332
333
class EnergyStoragePowerStationItem:
334
    def __init__(self):
335
        """"Initializes Class"""
336
        pass
337
338
    @staticmethod
339
    def on_options(req, resp, id_):
340
        resp.status = falcon.HTTP_200
341
342
    @staticmethod
343
    def on_get(req, resp, id_):
344
        access_control(req)
345
        if not id_.isdigit() or int(id_) <= 0:
346
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
347
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
348
349
        cnx = mysql.connector.connect(**config.myems_system_db)
350
        cursor = cnx.cursor()
351
352
        contact_dict = dict()
353
        query = (" SELECT id, name, uuid "
354
                 " FROM tbl_contacts ")
355
        cursor.execute(query)
356
        rows_contacts = cursor.fetchall()
357
        if rows_contacts is not None and len(rows_contacts) > 0:
358
            for row in rows_contacts:
359
                contact_dict[row[0]] = {"id": row[0],
360
                                        "name": row[1],
361
                                        "uuid": row[2]}
362
363
        cost_center_dict = dict()
364
        query = (" SELECT id, name, uuid "
365
                 " FROM tbl_cost_centers ")
366
        cursor.execute(query)
367
        rows_cost_centers = cursor.fetchall()
368
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
369
            for row in rows_cost_centers:
370
                cost_center_dict[row[0]] = {"id": row[0],
371
                                            "name": row[1],
372
                                            "uuid": row[2]}
373
374
        svg_dict = dict()
375
        query = (" SELECT id, name, uuid "
376
                 " FROM tbl_svgs ")
377
        cursor.execute(query)
378
        rows_svgs = cursor.fetchall()
379
        if rows_svgs is not None and len(rows_svgs) > 0:
380
            for row in rows_svgs:
381
                svg_dict[row[0]] = {"id": row[0],
382
                                    "name": row[1],
383
                                    "uuid": row[2]}
384
385
        # query point dict
386
        point_dict = dict()
387
        query = (" SELECT id, name "
388
                 " FROM tbl_points ")
389
        cursor.execute(query)
390
        rows_points = cursor.fetchall()
391
        if rows_points is not None and len(rows_points) > 0:
392
            for row in rows_points:
393
                point_dict[row[0]] = {"id": row[0],
394
                                      "name": row[1]}
395
396
        query = (" SELECT id, name, uuid, "
397
                 "        address, latitude, longitude, rated_capacity, rated_power, "
398
                 "        contact_id, cost_center_id, svg_id, is_cost_data_displayed, phase_of_lifecycle, description, "
399
                 "        latitude_point_id, longitude_point_id, svg2_id, svg3_id, svg4_id, svg5_id "
400
                 " FROM tbl_energy_storage_power_stations "
401
                 " WHERE id = %s ")
402
        cursor.execute(query, (id_,))
403
        row = cursor.fetchone()
404
        cursor.close()
405
        cnx.close()
406
407
        if row is None:
408
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
409
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
410
        else:
411
            meta_result = {"id": row[0],
412
                           "name": row[1],
413
                           "uuid": row[2],
414
                           "address": row[3],
415
                           "latitude": row[4],
416
                           "longitude": row[5],
417
                           "rated_capacity": row[6],
418
                           "rated_power": row[7],
419
                           "contact": contact_dict.get(row[8], None),
420
                           "cost_center": cost_center_dict.get(row[9], None),
421
                           "svg": svg_dict.get(row[10], None),
422
                           "is_cost_data_displayed": bool(row[11]),
423
                           "phase_of_lifecycle": row[12],
424
                           "description": row[13],
425
                           "latitude_point": point_dict.get(row[14], None),
426
                           "longitude_point": point_dict.get(row[15], None),
427
                           "svg2": svg_dict.get(row[16], None),
428
                           "svg3": svg_dict.get(row[17], None),
429
                           "svg4": svg_dict.get(row[18], None),
430
                           "svg5": svg_dict.get(row[19], None),
431
                           "qrcode": 'energystoragepowerstation:' + row[2]}
432
433
        resp.text = json.dumps(meta_result)
434
435 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
436
    @user_logger
437
    def on_delete(req, resp, id_):
438
        admin_control(req)
439
        if not id_.isdigit() or int(id_) <= 0:
440
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
441
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
442
443
        cnx = mysql.connector.connect(**config.myems_system_db)
444
        cursor = cnx.cursor()
445
446
        cursor.execute(" SELECT name "
447
                       " FROM tbl_energy_storage_power_stations "
448
                       " WHERE id = %s ", (id_,))
449
        if cursor.fetchone() is None:
450
            cursor.close()
451
            cnx.close()
452
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
453
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
454
        cursor.execute(" DELETE FROM tbl_energy_storage_power_stations_containers "
455
                       " WHERE energy_storage_power_station_id = %s ", (id_,))
456
457
        cursor.execute(" DELETE FROM tbl_energy_storage_power_stations "
458
                       " WHERE id = %s ", (id_,))
459
        cnx.commit()
460
461
        cursor.close()
462
        cnx.close()
463
464
        resp.status = falcon.HTTP_204
465
466
    @staticmethod
467
    @user_logger
468
    def on_put(req, resp, id_):
469
        """Handles PUT requests"""
470
        admin_control(req)
471
        try:
472
            raw_json = req.stream.read().decode('utf-8')
473
        except Exception as ex:
474
            raise falcon.HTTPError(status=falcon.HTTP_400,
475
                                   title='API.BAD_REQUEST',
476
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
477
478
        if not id_.isdigit() or int(id_) <= 0:
479
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
480
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
481
482
        new_values = json.loads(raw_json)
483
484
        if 'name' not in new_values['data'].keys() or \
485
                not isinstance(new_values['data']['name'], str) or \
486
                len(str.strip(new_values['data']['name'])) == 0:
487
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
488
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_NAME')
489
        name = str.strip(new_values['data']['name'])
490
491
        if 'address' not in new_values['data'].keys() or \
492
                not isinstance(new_values['data']['address'], str) or \
493
                len(str.strip(new_values['data']['address'])) == 0:
494
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
495
                                   description='API.INVALID_ADDRESS_VALUE')
496
        address = str.strip(new_values['data']['address'])
497
498
        if 'latitude' not in new_values['data'].keys() or \
499
                not (isinstance(new_values['data']['latitude'], float) or
500
                     isinstance(new_values['data']['latitude'], int)) or \
501
                new_values['data']['latitude'] < -90.0 or \
502
                new_values['data']['latitude'] > 90.0:
503
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
504
                                   description='API.INVALID_LATITUDE_VALUE')
505
        latitude = new_values['data']['latitude']
506
507
        if 'longitude' not in new_values['data'].keys() or \
508
                not (isinstance(new_values['data']['longitude'], float) or
509
                     isinstance(new_values['data']['longitude'], int)) or \
510
                new_values['data']['longitude'] < -180.0 or \
511
                new_values['data']['longitude'] > 180.0:
512
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
513
                                   description='API.INVALID_LONGITUDE_VALUE')
514
        longitude = new_values['data']['longitude']
515
516
        if 'rated_capacity' not in new_values['data'].keys() or \
517
                not (isinstance(new_values['data']['rated_capacity'], float) or
518
                     isinstance(new_values['data']['rated_capacity'], int)) or \
519
                new_values['data']['rated_capacity'] < 0.0:
520
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
521
                                   description='API.INVALID_RATED_CAPACITY')
522
        rated_capacity = new_values['data']['rated_capacity']
523
524
        if 'rated_power' not in new_values['data'].keys() or \
525
                not (isinstance(new_values['data']['rated_power'], float) or
526
                     isinstance(new_values['data']['rated_power'], int)) or \
527
                new_values['data']['rated_power'] < 0.0:
528
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
529
                                   description='API.INVALID_RATED_POWER')
530
        rated_power = new_values['data']['rated_power']
531
532
        if 'contact_id' not in new_values['data'].keys() or \
533
                not isinstance(new_values['data']['contact_id'], int) or \
534
                new_values['data']['contact_id'] <= 0:
535
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
536
                                   description='API.INVALID_CONTACT_ID')
537
        contact_id = new_values['data']['contact_id']
538
539
        if 'cost_center_id' not in new_values['data'].keys() or \
540
                not isinstance(new_values['data']['cost_center_id'], int) or \
541
                new_values['data']['cost_center_id'] <= 0:
542
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
543
                                   description='API.INVALID_COST_CENTER_ID')
544
        cost_center_id = new_values['data']['cost_center_id']
545
546
        if 'svg_id' not in new_values['data'].keys() or \
547
                not isinstance(new_values['data']['svg_id'], int) or \
548
                new_values['data']['svg_id'] <= 0:
549
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
550
                                   description='API.INVALID_SVG_ID')
551
        svg_id = new_values['data']['svg_id']
552
553
        if 'is_cost_data_displayed' not in new_values['data'].keys() or \
554
                not isinstance(new_values['data']['is_cost_data_displayed'], bool):
555
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
556
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED_VALUE')
557
        is_cost_data_displayed = new_values['data']['is_cost_data_displayed']
558
559
        if 'phase_of_lifecycle' not in new_values['data'].keys() or \
560
                not isinstance(new_values['data']['phase_of_lifecycle'], str) or \
561
                len(str.strip(new_values['data']['phase_of_lifecycle'])) == 0:
562
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
563
                                   description='API.INVALID_PHASE_OF_LIFECYCLE')
564
        phase_of_lifecycle = str.strip(new_values['data']['phase_of_lifecycle'])
565
566
        if 'description' in new_values['data'].keys() and \
567
                new_values['data']['description'] is not None and \
568
                len(str(new_values['data']['description'])) > 0:
569
            description = str.strip(new_values['data']['description'])
570
        else:
571
            description = None
572
573
        if 'latitude_point_id' in new_values['data'].keys() and \
574
                isinstance(new_values['data']['latitude_point_id'], int) and \
575
                new_values['data']['latitude_point_id'] > 0:
576
            latitude_point_id = new_values['data']['latitude_point_id']
577
        else:
578
            latitude_point_id = None
579
580
        if 'longitude_point_id' in new_values['data'].keys() and \
581
                isinstance(new_values['data']['longitude_point_id'], int) and \
582
                new_values['data']['longitude_point_id'] > 0:
583
            longitude_point_id = new_values['data']['longitude_point_id']
584
        else:
585
            longitude_point_id = None
586
587
        if 'svg2_id' in new_values['data'].keys() and \
588
                isinstance(new_values['data']['svg2_id'], int) and \
589
                new_values['data']['svg2_id'] > 0:
590
            svg2_id = new_values['data']['svg2_id']
591
        else:
592
            svg2_id = None
593
594
        if 'svg3_id' in new_values['data'].keys() and \
595
                isinstance(new_values['data']['svg3_id'], int) and \
596
                new_values['data']['svg3_id'] > 0:
597
            svg3_id = new_values['data']['svg3_id']
598
        else:
599
            svg3_id = None
600
601
        if 'svg4_id' in new_values['data'].keys() and \
602
                isinstance(new_values['data']['svg4_id'], int) and \
603
                new_values['data']['svg4_id'] > 0:
604
            svg4_id = new_values['data']['svg4_id']
605
        else:
606
            svg4_id = None
607
608
        if 'svg5_id' in new_values['data'].keys() and \
609
                isinstance(new_values['data']['svg5_id'], int) and \
610
                new_values['data']['svg5_id'] > 0:
611
            svg5_id = new_values['data']['svg5_id']
612
        else:
613
            svg5_id = None
614
615
        cnx = mysql.connector.connect(**config.myems_system_db)
616
        cursor = cnx.cursor()
617
618
        cursor.execute(" SELECT name "
619
                       " FROM tbl_energy_storage_power_stations "
620
                       " WHERE id = %s ", (id_,))
621
        if cursor.fetchone() is None:
622
            cursor.close()
623
            cnx.close()
624
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
625
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
626
627
        cursor.execute(" SELECT name "
628
                       " FROM tbl_energy_storage_power_stations "
629
                       " WHERE name = %s AND id != %s ", (name, id_))
630
        if cursor.fetchone() is not None:
631
            cursor.close()
632
            cnx.close()
633
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
634
                                   description='API.ENERGY_STORAGE_POWER_STATION_NAME_IS_ALREADY_IN_USE')
635
636
        cursor.execute(" SELECT name "
637
                       " FROM tbl_contacts "
638
                       " WHERE id = %s ",
639
                       (new_values['data']['contact_id'],))
640
        row = cursor.fetchone()
641
        if row is None:
642
            cursor.close()
643
            cnx.close()
644
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
645
                                   description='API.CONTACT_NOT_FOUND')
646
647
        cursor.execute(" SELECT name "
648
                       " FROM tbl_cost_centers "
649
                       " WHERE id = %s ",
650
                       (new_values['data']['cost_center_id'],))
651
        row = cursor.fetchone()
652
        if row is None:
653
            cursor.close()
654
            cnx.close()
655
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
656
                                   description='API.COST_CENTER_NOT_FOUND')
657
658
        cursor.execute(" SELECT name "
659
                       " FROM tbl_svgs "
660
                       " WHERE id = %s ",
661
                       (new_values['data']['svg_id'],))
662
        row = cursor.fetchone()
663
        if row is None:
664
            cursor.close()
665
            cnx.close()
666
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
667
                                   description='API.SVG_NOT_FOUND')
668
669
        update_row = (" UPDATE tbl_energy_storage_power_stations "
670
                      " SET name = %s, address = %s, latitude = %s, longitude = %s, "
671
                      "     rated_capacity = %s, rated_power = %s, "
672
                      "     contact_id = %s, cost_center_id = %s, "
673
                      "     svg_id = %s, is_cost_data_displayed = %s, phase_of_lifecycle = %s, description = %s, "
674
                      "     latitude_point_id = %s, longitude_point_id = %s, "
675
                      "     svg2_id = %s, svg3_id = %s, svg4_id = %s, svg5_id = %s "
676
                      " WHERE id = %s ")
677
        cursor.execute(update_row, (name,
678
                                    address,
679
                                    latitude,
680
                                    longitude,
681
                                    rated_capacity,
682
                                    rated_power,
683
                                    contact_id,
684
                                    cost_center_id,
685
                                    svg_id,
686
                                    is_cost_data_displayed,
687
                                    phase_of_lifecycle,
688
                                    description,
689
                                    latitude_point_id,
690
                                    longitude_point_id,
691
                                    svg2_id,
692
                                    svg3_id,
693
                                    svg4_id,
694
                                    svg5_id,
695
                                    id_))
696
        cnx.commit()
697
698
        cursor.close()
699
        cnx.close()
700
701
        resp.status = falcon.HTTP_200
702
703
704 View Code Duplication
class EnergyStoragePowerStationContainerCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
705
    def __init__(self):
706
        """Initializes Class"""
707
        pass
708
709
    @staticmethod
710
    def on_options(req, resp, id_):
711
        resp.status = falcon.HTTP_200
712
713
    @staticmethod
714
    def on_get(req, resp, id_):
715
        access_control(req)
716
        if not id_.isdigit() or int(id_) <= 0:
717
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
718
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
719
720
        cnx = mysql.connector.connect(**config.myems_system_db)
721
        cursor = cnx.cursor()
722
723
        cursor.execute(" SELECT name "
724
                       " FROM tbl_energy_storage_power_stations "
725
                       " WHERE id = %s ", (id_,))
726
        if cursor.fetchone() is None:
727
            cursor.close()
728
            cnx.close()
729
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
730
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
731
732
        query = (" SELECT s.id, s.name, s.uuid "
733
                 " FROM tbl_energy_storage_power_stations e, "
734
                 "      tbl_energy_storage_power_stations_containers es, tbl_energy_storage_containers s "
735
                 " WHERE es.energy_storage_power_station_id = e.id "
736
                 "       AND s.id = es.energy_storage_container_id "
737
                 "       AND e.id = %s "
738
                 " ORDER BY s.id ")
739
        cursor.execute(query, (id_,))
740
        rows = cursor.fetchall()
741
742
        result = list()
743
        if rows is not None and len(rows) > 0:
744
            for row in rows:
745
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
746
                result.append(meta_result)
747
748
        resp.text = json.dumps(result)
749
750
    @staticmethod
751
    @user_logger
752
    def on_post(req, resp, id_):
753
        """Handles POST requests"""
754
        admin_control(req)
755
        try:
756
            raw_json = req.stream.read().decode('utf-8')
757
        except Exception as ex:
758
            raise falcon.HTTPError(status=falcon.HTTP_400,
759
                                   title='API.BAD_REQUEST',
760
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
761
762
        if not id_.isdigit() or int(id_) <= 0:
763
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
764
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
765
766
        new_values = json.loads(raw_json)
767
768
        if 'energy_storage_container_id' not in new_values['data'].keys() or \
769
                not isinstance(new_values['data']['energy_storage_container_id'], int) or \
770
                new_values['data']['energy_storage_container_id'] <= 0:
771
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
772
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
773
        energy_storage_container_id = new_values['data']['energy_storage_container_id']
774
775
        cnx = mysql.connector.connect(**config.myems_system_db)
776
        cursor = cnx.cursor()
777
778
        cursor.execute(" SELECT name "
779
                       " FROM tbl_energy_storage_power_stations "
780
                       " WHERE id = %s ", (id_,))
781
        if cursor.fetchone() is None:
782
            cursor.close()
783
            cnx.close()
784
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
785
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
786
787
        cursor.execute(" SELECT name "
788
                       " FROM tbl_energy_storage_containers "
789
                       " WHERE id = %s ", (energy_storage_container_id,))
790
        if cursor.fetchone() is None:
791
            cursor.close()
792
            cnx.close()
793
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
794
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
795
796
        query = (" SELECT id " 
797
                 " FROM tbl_energy_storage_power_stations_containers "
798
                 " WHERE energy_storage_power_station_id = %s AND energy_storage_container_id = %s")
799
        cursor.execute(query, (id_, energy_storage_container_id,))
800
        if cursor.fetchone() is not None:
801
            cursor.close()
802
            cnx.close()
803
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
804
                                   description='API.ENERGY_STORAGE_CONTAINER_SENSOR_RELATION_EXISTS')
805
806
        add_row = (" INSERT INTO tbl_energy_storage_power_stations_containers "
807
                   "        (energy_storage_power_station_id, energy_storage_container_id) "
808
                   " VALUES (%s, %s) ")
809
        cursor.execute(add_row, (id_, energy_storage_container_id,))
810
        cnx.commit()
811
        cursor.close()
812
        cnx.close()
813
814
        resp.status = falcon.HTTP_201
815
        resp.location = '/energystoragepowerstationss/' + str(id_) + '/containers/' + str(energy_storage_container_id)
816
817
818 View Code Duplication
class EnergyStoragePowerStationContainerItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
819
    def __init__(self):
820
        """Initializes Class"""
821
        pass
822
823
    @staticmethod
824
    def on_options(req, resp, id_, sid):
825
        resp.status = falcon.HTTP_200
826
827
    @staticmethod
828
    @user_logger
829
    def on_delete(req, resp, id_, sid):
830
        admin_control(req)
831
        if not id_.isdigit() or int(id_) <= 0:
832
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
833
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
834
835
        if not sid.isdigit() or int(sid) <= 0:
836
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
837
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
838
839
        cnx = mysql.connector.connect(**config.myems_system_db)
840
        cursor = cnx.cursor()
841
842
        cursor.execute(" SELECT name "
843
                       " FROM tbl_energy_storage_power_stations "
844
                       " WHERE id = %s ", (id_,))
845
        if cursor.fetchone() is None:
846
            cursor.close()
847
            cnx.close()
848
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
849
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
850
851
        cursor.execute(" SELECT name "
852
                       " FROM tbl_energy_storage_containers "
853
                       " WHERE id = %s ", (sid,))
854
        if cursor.fetchone() is None:
855
            cursor.close()
856
            cnx.close()
857
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
858
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
859
860
        cursor.execute(" SELECT id "
861
                       " FROM tbl_energy_storage_power_stations_containers "
862
                       " WHERE energy_storage_power_station_id = %s AND energy_storage_container_id = %s ", (id_, sid))
863
        if cursor.fetchone() is None:
864
            cursor.close()
865
            cnx.close()
866
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
867
                                   description='API.ENERGY_STORAGE_POWER_STATION_CONTAINER_RELATION_NOT_FOUND')
868
869
        cursor.execute(" DELETE FROM tbl_energy_storage_power_stations_containers "
870
                       " WHERE energy_storage_power_station_id = %s AND energy_storage_container_id = %s ", (id_, sid))
871
        cnx.commit()
872
873
        cursor.close()
874
        cnx.close()
875
876
        resp.status = falcon.HTTP_204
877
878
879 View Code Duplication
class EnergyStoragePowerStationUserCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
880
    def __init__(self):
881
        """Initializes Class"""
882
        pass
883
884
    @staticmethod
885
    def on_options(req, resp, id_):
886
        resp.status = falcon.HTTP_200
887
888
    @staticmethod
889
    def on_get(req, resp, id_):
890
        access_control(req)
891
        if not id_.isdigit() or int(id_) <= 0:
892
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
893
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
894
895
        cnx = mysql.connector.connect(**config.myems_system_db)
896
        cursor = cnx.cursor()
897
        cursor.execute(" SELECT name "
898
                       " FROM tbl_energy_storage_power_stations "
899
                       " WHERE id = %s ", (id_,))
900
        if cursor.fetchone() is None:
901
            cursor.close()
902
            cnx.close()
903
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
904
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
905
906
        query = (" SELECT u.id, u.name, u.uuid "
907
                 " FROM tbl_energy_storage_power_stations m, tbl_energy_storage_power_stations_users mu, "
908
                 + config.myems_user_db['database'] + ".tbl_users u "
909
                 " WHERE mu.energy_storage_power_station_id = m.id AND u.id = mu.user_id AND m.id = %s "
910
                 " ORDER BY u.id ")
911
        cursor.execute(query, (id_,))
912
        rows = cursor.fetchall()
913
        result = list()
914
        if rows is not None and len(rows) > 0:
915
            for row in rows:
916
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
917
                result.append(meta_result)
918
919
        cursor.close()
920
        cnx.close()
921
        resp.text = json.dumps(result)
922
923
    @staticmethod
924
    @user_logger
925
    def on_post(req, resp, id_):
926
        """Handles POST requests"""
927
        admin_control(req)
928
        try:
929
            raw_json = req.stream.read().decode('utf-8')
930
        except Exception as ex:
931
            raise falcon.HTTPError(status=falcon.HTTP_400,
932
                                   title='API.BAD_REQUEST',
933
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
934
935
        if not id_.isdigit() or int(id_) <= 0:
936
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
937
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
938
939
        new_values = json.loads(raw_json)
940
        if 'user_id' not in new_values['data'].keys() or \
941
                not isinstance(new_values['data']['user_id'], int) or \
942
                new_values['data']['user_id'] <= 0:
943
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
944
                                   description='API.INVALID_USER_ID')
945
        user_id = new_values['data']['user_id']
946
        cnx = mysql.connector.connect(**config.myems_system_db)
947
        cursor = cnx.cursor()
948
        cursor.execute(" SELECT name "
949
                       " FROM tbl_energy_storage_power_stations "
950
                       " WHERE id = %s ", (id_,))
951
        if cursor.fetchone() is None:
952
            cursor.close()
953
            cnx.close()
954
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
955
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
956
957
        cnx_user = mysql.connector.connect(**config.myems_user_db)
958
        cursor_user = cnx_user.cursor()
959
        cursor_user.execute(" SELECT name"
960
                            " FROM tbl_users "
961
                            " WHERE id = %s ", (user_id,))
962
        if cursor_user.fetchone() is None:
963
            cursor_user.close()
964
            cnx_user.close()
965
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
966
                                   description='API.USER_NOT_FOUND')
967
        query = (" SELECT id "
968
                 " FROM tbl_energy_storage_power_stations_users "
969
                 " WHERE energy_storage_power_station_id = %s AND user_id = %s")
970
        cursor.execute(query, (id_, user_id,))
971
        if cursor.fetchone() is not None:
972
            cursor.close()
973
            cnx.close()
974
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
975
                                   description='API.ENERGY_STORAGE_POWER_STATION_USER_RELATION_EXISTS')
976
        add_row = (" INSERT INTO tbl_energy_storage_power_stations_users (energy_storage_power_station_id, user_id) "
977
                   " VALUES (%s, %s) ")
978
        cursor.execute(add_row, (id_, user_id,))
979
        cnx.commit()
980
        cursor.close()
981
        cnx.close()
982
        cursor_user.close()
983
        cnx_user.close()
984
985
        resp.status = falcon.HTTP_201
986
        resp.location = '/energystoragepowerstations/' + str(id_) + '/users/' + str(user_id)
987
988
989 View Code Duplication
class EnergyStoragePowerStationUserItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
990
    def __init__(self):
991
        """Initializes Class"""
992
        pass
993
994
    @staticmethod
995
    def on_options(req, resp, id_, uid):
996
        resp.status = falcon.HTTP_200
997
998
    @staticmethod
999
    @user_logger
1000
    def on_delete(req, resp, id_, uid):
1001
        # todo Verify if the user is bound when deleting it
1002
        admin_control(req)
1003
        if not id_.isdigit() or int(id_) <= 0:
1004
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1005
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
1006
1007
        if not uid.isdigit() or int(uid) <= 0:
1008
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1009
                                   description='API.INVALID_USER_ID')
1010
1011
        cnx = mysql.connector.connect(**config.myems_system_db)
1012
        cursor = cnx.cursor()
1013
        cursor.execute(" SELECT name "
1014
                       " FROM tbl_energy_storage_power_stations "
1015
                       " WHERE id = %s ", (id_,))
1016
        if cursor.fetchone() is None:
1017
            cursor.close()
1018
            cnx.close()
1019
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1020
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
1021
1022
        cnx_user = mysql.connector.connect(**config.myems_user_db)
1023
        cursor_user = cnx_user.cursor()
1024
        cursor_user.execute(" SELECT name FROM tbl_users WHERE id = %s ", (uid,))
1025
        if cursor_user.fetchone() is None:
1026
            cursor_user.close()
1027
            cnx_user.close()
1028
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1029
                                   description='API.USER_NOT_FOUND')
1030
1031
        cursor.execute(" SELECT id "
1032
                       " FROM tbl_energy_storage_power_stations_users "
1033
                       " WHERE energy_storage_power_station_id = %s AND user_id = %s ", (id_, uid))
1034
        if cursor.fetchone() is None:
1035
            cursor.close()
1036
            cnx.close()
1037
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1038
                                   description='API.ENERGY_STORAGE_POWER_STATION_USER_RELATION_NOT_FOUND')
1039
1040
        cursor.execute(" DELETE FROM tbl_energy_storage_power_stations_users "
1041
                       " WHERE energy_storage_power_station_id = %s AND user_id = %s ", (id_, uid))
1042
        cnx.commit()
1043
1044
        cursor.close()
1045
        cnx.close()
1046
        cursor_user.close()
1047
        cnx_user.close()
1048
1049
        resp.status = falcon.HTTP_204
1050
1051
1052 View Code Duplication
class EnergyStoragePowerStationExport:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1053
    def __init__(self):
1054
        """"Initializes Class"""
1055
        pass
1056
1057
    @staticmethod
1058
    def on_options(req, resp, id_):
1059
        resp.status = falcon.HTTP_200
1060
1061
    @staticmethod
1062
    def on_get(req, resp, id_):
1063
        access_control(req)
1064
        if not id_.isdigit() or int(id_) <= 0:
1065
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1066
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
1067
1068
        cnx = mysql.connector.connect(**config.myems_system_db)
1069
        cursor = cnx.cursor()
1070
1071
        query = (" SELECT id, name, uuid "
1072
                 " FROM tbl_contacts ")
1073
        cursor.execute(query)
1074
        rows_contacts = cursor.fetchall()
1075
1076
        contact_dict = dict()
1077
        if rows_contacts is not None and len(rows_contacts) > 0:
1078
            for row in rows_contacts:
1079
                contact_dict[row[0]] = {"id": row[0],
1080
                                        "name": row[1],
1081
                                        "uuid": row[2]}
1082
1083
        query = (" SELECT id, name, uuid "
1084
                 " FROM tbl_cost_centers ")
1085
        cursor.execute(query)
1086
        rows_cost_centers = cursor.fetchall()
1087
1088
        cost_center_dict = dict()
1089
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
1090
            for row in rows_cost_centers:
1091
                cost_center_dict[row[0]] = {"id": row[0],
1092
                                            "name": row[1],
1093
                                            "uuid": row[2]}
1094
1095
        query = (" SELECT id, name, uuid "
1096
                 " FROM tbl_svgs ")
1097
        cursor.execute(query)
1098
        rows_svgs = cursor.fetchall()
1099
1100
        svg_dict = dict()
1101
        if rows_svgs is not None and len(rows_svgs) > 0:
1102
            for row in rows_svgs:
1103
                svg_dict[row[0]] = {"id": row[0],
1104
                                    "name": row[1],
1105
                                    "uuid": row[2]}
1106
1107
        query = (" SELECT id, name, uuid, "
1108
                 "        address, latitude, longitude, rated_capacity, rated_power, "
1109
                 "        contact_id, cost_center_id, svg_id, is_cost_data_displayed, description "
1110
                 " FROM tbl_energy_storage_power_stations "
1111
                 " WHERE id = %s ")
1112
        cursor.execute(query, (id_,))
1113
        row = cursor.fetchone()
1114
        cursor.close()
1115
        cnx.close()
1116
1117
        if row is None:
1118
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1119
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
1120
        else:
1121
            meta_result = {"name": row[1],
1122
                           "uuid": row[2],
1123
                           "address": row[3],
1124
                           "latitude": row[4],
1125
                           "longitude": row[5],
1126
                           "rated_capacity": row[6],
1127
                           "rated_power": row[7],
1128
                           "contact": contact_dict.get(row[8], None),
1129
                           "cost_center": cost_center_dict.get(row[9], None),
1130
                           "svg": svg_dict.get(row[10], None),
1131
                           "is_cost_data_displayed": bool(row[11]),
1132
                           "description": row[12]}
1133
1134
        resp.text = json.dumps(meta_result)
1135
1136
1137
class EnergyStoragePowerStationImport:
1138
    def __init__(self):
1139
        """"Initializes Class"""
1140
        pass
1141
1142
    @staticmethod
1143
    def on_options(req, resp):
1144
        resp.status = falcon.HTTP_200
1145
1146
    @staticmethod
1147
    @user_logger
1148
    def on_post(req, resp):
1149
        """Handles POST requests"""
1150
        admin_control(req)
1151
        try:
1152
            raw_json = req.stream.read().decode('utf-8')
1153
        except Exception as ex:
1154
            raise falcon.HTTPError(status=falcon.HTTP_400,
1155
                                   title='API.BAD_REQUEST',
1156
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1157
1158
        new_values = json.loads(raw_json)
1159
1160
        print(new_values)
1161
        if 'name' not in new_values.keys() or \
1162
                not isinstance(new_values['name'], str) or \
1163
                len(str.strip(new_values['name'])) == 0:
1164
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1165
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_NAME')
1166
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
1167
        if config.utc_offset[0] == '-':
1168
            timezone_offset = -timezone_offset
1169
        name = str.strip(new_values['name']) + \
1170
            (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds')
1171
1172
        if 'address' not in new_values.keys() or \
1173
                not isinstance(new_values['address'], str) or \
1174
                len(str.strip(new_values['address'])) == 0:
1175
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1176
                                   description='API.INVALID_ADDRESS_VALUE')
1177
        address = str.strip(new_values['address'])
1178
1179
        if 'latitude' not in new_values.keys() or \
1180
                not (isinstance(new_values['latitude'], float) or
1181
                     isinstance(new_values['latitude'], int)) or \
1182
                new_values['latitude'] < -90.0 or \
1183
                new_values['latitude'] > 90.0:
1184
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1185
                                   description='API.INVALID_LATITUDE_VALUE')
1186
        latitude = new_values['latitude']
1187
1188
        if 'longitude' not in new_values.keys() or \
1189
                not (isinstance(new_values['longitude'], float) or
1190
                     isinstance(new_values['longitude'], int)) or \
1191
                new_values['longitude'] < -180.0 or \
1192
                new_values['longitude'] > 180.0:
1193
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1194
                                   description='API.INVALID_LONGITUDE_VALUE')
1195
        longitude = new_values['longitude']
1196
1197
        if 'rated_capacity' not in new_values.keys() or \
1198
                not (isinstance(new_values['rated_capacity'], float) or
1199
                     isinstance(new_values['rated_capacity'], int)) or \
1200
                new_values['rated_capacity'] < 0.0:
1201
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1202
                                   description='API.INVALID_RATED_CAPACITY')
1203
        rated_capacity = new_values['rated_capacity']
1204
1205
        if 'rated_power' not in new_values.keys() or \
1206
                not (isinstance(new_values['rated_power'], float) or
1207
                     isinstance(new_values['rated_power'], int)) or \
1208
                new_values['rated_power'] < 0.0:
1209
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1210
                                   description='API.INVALID_RATED_POWER')
1211
        rated_power = new_values['rated_power']
1212
1213
        if 'contact' not in new_values.keys() or \
1214
                'id' not in new_values['contact'].keys() or \
1215
                not isinstance(new_values['contact']['id'], int) or \
1216
                new_values['contact']['id'] <= 0:
1217
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1218
                                   description='API.INVALID_CONTACT_ID')
1219
        contact_id = new_values['contact']['id']
1220
1221
        if 'cost_center' not in new_values.keys() or \
1222
                'id' not in new_values['cost_center'].keys() or \
1223
                not isinstance(new_values['cost_center']['id'], int) or \
1224
                new_values['cost_center']['id'] <= 0:
1225
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1226
                                   description='API.INVALID_COST_CENTER_ID')
1227
        cost_center_id = new_values['cost_center']['id']
1228
1229
        if 'svg' not in new_values.keys() or \
1230
                'id' not in new_values['svg'].keys() or \
1231
                not isinstance(new_values['svg']['id'], int) or \
1232
                new_values['svg']['id'] <= 0:
1233
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1234
                                   description='API.INVALID_SVG_ID')
1235
        svg_id = new_values['svg']['id']
1236
1237
        if 'is_cost_data_displayed' not in new_values['data'].keys() or \
1238
                not isinstance(new_values['data']['is_cost_data_displayed'], bool):
1239
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1240
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED')
1241
        is_cost_data_displayed = new_values['data']['is_cost_data_displayed']
1242
1243
        if 'description' in new_values.keys() and \
1244
                new_values['description'] is not None and \
1245
                len(str(new_values['description'])) > 0:
1246
            description = str.strip(new_values['description'])
1247
        else:
1248
            description = None
1249
1250
        cnx = mysql.connector.connect(**config.myems_system_db)
1251
        cursor = cnx.cursor()
1252
1253
        cursor.execute(" SELECT name "
1254
                       " FROM tbl_energy_storage_power_stations "
1255
                       " WHERE name = %s ", (name,))
1256
        if cursor.fetchone() is not None:
1257
            cursor.close()
1258
            cnx.close()
1259
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1260
                                   description='API.ENERGY_STORAGE_POWER_STATION_NAME_IS_ALREADY_IN_USE')
1261
1262
        cursor.execute(" SELECT name "
1263
                       " FROM tbl_contacts "
1264
                       " WHERE id = %s ",
1265
                       (contact_id,))
1266
        row = cursor.fetchone()
1267
        if row is None:
1268
            cursor.close()
1269
            cnx.close()
1270
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1271
                                   description='API.CONTACT_NOT_FOUND')
1272
1273
        cursor.execute(" SELECT name "
1274
                       " FROM tbl_cost_centers "
1275
                       " WHERE id = %s ",
1276
                       (cost_center_id,))
1277
        row = cursor.fetchone()
1278
        if row is None:
1279
            cursor.close()
1280
            cnx.close()
1281
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1282
                                   description='API.COST_CENTER_NOT_FOUND')
1283
1284
        cursor.execute(" SELECT name "
1285
                       " FROM tbl_svgs "
1286
                       " WHERE id = %s ",
1287
                       (svg_id,))
1288
        row = cursor.fetchone()
1289
        if row is None:
1290
            cursor.close()
1291
            cnx.close()
1292
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1293
                                   description='API.SVG_NOT_FOUND')
1294
1295
        add_values = (" INSERT INTO tbl_energy_storage_power_stations "
1296
                      "    (name, uuid, address, latitude, longitude, rated_capacity, rated_power, "
1297
                      "     contact_id, cost_center_id, svg_id, is_cost_data_displayed, description) "
1298
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
1299
        cursor.execute(add_values, (name,
1300
                                    str(uuid.uuid4()),
1301
                                    address,
1302
                                    latitude,
1303
                                    longitude,
1304
                                    rated_capacity,
1305
                                    rated_power,
1306
                                    contact_id,
1307
                                    cost_center_id,
1308
                                    svg_id,
1309
                                    is_cost_data_displayed,
1310
                                    description))
1311
        new_id = cursor.lastrowid
1312
        cnx.commit()
1313
        cursor.close()
1314
        cnx.close()
1315
1316
        resp.status = falcon.HTTP_201
1317
        resp.location = '/energystoragepowerstations/' + str(new_id)
1318
1319
1320
class EnergyStoragePowerStationClone:
1321
    def __init__(self):
1322
        """Initializes Class"""
1323
        pass
1324
1325
    @staticmethod
1326
    def on_options(req, resp, id_):
1327
        resp.status = falcon.HTTP_200
1328
1329
    @staticmethod
1330
    @user_logger
1331
    def on_post(req, resp, id_):
1332
        """Handles POST requests"""
1333
        admin_control(req)
1334
        if not id_.isdigit() or int(id_) <= 0:
1335
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1336
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
1337
1338
        cnx = mysql.connector.connect(**config.myems_system_db)
1339
        cursor = cnx.cursor()
1340
1341
        query = (" SELECT id, name, uuid, "
1342
                 "        address, latitude, longitude, rated_capacity, rated_power, "
1343
                 "        contact_id, cost_center_id, svg_id, is_cost_data_displayed, description "
1344
                 " FROM tbl_energy_storage_power_stations "
1345
                 " WHERE id = %s ")
1346
        cursor.execute(query, (id_,))
1347
        row = cursor.fetchone()
1348
1349
        if row is None:
1350
            cursor.close()
1351
            cnx.close()
1352
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1353
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
1354
        else:
1355
            meta_result = {"name": row[1],
1356
                           "uuid": row[2],
1357
                           "address": row[3],
1358
                           "latitude": row[4],
1359
                           "longitude": row[5],
1360
                           "rated_capacity": row[6],
1361
                           "rated_power": row[7],
1362
                           "contact_id": row[8],
1363
                           "cost_center_id": row[9],
1364
                           "svg_id": row[10],
1365
                           "is_cost_data_displayed": row[11],
1366
                           "description": row[12]}
1367
1368
            timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
1369
            if config.utc_offset[0] == '-':
1370
                timezone_offset = -timezone_offset
1371
            new_name = str.strip(meta_result['name']) + \
1372
                (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds')
1373
1374
            add_values = (" INSERT INTO tbl_energy_storage_power_stations "
1375
                          "    (name, uuid, address, latitude, longitude, rated_capacity, rated_power, "
1376
                          "     contact_id, cost_center_id, svg_id, is_cost_data_displayed, description) "
1377
                          " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
1378
            cursor.execute(add_values, (new_name,
1379
                                        str(uuid.uuid4()),
1380
                                        meta_result['address'],
1381
                                        meta_result['latitude'],
1382
                                        meta_result['longitude'],
1383
                                        meta_result['rated_capacity'],
1384
                                        meta_result['rated_power'],
1385
                                        meta_result['contact_id'],
1386
                                        meta_result['cost_center_id'],
1387
                                        meta_result['svg_id'],
1388
                                        meta_result['is_cost_data_displayed'],
1389
                                        meta_result['description']))
1390
            new_id = cursor.lastrowid
1391
            cnx.commit()
1392
            cursor.close()
1393
            cnx.close()
1394
1395
            resp.status = falcon.HTTP_201
1396
            resp.location = '/energystoragepowerstations/' + str(new_id)
1397