Passed
Push — master ( 36be38...62620d )
by
unknown
13:27 queued 01:12
created

SpaceEnergyStoragePowerStationCollection.on_get()   F

Complexity

Conditions 14

Size

Total Lines 77
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 51
dl 0
loc 77
rs 3.6
c 0
b 0
f 0
cc 14
nop 3

How to fix   Long Method    Complexity   

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:

Complexity

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

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

1
import uuid
2
from datetime import datetime, timedelta
3
import falcon
4
import mysql.connector
5
import simplejson as json
6
from anytree import AnyNode, LevelOrderIter
7
from anytree.exporter import JsonExporter
8
from core.useractivity import user_logger, admin_control, access_control, api_key_control
9
import config
10
11
12
class SpaceCollection:
13
    def __init__(self):
14
        """Initializes Class"""
15
        pass
16
17
    @staticmethod
18
    def on_options(req, resp):
19
        resp.status = falcon.HTTP_200
20
21
    @staticmethod
22
    def on_get(req, resp):
23
        if 'API-KEY' not in req.headers or \
24
                not isinstance(req.headers['API-KEY'], str) or \
25
                len(str.strip(req.headers['API-KEY'])) == 0:
26
            access_control(req)
27
        else:
28
            api_key_control(req)
29
        cnx = mysql.connector.connect(**config.myems_system_db)
30
        cursor = cnx.cursor()
31
32
        query = (" SELECT id, name, uuid "
33
                 " FROM tbl_spaces ")
34
        cursor.execute(query)
35
        rows_spaces = cursor.fetchall()
36
37
        space_dict = dict()
38
        if rows_spaces is not None and len(rows_spaces) > 0:
39
            for row in rows_spaces:
40
                space_dict[row[0]] = {"id": row[0],
41
                                      "name": row[1],
42
                                      "uuid": row[2]}
43
44
        query = (" SELECT id, name, utc_offset "
45
                 " FROM tbl_timezones ")
46
        cursor.execute(query)
47
        rows_timezones = cursor.fetchall()
48
49
        timezone_dict = dict()
50
        if rows_timezones is not None and len(rows_timezones) > 0:
51
            for row in rows_timezones:
52
                timezone_dict[row[0]] = {"id": row[0],
53
                                         "name": row[1],
54
                                         "utc_offset": row[2]}
55
56
        query = (" SELECT id, name, uuid "
57
                 " FROM tbl_contacts ")
58
        cursor.execute(query)
59
        rows_contacts = cursor.fetchall()
60
61
        contact_dict = dict()
62
        if rows_contacts is not None and len(rows_contacts) > 0:
63
            for row in rows_contacts:
64
                contact_dict[row[0]] = {"id": row[0],
65
                                        "name": row[1],
66
                                        "uuid": row[2]}
67
68
        query = (" SELECT id, name, uuid "
69
                 " FROM tbl_cost_centers ")
70
        cursor.execute(query)
71
        rows_cost_centers = cursor.fetchall()
72
73
        cost_center_dict = dict()
74
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
75
            for row in rows_cost_centers:
76
                cost_center_dict[row[0]] = {"id": row[0],
77
                                            "name": row[1],
78
                                            "uuid": row[2]}
79
80
        query = (" SELECT id, name, uuid, "
81
                 "      parent_space_id, area, number_of_occupants, timezone_id, is_input_counted, is_output_counted, "
82
                 "      contact_id, cost_center_id, latitude, longitude, description "
83
                 " FROM tbl_spaces "
84
                 " ORDER BY id ")
85
        cursor.execute(query)
86
        rows_spaces = cursor.fetchall()
87
88
        result = list()
89 View Code Duplication
        if rows_spaces is not None and len(rows_spaces) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
90
            for row in rows_spaces:
91
                meta_result = {"id": row[0],
92
                               "name": row[1],
93
                               "uuid": row[2],
94
                               "parent_space": space_dict.get(row[3], None),
95
                               "area": row[4],
96
                               "number_of_occupants": row[5],
97
                               "timezone": timezone_dict.get(row[6], None),
98
                               "is_input_counted": bool(row[7]),
99
                               "is_output_counted": bool(row[8]),
100
                               "contact": contact_dict.get(row[9], None),
101
                               "cost_center": cost_center_dict.get(row[10], None),
102
                               "latitude": row[11],
103
                               "longitude": row[12],
104
                               "description": row[13],
105
                               "qrcode": "space:" + row[2]}
106
                result.append(meta_result)
107
108
        cursor.close()
109
        cnx.close()
110
        resp.text = json.dumps(result)
111
112
    @staticmethod
113
    @user_logger
114
    def on_post(req, resp):
115
        """Handles POST requests"""
116
        admin_control(req)
117
        try:
118
            raw_json = req.stream.read().decode('utf-8')
119
            new_values = json.loads(raw_json)
120
        except Exception as ex:
121
            raise falcon.HTTPError(status=falcon.HTTP_400,
122
                                   title='API.BAD_REQUEST',
123
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
124
125
        if 'name' not in new_values['data'].keys() or \
126
                not isinstance(new_values['data']['name'], str) or \
127
                len(str.strip(new_values['data']['name'])) == 0:
128
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
129
                                   description='API.INVALID_SPACE_NAME')
130
        name = str.strip(new_values['data']['name'])
131
132
        if 'parent_space_id' in new_values['data'].keys():
133
            if new_values['data']['parent_space_id'] <= 0:
134
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
135
                                       description='API.INVALID_PARENT_SPACE_ID')
136
            parent_space_id = new_values['data']['parent_space_id']
137
        else:
138
            parent_space_id = None
139
140
        if 'area' not in new_values['data'].keys() or \
141
                not (isinstance(new_values['data']['area'], float) or
142
                     isinstance(new_values['data']['area'], int)) or \
143
                new_values['data']['area'] <= 0.0:
144
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
145
                                   description='API.INVALID_AREA_VALUE')
146
        area = new_values['data']['area']
147
148
        if 'number_of_occupants' not in new_values['data'].keys() or \
149
                not (isinstance(new_values['data']['number_of_occupants'], float) or
150
                     isinstance(new_values['data']['number_of_occupants'], int)) or \
151
                new_values['data']['number_of_occupants'] <= 0:
152
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
153
                                   description='API.INVALID_NUMBER_OF_OCCUPANTS')
154
        number_of_occupants = new_values['data']['number_of_occupants']
155
156
        if 'timezone_id' not in new_values['data'].keys() or \
157
                not isinstance(new_values['data']['timezone_id'], int) or \
158
                new_values['data']['timezone_id'] <= 0:
159
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
160
                                   description='API.INVALID_TIMEZONE_ID')
161
        timezone_id = new_values['data']['timezone_id']
162
163
        if 'is_input_counted' not in new_values['data'].keys() or \
164
                not isinstance(new_values['data']['is_input_counted'], bool):
165
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
166
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
167
        is_input_counted = new_values['data']['is_input_counted']
168
169
        if 'is_output_counted' not in new_values['data'].keys() or \
170
                not isinstance(new_values['data']['is_output_counted'], bool):
171
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
172
                                   description='API.INVALID_IS_OUTPUT_COUNTED_VALUE')
173
        is_output_counted = new_values['data']['is_output_counted']
174
175
        if 'contact_id' in new_values['data'].keys():
176
            if new_values['data']['contact_id'] <= 0:
177
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
178
                                       description='API.INVALID_CONTACT_ID')
179
            contact_id = new_values['data']['contact_id']
180
        else:
181
            contact_id = None
182
183
        if 'cost_center_id' in new_values['data'].keys():
184
            if new_values['data']['cost_center_id'] <= 0:
185
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
186
                                       description='API.INVALID_COST_CENTER_ID')
187
            cost_center_id = new_values['data']['cost_center_id']
188
        else:
189
            cost_center_id = None
190
191 View Code Duplication
        if 'latitude' in new_values['data'].keys() and new_values['data']['latitude'] is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
192
            if not (isinstance(new_values['data']['latitude'], float) or
193
                    isinstance(new_values['data']['latitude'], int)) or \
194
                    new_values['data']['latitude'] < -90.0 or \
195
                    new_values['data']['latitude'] > 90.0:
196
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
197
                                       description='API.INVALID_LATITUDE_VALUE')
198
            latitude = new_values['data']['latitude']
199
        else:
200
            latitude = None
201
202 View Code Duplication
        if 'longitude' in new_values['data'].keys() and new_values['data']['longitude'] is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
203
            if not (isinstance(new_values['data']['longitude'], float) or
204
                    isinstance(new_values['data']['longitude'], int)) or \
205
                    new_values['data']['longitude'] < -180.0 or \
206
                    new_values['data']['longitude'] > 180.0:
207
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
208
                                       description='API.INVALID_LONGITUDE_VALUE')
209
            longitude = new_values['data']['longitude']
210
        else:
211
            longitude = None
212
213
        if 'description' in new_values['data'].keys() and \
214
                new_values['data']['description'] is not None and \
215
                len(str(new_values['data']['description'])) > 0:
216
            description = str.strip(new_values['data']['description'])
217
        else:
218
            description = None
219
220
        cnx = mysql.connector.connect(**config.myems_system_db)
221
        cursor = cnx.cursor()
222
223
        cursor.execute(" SELECT name "
224
                       " FROM tbl_spaces "
225
                       " WHERE name = %s ", (name,))
226
        if cursor.fetchone() is not None:
227
            cursor.close()
228
            cnx.close()
229
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
230
                                   description='API.SPACE_NAME_IS_ALREADY_IN_USE')
231
232 View Code Duplication
        if parent_space_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
233
            cursor.execute(" SELECT name "
234
                           " FROM tbl_spaces "
235
                           " WHERE id = %s ",
236
                           (new_values['data']['parent_space_id'],))
237
            row = cursor.fetchone()
238
            if row is None:
239
                cursor.close()
240
                cnx.close()
241
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
242
                                       description='API.PARENT_SPACE_NOT_FOUND')
243
244
        cursor.execute(" SELECT name "
245
                       " FROM tbl_timezones "
246
                       " WHERE id = %s ",
247
                       (new_values['data']['timezone_id'],))
248
        if cursor.fetchone() is None:
249
            cursor.close()
250
            cnx.close()
251
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
252
                                   description='API.TIMEZONE_NOT_FOUND')
253 View Code Duplication
        if contact_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
254
            cursor.execute(" SELECT name "
255
                           " FROM tbl_contacts "
256
                           " WHERE id = %s ",
257
                           (new_values['data']['contact_id'],))
258
            row = cursor.fetchone()
259
            if row is None:
260
                cursor.close()
261
                cnx.close()
262
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
263
                                       description='API.CONTACT_NOT_FOUND')
264
265
        if cost_center_id is not None:
266
            cursor.execute(" SELECT name "
267
                           " FROM tbl_cost_centers "
268
                           " WHERE id = %s ",
269
                           (new_values['data']['cost_center_id'],))
270
            row = cursor.fetchone()
271
            if row is None:
272
                cursor.close()
273
                cnx.close()
274
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
275
                                       description='API.COST_CENTER_NOT_FOUND')
276
277
        add_values = (" INSERT INTO tbl_spaces "
278
                      "    (name, uuid, parent_space_id, area, number_of_occupants, timezone_id, is_input_counted, "
279
                      "     is_output_counted, contact_id, cost_center_id, latitude, longitude, description) "
280
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
281
        cursor.execute(add_values, (name,
282
                                    str(uuid.uuid4()),
283
                                    parent_space_id,
284
                                    area,
285
                                    number_of_occupants,
286
                                    timezone_id,
287
                                    is_input_counted,
288
                                    is_output_counted,
289
                                    contact_id,
290
                                    cost_center_id,
291
                                    latitude,
292
                                    longitude,
293
                                    description))
294
        new_id = cursor.lastrowid
295
        cnx.commit()
296
        cursor.close()
297
        cnx.close()
298
299
        resp.status = falcon.HTTP_201
300
        resp.location = '/spaces/' + str(new_id)
301
302
303
class SpaceItem:
304
    def __init__(self):
305
        """Initializes Class"""
306
        pass
307
308
    @staticmethod
309
    def on_options(req, resp, id_):
310
        resp.status = falcon.HTTP_200
311
312
    @staticmethod
313
    def on_get(req, resp, id_):
314
        if 'API-KEY' not in req.headers or \
315
                not isinstance(req.headers['API-KEY'], str) or \
316
                len(str.strip(req.headers['API-KEY'])) == 0:
317
            access_control(req)
318
        else:
319
            api_key_control(req)
320
        if not id_.isdigit() or int(id_) <= 0:
321
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
322
                                   description='API.INVALID_METER_ID')
323
324
        cnx = mysql.connector.connect(**config.myems_system_db)
325
        cursor = cnx.cursor()
326
327
        query = (" SELECT id, name, uuid "
328
                 " FROM tbl_spaces ")
329
        cursor.execute(query)
330
        rows_spaces = cursor.fetchall()
331
332
        space_dict = dict()
333
        if rows_spaces is not None and len(rows_spaces) > 0:
334
            for row in rows_spaces:
335
                space_dict[row[0]] = {"id": row[0],
336
                                      "name": row[1],
337
                                      "uuid": row[2]}
338
339
        query = (" SELECT id, name, utc_offset "
340
                 " FROM tbl_timezones ")
341
        cursor.execute(query)
342
        rows_timezones = cursor.fetchall()
343
344
        timezone_dict = dict()
345
        if rows_timezones is not None and len(rows_timezones) > 0:
346
            for row in rows_timezones:
347
                timezone_dict[row[0]] = {"id": row[0],
348
                                         "name": row[1],
349
                                         "utc_offset": row[2]}
350
351
        query = (" SELECT id, name, uuid "
352
                 " FROM tbl_contacts ")
353
        cursor.execute(query)
354
        rows_contacts = cursor.fetchall()
355
356
        contact_dict = dict()
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
        query = (" SELECT id, name, uuid "
364
                 " FROM tbl_cost_centers ")
365
        cursor.execute(query)
366
        rows_cost_centers = cursor.fetchall()
367
368
        cost_center_dict = dict()
369
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
370
            for row in rows_cost_centers:
371
                cost_center_dict[row[0]] = {"id": row[0],
372
                                            "name": row[1],
373
                                            "uuid": row[2]}
374
375
        query = (" SELECT id, name, uuid, "
376
                 "       parent_space_id, area, number_of_occupants, timezone_id, is_input_counted, is_output_counted, "
377
                 "       contact_id, cost_center_id, latitude, longitude, description "
378
                 " FROM tbl_spaces "
379
                 " WHERE id = %s ")
380
        cursor.execute(query, (id_,))
381
        row = cursor.fetchone()
382
        cursor.close()
383
        cnx.close()
384
385
        if row is None:
386
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
387
                                   description='API.SPACE_NOT_FOUND')
388
        else:
389
            meta_result = {"id": row[0],
390
                           "name": row[1],
391
                           "uuid": row[2],
392
                           "parent_space_id": space_dict.get(row[3], None),
393
                           "area": row[4],
394
                           "number_of_occupants": row[5],
395
                           "timezone": timezone_dict.get(row[6], None),
396
                           "is_input_counted": bool(row[7]),
397
                           "is_output_counted": bool(row[8]),
398
                           "contact": contact_dict.get(row[9], None),
399
                           "cost_center": cost_center_dict.get(row[10], None),
400
                           "latitude": row[11],
401
                           "longitude": row[12],
402
                           "description": row[13],
403
                           "qrcode": "space:" + row[2]}
404
405
        resp.text = json.dumps(meta_result)
406
407
    @staticmethod
408
    @user_logger
409
    def on_delete(req, resp, id_):
410
        admin_control(req)
411
        if not id_.isdigit() or int(id_) <= 0:
412
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
413
                                   description='API.INVALID_SPACE_ID')
414
        if int(id_) == 1:
415
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
416
                                   description='API.THIS_SPACE_CANNOT_BE_DELETED')
417
418
        cnx = mysql.connector.connect(**config.myems_system_db)
419
        cursor = cnx.cursor()
420
421
        cursor.execute(" SELECT name "
422
                       " FROM tbl_spaces "
423
                       " WHERE id = %s ", (id_,))
424
        if cursor.fetchone() is None:
425
            cursor.close()
426
            cnx.close()
427
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
428
                                   description='API.SPACE_NOT_FOUND')
429
430
        # checkout relation with children spaces
431
        cursor.execute(" SELECT id "
432
                       " FROM tbl_spaces "
433
                       " WHERE parent_space_id = %s ",
434
                       (id_,))
435
        rows_spaces = cursor.fetchall()
436
        if rows_spaces is not None and len(rows_spaces) > 0:
437
            cursor.close()
438
            cnx.close()
439
            raise falcon.HTTPError(status=falcon.HTTP_400,
440
                                   title='API.BAD_REQUEST',
441
                                   description='API.THERE_IS_RELATION_WITH_CHILDREN_SPACES')
442
443
        # delete relation with combined equipment
444
        cursor.execute(" DELETE FROM tbl_spaces_combined_equipments WHERE space_id = %s ", (id_,))
445
446
        # delete relation with commands
447
        cursor.execute(" DELETE FROM tbl_spaces_commands WHERE space_id = %s ", (id_,))
448
449
        # delete relation with equipments
450
        cursor.execute(" DELETE FROM tbl_spaces_equipments WHERE space_id = %s ", (id_,))
451
452
        # delete relation with meters
453
        cursor.execute(" DELETE FROM tbl_spaces_meters WHERE space_id = %s ", (id_,))
454
455
        # delete relation with offline meters
456
        cursor.execute(" DELETE FROM tbl_spaces_offline_meters WHERE space_id = %s ", (id_,))
457
458
        # delete relation with points
459
        cursor.execute(" DELETE FROM tbl_spaces_points WHERE space_id = %s ", (id_,))
460
461
        # delete relation with sensors
462
        cursor.execute(" DELETE FROM tbl_spaces_sensors WHERE space_id = %s ", (id_,))
463
464
        # delete relation with shopfloors
465
        cursor.execute(" DELETE FROM tbl_spaces_shopfloors WHERE space_id = %s ", (id_,))
466
467
        # delete relation with stores
468
        cursor.execute(" DELETE FROM tbl_spaces_stores WHERE space_id = %s ", (id_,))
469
470
        # delete relation with tenants
471
        cursor.execute(" DELETE FROM tbl_spaces_tenants WHERE space_id = %s ", (id_,))
472
473
        # delete relation with virtual meters
474
        cursor.execute(" DELETE FROM tbl_spaces_virtual_meters WHERE space_id = %s ", (id_,))
475
476
        # delete relation with working calendars
477
        cursor.execute(" DELETE FROM tbl_spaces_working_calendars WHERE space_id = %s ", (id_,))
478
479
        cursor.execute(" DELETE FROM tbl_spaces WHERE id = %s ", (id_,))
480
        cnx.commit()
481
482
        cursor.close()
483
        cnx.close()
484
485
        resp.status = falcon.HTTP_204
486
487
    @staticmethod
488
    @user_logger
489
    def on_put(req, resp, id_):
490
        """Handles PUT requests"""
491
        admin_control(req)
492
        try:
493
            raw_json = req.stream.read().decode('utf-8')
494
        except Exception as ex:
495
            raise falcon.HTTPError(status=falcon.HTTP_400,
496
                                   title='API.BAD_REQUEST',
497
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
498
499
        if not id_.isdigit() or int(id_) <= 0:
500
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
501
                                   description='API.INVALID_SPACE_ID')
502
503
        new_values = json.loads(raw_json)
504
505
        if 'name' not in new_values['data'].keys() or \
506
                not isinstance(new_values['data']['name'], str) or \
507
                len(str.strip(new_values['data']['name'])) == 0:
508
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
509
                                   description='API.INVALID_SPACE_NAME')
510
        name = str.strip(new_values['data']['name'])
511
512
        if int(id_) == 1:
513
            parent_space_id = None
514
        else:
515
            if 'parent_space_id' not in new_values['data'].keys() or \
516
                    new_values['data']['parent_space_id'] is None or \
517
                    not isinstance(new_values['data']['parent_space_id'], int) or \
518
                    int(new_values['data']['parent_space_id']) <= 0:
519
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
520
                                       description='API.INVALID_TIMEZONE_ID')
521
            parent_space_id = int(new_values['data']['parent_space_id'])
522
523
        if 'area' not in new_values['data'].keys() or \
524
                not (isinstance(new_values['data']['area'], float) or
525
                     isinstance(new_values['data']['area'], int)) or \
526
                new_values['data']['area'] <= 0.0:
527
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
528
                                   description='API.INVALID_AREA_VALUE')
529
        area = new_values['data']['area']
530
531
        if 'number_of_occupants' not in new_values['data'].keys() or \
532
                not (isinstance(new_values['data']['number_of_occupants'], float) or
533
                     isinstance(new_values['data']['number_of_occupants'], int)) or \
534
                new_values['data']['number_of_occupants'] <= 0:
535
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
536
                                   description='API.INVALID_NUMBER_OF_OCCUPANTS')
537
        number_of_occupants = new_values['data']['number_of_occupants']
538
539
        if 'timezone_id' not in new_values['data'].keys() or \
540
                not isinstance(new_values['data']['timezone_id'], int) or \
541
                new_values['data']['timezone_id'] <= 0:
542
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
543
                                   description='API.INVALID_TIMEZONE_ID')
544
        timezone_id = new_values['data']['timezone_id']
545
546
        if 'is_input_counted' not in new_values['data'].keys() or \
547
                not isinstance(new_values['data']['is_input_counted'], bool):
548
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
549
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
550
        is_input_counted = new_values['data']['is_input_counted']
551
552
        if 'is_output_counted' not in new_values['data'].keys() or \
553
                not isinstance(new_values['data']['is_output_counted'], bool):
554
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
555
                                   description='API.INVALID_IS_OUTPUT_COUNTED_VALUE')
556
        is_output_counted = new_values['data']['is_output_counted']
557
558
        if 'contact_id' in new_values['data'].keys() and new_values['data']['contact_id'] is not None:
559
            if new_values['data']['contact_id'] <= 0:
560
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
561
                                       description='API.INVALID_CONTACT_ID')
562
            contact_id = new_values['data']['contact_id']
563
        else:
564
            contact_id = None
565
566
        if 'cost_center_id' in new_values['data'].keys():
567
            if new_values['data']['cost_center_id'] <= 0:
568
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
569
                                       description='API.INVALID_COST_CENTER_ID')
570
            cost_center_id = new_values['data']['cost_center_id']
571
        else:
572
            cost_center_id = None
573
574 View Code Duplication
        if 'latitude' in new_values['data'].keys():
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
575
            if new_values['data']['latitude'] is not None:
576
                if not (isinstance(new_values['data']['latitude'], float) or
577
                        isinstance(new_values['data']['latitude'], int)) or \
578
                        new_values['data']['latitude'] < -90.0 or \
579
                        new_values['data']['latitude'] > 90.0:
580
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
581
                                           description='API.INVALID_LATITUDE_VALUE')
582
                latitude = new_values['data']['latitude']
583
            else:
584
                latitude = None
585
        else:
586
            latitude = None
587
588 View Code Duplication
        if 'longitude' in new_values['data'].keys():
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
589
            if new_values['data']['latitude'] is not None:
590
                if not (isinstance(new_values['data']['longitude'], float) or
591
                        isinstance(new_values['data']['longitude'], int)) or \
592
                        new_values['data']['longitude'] < -180.0 or \
593
                        new_values['data']['longitude'] > 180.0:
594
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
595
                                           description='API.INVALID_LONGITUDE_VALUE')
596
                longitude = new_values['data']['longitude']
597
            else:
598
                longitude = None
599
        else:
600
            longitude = None
601
602
        if 'description' in new_values['data'].keys() and \
603
                new_values['data']['description'] is not None and \
604
                len(str(new_values['data']['description'])) > 0:
605
            description = str.strip(new_values['data']['description'])
606
        else:
607
            description = None
608
609
        cnx = mysql.connector.connect(**config.myems_system_db)
610
        cursor = cnx.cursor()
611
612
        cursor.execute(" SELECT name "
613
                       " FROM tbl_spaces "
614
                       " WHERE id = %s ", (id_,))
615
        if cursor.fetchone() is None:
616
            cursor.close()
617
            cnx.close()
618
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
619
                                   description='API.SPACE_NOT_FOUND')
620
621
        cursor.execute(" SELECT name "
622
                       " FROM tbl_spaces "
623
                       " WHERE name = %s AND id != %s ", (name, id_))
624
        if cursor.fetchone() is not None:
625
            cursor.close()
626
            cnx.close()
627
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
628
                                   description='API.SPACE_NAME_IS_ALREADY_IN_USE')
629
630 View Code Duplication
        if parent_space_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
631
            cursor.execute(" SELECT name "
632
                           " FROM tbl_spaces "
633
                           " WHERE id = %s ",
634
                           (new_values['data']['parent_space_id'],))
635
            row = cursor.fetchone()
636
            if row is None:
637
                cursor.close()
638
                cnx.close()
639
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
640
                                       description='API.PARENT_SPACE_NOT_FOUND')
641
642
        cursor.execute(" SELECT name "
643
                       " FROM tbl_timezones "
644
                       " WHERE id = %s ",
645
                       (new_values['data']['timezone_id'],))
646
        if cursor.fetchone() is None:
647
            cursor.close()
648
            cnx.close()
649
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
650
                                   description='API.TIMEZONE_NOT_FOUND')
651 View Code Duplication
        if contact_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
652
            cursor.execute(" SELECT name "
653
                           " FROM tbl_contacts "
654
                           " WHERE id = %s ",
655
                           (new_values['data']['contact_id'],))
656
            row = cursor.fetchone()
657
            if row is None:
658
                cursor.close()
659
                cnx.close()
660
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
661
                                       description='API.CONTACT_NOT_FOUND')
662
663
        if cost_center_id is not None:
664
            cursor.execute(" SELECT name "
665
                           " FROM tbl_cost_centers "
666
                           " WHERE id = %s ",
667
                           (new_values['data']['cost_center_id'],))
668
            row = cursor.fetchone()
669
            if row is None:
670
                cursor.close()
671
                cnx.close()
672
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
673
                                       description='API.COST_CENTER_NOT_FOUND')
674
675
        update_row = (" UPDATE tbl_spaces "
676
                      " SET name = %s, parent_space_id = %s, area = %s, number_of_occupants = %s, timezone_id = %s, "
677
                      "     is_input_counted = %s, is_output_counted = %s, contact_id = %s, cost_center_id = %s, "
678
                      "     latitude = %s, longitude = %s, description = %s "
679
                      " WHERE id = %s ")
680
        cursor.execute(update_row, (name,
681
                                    parent_space_id,
682
                                    area,
683
                                    number_of_occupants,
684
                                    timezone_id,
685
                                    is_input_counted,
686
                                    is_output_counted,
687
                                    contact_id,
688
                                    cost_center_id,
689
                                    latitude,
690
                                    longitude,
691
                                    description,
692
                                    id_))
693
        cnx.commit()
694
695
        cursor.close()
696
        cnx.close()
697
698
        resp.status = falcon.HTTP_200
699
700
701
class SpaceChildrenCollection:
702
    def __init__(self):
703
        """Initializes Class"""
704
        pass
705
706
    @staticmethod
707
    def on_options(req, resp, id_):
708
        resp.status = falcon.HTTP_200
709
710
    @staticmethod
711
    def on_get(req, resp, id_):
712
        if 'API-KEY' not in req.headers or \
713
                not isinstance(req.headers['API-KEY'], str) or \
714
                len(str.strip(req.headers['API-KEY'])) == 0:
715
            access_control(req)
716
        else:
717
            api_key_control(req)
718
        if not id_.isdigit() or int(id_) <= 0:
719
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
720
                                   description='API.INVALID_SPACE_ID')
721
722
        cnx = mysql.connector.connect(**config.myems_system_db)
723
        cursor = cnx.cursor()
724
725
        query = (" SELECT id, name, uuid, "
726
                 "  parent_space_id, area, number_of_occupants, timezone_id, is_input_counted, is_output_counted, "
727
                 "  contact_id, cost_center_id, latitude, longitude, description "
728
                 " FROM tbl_spaces "
729
                 " WHERE id = %s ")
730
        cursor.execute(query, (id_,))
731
        row_current_space = cursor.fetchone()
732
        if row_current_space is None:
733
            cursor.close()
734
            cnx.close()
735
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
736
                                   description='API.SPACE_NOT_FOUND')
737
        # note: row_current_space will be used at the end
738
739
        query = (" SELECT id, name, uuid "
740
                 " FROM tbl_spaces ")
741
        cursor.execute(query)
742
        rows_spaces = cursor.fetchall()
743
744
        space_dict = dict()
745
        if rows_spaces is not None and len(rows_spaces) > 0:
746
            for row in rows_spaces:
747
                space_dict[row[0]] = {"id": row[0],
748
                                      "name": row[1],
749
                                      "uuid": row[2]}
750
751
        query = (" SELECT id, name, utc_offset "
752
                 " FROM tbl_timezones ")
753
        cursor.execute(query)
754
        rows_timezones = cursor.fetchall()
755
756
        timezone_dict = dict()
757
        if rows_timezones is not None and len(rows_timezones) > 0:
758
            for row in rows_timezones:
759
                timezone_dict[row[0]] = {"id": row[0],
760
                                         "name": row[1],
761
                                         "utc_offset": row[2]}
762
763
        query = (" SELECT id, name, uuid "
764
                 " FROM tbl_contacts ")
765
        cursor.execute(query)
766
        rows_contacts = cursor.fetchall()
767
768
        contact_dict = dict()
769
        if rows_contacts is not None and len(rows_contacts) > 0:
770
            for row in rows_contacts:
771
                contact_dict[row[0]] = {"id": row[0],
772
                                        "name": row[1],
773
                                        "uuid": row[2]}
774
775
        query = (" SELECT id, name, uuid "
776
                 " FROM tbl_cost_centers ")
777
        cursor.execute(query)
778
        rows_cost_centers = cursor.fetchall()
779
780
        cost_center_dict = dict()
781
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
782
            for row in rows_cost_centers:
783
                cost_center_dict[row[0]] = {"id": row[0],
784
                                            "name": row[1],
785
                                            "uuid": row[2]}
786
        result = dict()
787
        result['current'] = dict()
788
        result['current']['id'] = row_current_space[0]
789
        result['current']['name'] = row_current_space[1]
790
        result['current']['uuid'] = row_current_space[2]
791
        result['current']['parent_space'] = space_dict.get(row_current_space[3], None)
792
        result['current']['area'] = row_current_space[4]
793
        result['current']['number_of_occupants'] = row_current_space[5]
794
        result['current']['timezone'] = timezone_dict.get(row_current_space[6], None)
795
        result['current']['is_input_counted'] = bool(row_current_space[7])
796
        result['current']['is_output_counted'] = bool(row_current_space[8])
797
        result['current']['contact'] = contact_dict.get(row_current_space[9], None)
798
        result['current']['cost_center'] = cost_center_dict.get(row_current_space[10], None)
799
        result['current']['latitude'] = row_current_space[11]
800
        result['current']['longitude'] = row_current_space[12]
801
        result['current']['description'] = row_current_space[13]
802
        result['current']['qrcode'] = 'space:' + row_current_space[2]
803
804
        result['children'] = list()
805
806
        query = (" SELECT id, name, uuid, "
807
                 "       parent_space_id, area, number_of_occupants, timezone_id, is_input_counted, is_output_counted, "
808
                 "        contact_id, cost_center_id, latitude, longitude, description "
809
                 " FROM tbl_spaces "
810
                 " WHERE parent_space_id = %s "
811
                 " ORDER BY id ")
812
        cursor.execute(query, (id_, ))
813
        rows_spaces = cursor.fetchall()
814
815 View Code Duplication
        if rows_spaces is not None and len(rows_spaces) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
816
            for row in rows_spaces:
817
                meta_result = {"id": row[0],
818
                               "name": row[1],
819
                               "uuid": row[2],
820
                               "parent_space": space_dict.get(row[3], None),
821
                               "area": row[4],
822
                               "number_of_occupants": row[5],
823
                               "timezone": timezone_dict.get(row[6], None),
824
                               "is_input_counted": bool(row[7]),
825
                               "is_output_counted": bool(row[8]),
826
                               "contact": contact_dict.get(row[9], None),
827
                               "cost_center": cost_center_dict.get(row[10], None),
828
                               "latitude": row[11],
829
                               "longitude": row[12],
830
                               "description": row[13],
831
                               "qrcode": 'space:' + row[2]}
832
                result['children'].append(meta_result)
833
834
        cursor.close()
835
        cnx.close()
836
        resp.text = json.dumps(result)
837
838
839 View Code Duplication
class SpaceCombinedEquipmentCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
840
    def __init__(self):
841
        """Initializes Class"""
842
        pass
843
844
    @staticmethod
845
    def on_options(req, resp, id_):
846
        resp.status = falcon.HTTP_200
847
848
    @staticmethod
849
    def on_get(req, resp, id_):
850
        if 'API-KEY' not in req.headers or \
851
                not isinstance(req.headers['API-KEY'], str) or \
852
                len(str.strip(req.headers['API-KEY'])) == 0:
853
            access_control(req)
854
        else:
855
            api_key_control(req)
856
        if not id_.isdigit() or int(id_) <= 0:
857
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
858
                                   description='API.INVALID_SPACE_ID')
859
860
        cnx = mysql.connector.connect(**config.myems_system_db)
861
        cursor = cnx.cursor()
862
863
        cursor.execute(" SELECT name "
864
                       " FROM tbl_spaces "
865
                       " WHERE id = %s ", (id_,))
866
        if cursor.fetchone() is None:
867
            cursor.close()
868
            cnx.close()
869
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
870
                                   description='API.SPACE_NOT_FOUND')
871
872
        query = (" SELECT e.id, e.name, e.uuid "
873
                 " FROM tbl_spaces s, tbl_spaces_combined_equipments se, tbl_combined_equipments e "
874
                 " WHERE se.space_id = s.id AND e.id = se.combined_equipment_id AND s.id = %s "
875
                 " ORDER BY e.id ")
876
        cursor.execute(query, (id_,))
877
        rows = cursor.fetchall()
878
879
        result = list()
880
        if rows is not None and len(rows) > 0:
881
            for row in rows:
882
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
883
                result.append(meta_result)
884
885
        resp.text = json.dumps(result)
886
887
    @staticmethod
888
    @user_logger
889
    def on_post(req, resp, id_):
890
        """Handles POST requests"""
891
        admin_control(req)
892
        try:
893
            raw_json = req.stream.read().decode('utf-8')
894
        except Exception as ex:
895
            raise falcon.HTTPError(status=falcon.HTTP_400,
896
                                   title='API.BAD_REQUEST',
897
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
898
899
        if not id_.isdigit() or int(id_) <= 0:
900
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
901
                                   description='API.INVALID_SPACE_ID')
902
903
        new_values = json.loads(raw_json)
904
905
        if 'combined_equipment_id' not in new_values['data'].keys() or \
906
                not isinstance(new_values['data']['combined_equipment_id'], int) or \
907
                new_values['data']['combined_equipment_id'] <= 0:
908
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
909
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
910
        combined_equipment_id = new_values['data']['combined_equipment_id']
911
912
        cnx = mysql.connector.connect(**config.myems_system_db)
913
        cursor = cnx.cursor()
914
915
        cursor.execute(" SELECT name "
916
                       " from tbl_spaces "
917
                       " WHERE id = %s ", (id_,))
918
        if cursor.fetchone() is None:
919
            cursor.close()
920
            cnx.close()
921
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
922
                                   description='API.SPACE_NOT_FOUND')
923
924
        cursor.execute(" SELECT name "
925
                       " FROM tbl_combined_equipments "
926
                       " WHERE id = %s ", (combined_equipment_id,))
927
        if cursor.fetchone() is None:
928
            cursor.close()
929
            cnx.close()
930
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
931
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
932
933
        query = (" SELECT id " 
934
                 " FROM tbl_spaces_combined_equipments "
935
                 " WHERE space_id = %s AND combined_equipment_id = %s")
936
        cursor.execute(query, (id_, combined_equipment_id,))
937
        if cursor.fetchone() is not None:
938
            cursor.close()
939
            cnx.close()
940
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
941
                                   description='API.SPACE_COMBINED_EQUIPMENT_RELATION_EXISTS')
942
943
        add_row = (" INSERT INTO tbl_spaces_combined_equipments (space_id, combined_equipment_id) "
944
                   " VALUES (%s, %s) ")
945
        cursor.execute(add_row, (id_, combined_equipment_id,))
946
        cnx.commit()
947
        cursor.close()
948
        cnx.close()
949
950
        resp.status = falcon.HTTP_201
951
        resp.location = '/spaces/' + str(id_) + '/combinedequipments/' + str(combined_equipment_id)
952
953
954 View Code Duplication
class SpaceCombinedEquipmentItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
955
    def __init__(self):
956
        """Initializes Class"""
957
        pass
958
959
    @staticmethod
960
    def on_options(req, resp, id_, eid):
961
        resp.status = falcon.HTTP_200
962
963
    @staticmethod
964
    @user_logger
965
    def on_delete(req, resp, id_, eid):
966
        admin_control(req)
967
        if not id_.isdigit() or int(id_) <= 0:
968
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
969
                                   description='API.INVALID_SPACE_ID')
970
971
        if not eid.isdigit() or int(eid) <= 0:
972
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
973
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
974
975
        cnx = mysql.connector.connect(**config.myems_system_db)
976
        cursor = cnx.cursor()
977
978
        cursor.execute(" SELECT name "
979
                       " FROM tbl_spaces "
980
                       " WHERE id = %s ", (id_,))
981
        if cursor.fetchone() is None:
982
            cursor.close()
983
            cnx.close()
984
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
985
                                   description='API.SPACE_NOT_FOUND')
986
987
        cursor.execute(" SELECT name "
988
                       " FROM tbl_combined_equipments "
989
                       " WHERE id = %s ", (eid,))
990
        if cursor.fetchone() is None:
991
            cursor.close()
992
            cnx.close()
993
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
994
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
995
996
        cursor.execute(" SELECT id "
997
                       " FROM tbl_spaces_combined_equipments "
998
                       " WHERE space_id = %s AND combined_equipment_id = %s ", (id_, eid))
999
        if cursor.fetchone() is None:
1000
            cursor.close()
1001
            cnx.close()
1002
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1003
                                   description='API.SPACE_COMBINED_EQUIPMENT_RELATION_NOT_FOUND')
1004
1005
        cursor.execute(" DELETE FROM tbl_spaces_combined_equipments "
1006
                       " WHERE space_id = %s AND combined_equipment_id = %s ", (id_, eid))
1007
        cnx.commit()
1008
1009
        cursor.close()
1010
        cnx.close()
1011
1012
        resp.status = falcon.HTTP_204
1013
1014
1015
class SpaceEnergyStoragePowerStationCollection:
1016
    def __init__(self):
1017
        """Initializes Class"""
1018
        pass
1019
1020
    @staticmethod
1021
    def on_options(req, resp, id_):
1022
        resp.status = falcon.HTTP_200
1023
1024
    @staticmethod
1025
    def on_get(req, resp, id_):
1026
        # NOTE: DO NOT allow to be called by api_key
1027
        access_control(req)
1028
1029
        if not id_.isdigit() or int(id_) <= 0:
1030
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1031
                                   description='API.INVALID_SPACE_ID')
1032
1033
        if 'USER-UUID' not in req.headers or \
1034
                not isinstance(req.headers['USER-UUID'], str) or \
1035
                len(str.strip(req.headers['USER-UUID'])) == 0:
1036
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1037
                                   description='API.INVALID_USER_UUID')
1038
        user_uuid = str.strip(req.headers['USER-UUID'])
1039
1040
        cnx_user = mysql.connector.connect(**config.myems_user_db)
1041
        cursor_user = cnx_user.cursor()
1042
        cursor_user.execute(" SELECT id FROM tbl_users WHERE uuid = %s ", (user_uuid,))
1043
        row_user = cursor_user.fetchone()
1044
        if row_user is None or len(row_user) != 1:
1045
            cursor_user.close()
1046
            cnx_user.close()
1047
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1048
                                   description='API.USER_NOT_FOUND')
1049
        else:
1050
            user_id = row_user[0]
1051
1052
        # get privilege
1053
        query = (" SELECT is_admin "
1054
                 " FROM tbl_users "
1055
                 " WHERE uuid = %s ")
1056
        cursor_user.execute(query, (user_uuid,))
1057
        row = cursor_user.fetchone()
1058
        if row is None:
1059
            cursor_user.close()
1060
            cnx_user.close()
1061
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.USER_NOT_FOUND')
1062
        else:
1063
            is_admin = bool(row[0])
1064
1065
        cnx = mysql.connector.connect(**config.myems_system_db)
1066
        cursor = cnx.cursor()
1067
1068
        cursor.execute(" SELECT name "
1069
                       " FROM tbl_spaces "
1070
                       " WHERE id = %s ", (id_,))
1071
        if cursor.fetchone() is None:
1072
            cursor.close()
1073
            cnx.close()
1074
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1075
                                   description='API.SPACE_NOT_FOUND')
1076
1077
        if is_admin:
1078
            query = (" SELECT e.id, e.name, e.uuid, e.phase_of_lifecycle "
1079
                     " FROM tbl_spaces s, tbl_spaces_energy_storage_power_stations se, "
1080
                     "      tbl_energy_storage_power_stations e "
1081
                     " WHERE se.space_id = s.id AND e.id = se.energy_storage_power_station_id AND s.id = %s "
1082
                     " ORDER BY e.phase_of_lifecycle, e.id ")
1083
            cursor.execute(query, (id_,))
1084
        else:
1085
            query = (" SELECT e.id, e.name, e.uuid, e.phase_of_lifecycle "
1086
                     " FROM tbl_spaces s, tbl_spaces_energy_storage_power_stations se, "
1087
                     "      tbl_energy_storage_power_stations e, tbl_energy_storage_power_stations_users su "
1088
                     " WHERE se.space_id = s.id AND e.id = se.energy_storage_power_station_id AND "
1089
                     "       e.id = su.energy_storage_power_station_id AND s.id = %s AND su.user_id = %s "
1090
                     " ORDER BY e.phase_of_lifecycle, e.id ")
1091
            cursor.execute(query, (id_, user_id))
1092
        rows = cursor.fetchall()
1093
1094
        result = list()
1095
        if rows is not None and len(rows) > 0:
1096
            for row in rows:
1097
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1098
                result.append(meta_result)
1099
1100
        resp.text = json.dumps(result)
1101
1102
    @staticmethod
1103
    @user_logger
1104
    def on_post(req, resp, id_):
1105
        """Handles POST requests"""
1106
        admin_control(req)
1107
        try:
1108
            raw_json = req.stream.read().decode('utf-8')
1109
        except Exception as ex:
1110
            raise falcon.HTTPError(status=falcon.HTTP_400,
1111
                                   title='API.BAD_REQUEST',
1112
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1113
1114
        if not id_.isdigit() or int(id_) <= 0:
1115
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1116
                                   description='API.INVALID_SPACE_ID')
1117
1118
        new_values = json.loads(raw_json)
1119
1120
        if 'energy_storage_power_station_id' not in new_values['data'].keys() or \
1121
                not isinstance(new_values['data']['energy_storage_power_station_id'], int) or \
1122
                new_values['data']['energy_storage_power_station_id'] <= 0:
1123
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1124
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
1125
        energy_storage_power_station_id = new_values['data']['energy_storage_power_station_id']
1126
1127
        cnx = mysql.connector.connect(**config.myems_system_db)
1128
        cursor = cnx.cursor()
1129
1130
        cursor.execute(" SELECT name "
1131
                       " from tbl_spaces "
1132
                       " WHERE id = %s ", (id_,))
1133
        if cursor.fetchone() is None:
1134
            cursor.close()
1135
            cnx.close()
1136
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1137
                                   description='API.SPACE_NOT_FOUND')
1138
1139
        cursor.execute(" SELECT name "
1140
                       " FROM tbl_energy_storage_power_stations "
1141
                       " WHERE id = %s ", (energy_storage_power_station_id,))
1142
        if cursor.fetchone() is None:
1143
            cursor.close()
1144
            cnx.close()
1145
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1146
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
1147
1148
        query = (" SELECT id " 
1149
                 " FROM tbl_spaces_energy_storage_power_stations "
1150
                 " WHERE space_id = %s AND energy_storage_power_station_id = %s")
1151
        cursor.execute(query, (id_, energy_storage_power_station_id,))
1152
        if cursor.fetchone() is not None:
1153
            cursor.close()
1154
            cnx.close()
1155
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1156
                                   description='API.SPACE_ENERGY_STORAGE_POWER_STATION_RELATION_EXISTS')
1157
1158
        add_row = (" INSERT INTO tbl_spaces_energy_storage_power_stations (space_id, energy_storage_power_station_id) "
1159
                   " VALUES (%s, %s) ")
1160
        cursor.execute(add_row, (id_, energy_storage_power_station_id,))
1161
        cnx.commit()
1162
        cursor.close()
1163
        cnx.close()
1164
1165
        resp.status = falcon.HTTP_201
1166
        resp.location = '/spaces/' + str(id_) + '/energystoragepowerstations/' + str(energy_storage_power_station_id)
1167
1168
1169 View Code Duplication
class SpaceEnergyStoragePowerStationItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1170
    def __init__(self):
1171
        """Initializes Class"""
1172
        pass
1173
1174
    @staticmethod
1175
    def on_options(req, resp, id_, eid):
1176
        resp.status = falcon.HTTP_200
1177
1178
    @staticmethod
1179
    @user_logger
1180
    def on_delete(req, resp, id_, eid):
1181
        admin_control(req)
1182
        if not id_.isdigit() or int(id_) <= 0:
1183
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1184
                                   description='API.INVALID_SPACE_ID')
1185
1186
        if not eid.isdigit() or int(eid) <= 0:
1187
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1188
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
1189
1190
        cnx = mysql.connector.connect(**config.myems_system_db)
1191
        cursor = cnx.cursor()
1192
1193
        cursor.execute(" SELECT name "
1194
                       " FROM tbl_spaces "
1195
                       " WHERE id = %s ", (id_,))
1196
        if cursor.fetchone() is None:
1197
            cursor.close()
1198
            cnx.close()
1199
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1200
                                   description='API.SPACE_NOT_FOUND')
1201
1202
        cursor.execute(" SELECT name "
1203
                       " FROM tbl_energy_storage_power_stations "
1204
                       " WHERE id = %s ", (eid,))
1205
        if cursor.fetchone() is None:
1206
            cursor.close()
1207
            cnx.close()
1208
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1209
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
1210
1211
        cursor.execute(" SELECT id "
1212
                       " FROM tbl_spaces_energy_storage_power_stations "
1213
                       " WHERE space_id = %s AND energy_storage_power_station_id = %s ", (id_, eid))
1214
        if cursor.fetchone() is None:
1215
            cursor.close()
1216
            cnx.close()
1217
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1218
                                   description='API.SPACE_ENERGY_STORAGE_POWER_STATION_RELATION_NOT_FOUND')
1219
1220
        cursor.execute(" DELETE FROM tbl_spaces_energy_storage_power_stations "
1221
                       " WHERE space_id = %s AND energy_storage_power_station_id = %s ", (id_, eid))
1222
        cnx.commit()
1223
1224
        cursor.close()
1225
        cnx.close()
1226
1227
        resp.status = falcon.HTTP_204
1228
1229
1230 View Code Duplication
class SpaceEquipmentCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1231
    def __init__(self):
1232
        """Initializes Class"""
1233
        pass
1234
1235
    @staticmethod
1236
    def on_options(req, resp, id_):
1237
        resp.status = falcon.HTTP_200
1238
1239
    @staticmethod
1240
    def on_get(req, resp, id_):
1241
        if 'API-KEY' not in req.headers or \
1242
                not isinstance(req.headers['API-KEY'], str) or \
1243
                len(str.strip(req.headers['API-KEY'])) == 0:
1244
            access_control(req)
1245
        else:
1246
            api_key_control(req)
1247
        if not id_.isdigit() or int(id_) <= 0:
1248
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1249
                                   description='API.INVALID_SPACE_ID')
1250
1251
        cnx = mysql.connector.connect(**config.myems_system_db)
1252
        cursor = cnx.cursor()
1253
1254
        cursor.execute(" SELECT name "
1255
                       " FROM tbl_spaces "
1256
                       " WHERE id = %s ", (id_,))
1257
        if cursor.fetchone() is None:
1258
            cursor.close()
1259
            cnx.close()
1260
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1261
                                   description='API.SPACE_NOT_FOUND')
1262
1263
        query = (" SELECT e.id, e.name, e.uuid "
1264
                 " FROM tbl_spaces s, tbl_spaces_equipments se, tbl_equipments e "
1265
                 " WHERE se.space_id = s.id AND e.id = se.equipment_id AND s.id = %s "
1266
                 " ORDER BY e.id ")
1267
        cursor.execute(query, (id_,))
1268
        rows = cursor.fetchall()
1269
1270
        result = list()
1271
        if rows is not None and len(rows) > 0:
1272
            for row in rows:
1273
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1274
                result.append(meta_result)
1275
1276
        resp.text = json.dumps(result)
1277
1278
    @staticmethod
1279
    @user_logger
1280
    def on_post(req, resp, id_):
1281
        """Handles POST requests"""
1282
        admin_control(req)
1283
        try:
1284
            raw_json = req.stream.read().decode('utf-8')
1285
        except Exception as ex:
1286
            raise falcon.HTTPError(status=falcon.HTTP_400,
1287
                                   title='API.BAD_REQUEST',
1288
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1289
1290
        if not id_.isdigit() or int(id_) <= 0:
1291
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1292
                                   description='API.INVALID_SPACE_ID')
1293
1294
        new_values = json.loads(raw_json)
1295
1296
        if 'equipment_id' not in new_values['data'].keys() or \
1297
                not isinstance(new_values['data']['equipment_id'], int) or \
1298
                new_values['data']['equipment_id'] <= 0:
1299
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1300
                                   description='API.INVALID_EQUIPMENT_ID')
1301
        equipment_id = new_values['data']['equipment_id']
1302
1303
        cnx = mysql.connector.connect(**config.myems_system_db)
1304
        cursor = cnx.cursor()
1305
1306
        cursor.execute(" SELECT name "
1307
                       " from tbl_spaces "
1308
                       " WHERE id = %s ", (id_,))
1309
        if cursor.fetchone() is None:
1310
            cursor.close()
1311
            cnx.close()
1312
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1313
                                   description='API.SPACE_NOT_FOUND')
1314
1315
        cursor.execute(" SELECT name "
1316
                       " FROM tbl_equipments "
1317
                       " WHERE id = %s ", (equipment_id,))
1318
        if cursor.fetchone() is None:
1319
            cursor.close()
1320
            cnx.close()
1321
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1322
                                   description='API.EQUIPMENT_NOT_FOUND')
1323
1324
        query = (" SELECT id " 
1325
                 " FROM tbl_spaces_equipments "
1326
                 " WHERE space_id = %s AND equipment_id = %s")
1327
        cursor.execute(query, (id_, equipment_id,))
1328
        if cursor.fetchone() is not None:
1329
            cursor.close()
1330
            cnx.close()
1331
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1332
                                   description='API.SPACE_EQUIPMENT_RELATION_EXISTS')
1333
1334
        add_row = (" INSERT INTO tbl_spaces_equipments (space_id, equipment_id) "
1335
                   " VALUES (%s, %s) ")
1336
        cursor.execute(add_row, (id_, equipment_id,))
1337
        cnx.commit()
1338
        cursor.close()
1339
        cnx.close()
1340
1341
        resp.status = falcon.HTTP_201
1342
        resp.location = '/spaces/' + str(id_) + '/equipments/' + str(equipment_id)
1343
1344
1345 View Code Duplication
class SpaceEquipmentItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1346
    def __init__(self):
1347
        """Initializes Class"""
1348
        pass
1349
1350
    @staticmethod
1351
    def on_options(req, resp, id_, eid):
1352
        resp.status = falcon.HTTP_200
1353
1354
    @staticmethod
1355
    @user_logger
1356
    def on_delete(req, resp, id_, eid):
1357
        admin_control(req)
1358
        if not id_.isdigit() or int(id_) <= 0:
1359
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1360
                                   description='API.INVALID_SPACE_ID')
1361
1362
        if not eid.isdigit() or int(eid) <= 0:
1363
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1364
                                   description='API.INVALID_EQUIPMENT_ID')
1365
1366
        cnx = mysql.connector.connect(**config.myems_system_db)
1367
        cursor = cnx.cursor()
1368
1369
        cursor.execute(" SELECT name "
1370
                       " FROM tbl_spaces "
1371
                       " WHERE id = %s ", (id_,))
1372
        if cursor.fetchone() is None:
1373
            cursor.close()
1374
            cnx.close()
1375
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1376
                                   description='API.SPACE_NOT_FOUND')
1377
1378
        cursor.execute(" SELECT name "
1379
                       " FROM tbl_equipments "
1380
                       " WHERE id = %s ", (eid,))
1381
        if cursor.fetchone() is None:
1382
            cursor.close()
1383
            cnx.close()
1384
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1385
                                   description='API.EQUIPMENT_NOT_FOUND')
1386
1387
        cursor.execute(" SELECT id "
1388
                       " FROM tbl_spaces_equipments "
1389
                       " WHERE space_id = %s AND equipment_id = %s ", (id_, eid))
1390
        if cursor.fetchone() is None:
1391
            cursor.close()
1392
            cnx.close()
1393
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1394
                                   description='API.SPACE_EQUIPMENT_RELATION_NOT_FOUND')
1395
1396
        cursor.execute(" DELETE FROM tbl_spaces_equipments WHERE space_id = %s AND equipment_id = %s ", (id_, eid))
1397
        cnx.commit()
1398
1399
        cursor.close()
1400
        cnx.close()
1401
1402
        resp.status = falcon.HTTP_204
1403
1404
1405 View Code Duplication
class SpaceHybridPowerStationCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1406
    def __init__(self):
1407
        """Initializes Class"""
1408
        pass
1409
1410
    @staticmethod
1411
    def on_options(req, resp, id_):
1412
        resp.status = falcon.HTTP_200
1413
1414
    @staticmethod
1415
    def on_get(req, resp, id_):
1416
        if 'API-KEY' not in req.headers or \
1417
                not isinstance(req.headers['API-KEY'], str) or \
1418
                len(str.strip(req.headers['API-KEY'])) == 0:
1419
            access_control(req)
1420
        else:
1421
            api_key_control(req)
1422
        if not id_.isdigit() or int(id_) <= 0:
1423
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1424
                                   description='API.INVALID_SPACE_ID')
1425
1426
        cnx = mysql.connector.connect(**config.myems_system_db)
1427
        cursor = cnx.cursor()
1428
1429
        cursor.execute(" SELECT name "
1430
                       " FROM tbl_spaces "
1431
                       " WHERE id = %s ", (id_,))
1432
        if cursor.fetchone() is None:
1433
            cursor.close()
1434
            cnx.close()
1435
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1436
                                   description='API.SPACE_NOT_FOUND')
1437
1438
        query = (" SELECT e.id, e.name, e.uuid, e.phase_of_lifecycle "
1439
                 " FROM tbl_spaces s, tbl_spaces_hybrid_power_stations se, tbl_hybrid_power_stations e "
1440
                 " WHERE se.space_id = s.id AND e.id = se.hybrid_power_station_id AND s.id = %s "
1441
                 " ORDER BY e.phase_of_lifecycle, e.id ")
1442
        cursor.execute(query, (id_,))
1443
        rows = cursor.fetchall()
1444
1445
        result = list()
1446
        if rows is not None and len(rows) > 0:
1447
            for row in rows:
1448
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1449
                result.append(meta_result)
1450
1451
        resp.text = json.dumps(result)
1452
1453
    @staticmethod
1454
    @user_logger
1455
    def on_post(req, resp, id_):
1456
        """Handles POST requests"""
1457
        admin_control(req)
1458
        try:
1459
            raw_json = req.stream.read().decode('utf-8')
1460
        except Exception as ex:
1461
            raise falcon.HTTPError(status=falcon.HTTP_400,
1462
                                   title='API.BAD_REQUEST',
1463
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1464
1465
        if not id_.isdigit() or int(id_) <= 0:
1466
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1467
                                   description='API.INVALID_SPACE_ID')
1468
1469
        new_values = json.loads(raw_json)
1470
1471
        if 'hybrid_power_station_id' not in new_values['data'].keys() or \
1472
                not isinstance(new_values['data']['hybrid_power_station_id'], int) or \
1473
                new_values['data']['hybrid_power_station_id'] <= 0:
1474
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1475
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
1476
        hybrid_power_station_id = new_values['data']['hybrid_power_station_id']
1477
1478
        cnx = mysql.connector.connect(**config.myems_system_db)
1479
        cursor = cnx.cursor()
1480
1481
        cursor.execute(" SELECT name "
1482
                       " from tbl_spaces "
1483
                       " WHERE id = %s ", (id_,))
1484
        if cursor.fetchone() is None:
1485
            cursor.close()
1486
            cnx.close()
1487
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1488
                                   description='API.SPACE_NOT_FOUND')
1489
1490
        cursor.execute(" SELECT name "
1491
                       " FROM tbl_hybrid_power_stations "
1492
                       " WHERE id = %s ", (hybrid_power_station_id,))
1493
        if cursor.fetchone() is None:
1494
            cursor.close()
1495
            cnx.close()
1496
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1497
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
1498
1499
        query = (" SELECT id " 
1500
                 " FROM tbl_spaces_hybrid_power_stations "
1501
                 " WHERE space_id = %s AND hybrid_power_station_id = %s")
1502
        cursor.execute(query, (id_, hybrid_power_station_id,))
1503
        if cursor.fetchone() is not None:
1504
            cursor.close()
1505
            cnx.close()
1506
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1507
                                   description='API.SPACE_HYBRID_POWER_STATION_RELATION_EXISTS')
1508
1509
        add_row = (" INSERT INTO tbl_spaces_hybrid_power_stations (space_id, hybrid_power_station_id) "
1510
                   " VALUES (%s, %s) ")
1511
        cursor.execute(add_row, (id_, hybrid_power_station_id,))
1512
        cnx.commit()
1513
        cursor.close()
1514
        cnx.close()
1515
1516
        resp.status = falcon.HTTP_201
1517
        resp.location = '/spaces/' + str(id_) + '/energystoragepowerstations/' + str(hybrid_power_station_id)
1518
1519
1520 View Code Duplication
class SpaceHybridPowerStationItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1521
    def __init__(self):
1522
        """Initializes Class"""
1523
        pass
1524
1525
    @staticmethod
1526
    def on_options(req, resp, id_, eid):
1527
        resp.status = falcon.HTTP_200
1528
1529
    @staticmethod
1530
    @user_logger
1531
    def on_delete(req, resp, id_, eid):
1532
        admin_control(req)
1533
        if not id_.isdigit() or int(id_) <= 0:
1534
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1535
                                   description='API.INVALID_SPACE_ID')
1536
1537
        if not eid.isdigit() or int(eid) <= 0:
1538
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1539
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
1540
1541
        cnx = mysql.connector.connect(**config.myems_system_db)
1542
        cursor = cnx.cursor()
1543
1544
        cursor.execute(" SELECT name "
1545
                       " FROM tbl_spaces "
1546
                       " WHERE id = %s ", (id_,))
1547
        if cursor.fetchone() is None:
1548
            cursor.close()
1549
            cnx.close()
1550
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1551
                                   description='API.SPACE_NOT_FOUND')
1552
1553
        cursor.execute(" SELECT name "
1554
                       " FROM tbl_hybrid_power_stations "
1555
                       " WHERE id = %s ", (eid,))
1556
        if cursor.fetchone() is None:
1557
            cursor.close()
1558
            cnx.close()
1559
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1560
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
1561
1562
        cursor.execute(" SELECT id "
1563
                       " FROM tbl_spaces_hybrid_power_stations "
1564
                       " WHERE space_id = %s AND hybrid_power_station_id = %s ", (id_, eid))
1565
        if cursor.fetchone() is None:
1566
            cursor.close()
1567
            cnx.close()
1568
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1569
                                   description='API.SPACE_HYBRID_POWER_STATION_RELATION_NOT_FOUND')
1570
1571
        cursor.execute(" DELETE FROM tbl_spaces_hybrid_power_stations "
1572
                       " WHERE space_id = %s AND hybrid_power_station_id = %s ", (id_, eid))
1573
        cnx.commit()
1574
1575
        cursor.close()
1576
        cnx.close()
1577
1578
        resp.status = falcon.HTTP_204
1579
1580
1581 View Code Duplication
class SpaceMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1582
    def __init__(self):
1583
        """Initializes Class"""
1584
        pass
1585
1586
    @staticmethod
1587
    def on_options(req, resp, id_):
1588
        resp.status = falcon.HTTP_200
1589
1590
    @staticmethod
1591
    def on_get(req, resp, id_):
1592
        if 'API-KEY' not in req.headers or \
1593
                not isinstance(req.headers['API-KEY'], str) or \
1594
                len(str.strip(req.headers['API-KEY'])) == 0:
1595
            access_control(req)
1596
        else:
1597
            api_key_control(req)
1598
        if not id_.isdigit() or int(id_) <= 0:
1599
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1600
                                   description='API.INVALID_SPACE_ID')
1601
1602
        cnx = mysql.connector.connect(**config.myems_system_db)
1603
        cursor = cnx.cursor()
1604
1605
        cursor.execute(" SELECT name "
1606
                       " FROM tbl_spaces "
1607
                       " WHERE id = %s ", (id_,))
1608
        if cursor.fetchone() is None:
1609
            cursor.close()
1610
            cnx.close()
1611
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1612
                                   description='API.SPACE_NOT_FOUND')
1613
1614
        query = (" SELECT id, name, uuid "
1615
                 " FROM tbl_energy_categories ")
1616
        cursor.execute(query)
1617
        rows_energy_categories = cursor.fetchall()
1618
1619
        energy_category_dict = dict()
1620
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1621
            for row in rows_energy_categories:
1622
                energy_category_dict[row[0]] = {"id": row[0],
1623
                                                "name": row[1],
1624
                                                "uuid": row[2]}
1625
1626
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1627
                 " FROM tbl_spaces s, tbl_spaces_meters sm, tbl_meters m "
1628
                 " WHERE sm.space_id = s.id AND m.id = sm.meter_id AND s.id = %s "
1629
                 " ORDER BY m.id ")
1630
        cursor.execute(query, (id_,))
1631
        rows = cursor.fetchall()
1632
1633
        result = list()
1634
        if rows is not None and len(rows) > 0:
1635
            for row in rows:
1636
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1637
                               "energy_category": energy_category_dict.get(row[3], None)}
1638
                result.append(meta_result)
1639
1640
        resp.text = json.dumps(result)
1641
1642
    @staticmethod
1643
    @user_logger
1644
    def on_post(req, resp, id_):
1645
        """Handles POST requests"""
1646
        admin_control(req)
1647
        try:
1648
            raw_json = req.stream.read().decode('utf-8')
1649
        except Exception as ex:
1650
            raise falcon.HTTPError(status=falcon.HTTP_400,
1651
                                   title='API.BAD_REQUEST',
1652
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1653
1654
        if not id_.isdigit() or int(id_) <= 0:
1655
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1656
                                   description='API.INVALID_SPACE_ID')
1657
1658
        new_values = json.loads(raw_json)
1659
1660
        if 'meter_id' not in new_values['data'].keys() or \
1661
                not isinstance(new_values['data']['meter_id'], int) or \
1662
                new_values['data']['meter_id'] <= 0:
1663
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1664
                                   description='API.INVALID_METER_ID')
1665
        meter_id = new_values['data']['meter_id']
1666
1667
        cnx = mysql.connector.connect(**config.myems_system_db)
1668
        cursor = cnx.cursor()
1669
1670
        cursor.execute(" SELECT name "
1671
                       " from tbl_spaces "
1672
                       " WHERE id = %s ", (id_,))
1673
        if cursor.fetchone() is None:
1674
            cursor.close()
1675
            cnx.close()
1676
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1677
                                   description='API.SPACE_NOT_FOUND')
1678
1679
        cursor.execute(" SELECT name "
1680
                       " FROM tbl_meters "
1681
                       " WHERE id = %s ", (meter_id,))
1682
        if cursor.fetchone() is None:
1683
            cursor.close()
1684
            cnx.close()
1685
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1686
                                   description='API.METER_NOT_FOUND')
1687
1688
        query = (" SELECT id " 
1689
                 " FROM tbl_spaces_meters "
1690
                 " WHERE space_id = %s AND meter_id = %s")
1691
        cursor.execute(query, (id_, meter_id,))
1692
        if cursor.fetchone() is not None:
1693
            cursor.close()
1694
            cnx.close()
1695
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1696
                                   description='API.SPACE_METER_RELATION_EXISTS')
1697
1698
        add_row = (" INSERT INTO tbl_spaces_meters (space_id, meter_id) "
1699
                   " VALUES (%s, %s) ")
1700
        cursor.execute(add_row, (id_, meter_id,))
1701
        cnx.commit()
1702
        cursor.close()
1703
        cnx.close()
1704
1705
        resp.status = falcon.HTTP_201
1706
        resp.location = '/spaces/' + str(id_) + '/meters/' + str(meter_id)
1707
1708
1709 View Code Duplication
class SpaceMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1710
    def __init__(self):
1711
        """Initializes Class"""
1712
        pass
1713
1714
    @staticmethod
1715
    def on_options(req, resp, id_, mid):
1716
        resp.status = falcon.HTTP_200
1717
1718
    @staticmethod
1719
    @user_logger
1720
    def on_delete(req, resp, id_, mid):
1721
        admin_control(req)
1722
        if not id_.isdigit() or int(id_) <= 0:
1723
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1724
                                   description='API.INVALID_SPACE_ID')
1725
1726
        if not mid.isdigit() or int(mid) <= 0:
1727
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1728
                                   description='API.INVALID_METER_ID')
1729
1730
        cnx = mysql.connector.connect(**config.myems_system_db)
1731
        cursor = cnx.cursor()
1732
1733
        cursor.execute(" SELECT name "
1734
                       " FROM tbl_spaces "
1735
                       " WHERE id = %s ", (id_,))
1736
        if cursor.fetchone() is None:
1737
            cursor.close()
1738
            cnx.close()
1739
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1740
                                   description='API.SPACE_NOT_FOUND')
1741
1742
        cursor.execute(" SELECT name "
1743
                       " FROM tbl_meters "
1744
                       " WHERE id = %s ", (mid,))
1745
        if cursor.fetchone() is None:
1746
            cursor.close()
1747
            cnx.close()
1748
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1749
                                   description='API.METER_NOT_FOUND')
1750
1751
        cursor.execute(" SELECT id "
1752
                       " FROM tbl_spaces_meters "
1753
                       " WHERE space_id = %s AND meter_id = %s ", (id_, mid))
1754
        # use fetchall to avoid 'Unread result found' error in case there are duplicate rows
1755
        rows = cursor.fetchall()
1756
        if rows is None or len(rows) == 0:
1757
            cursor.close()
1758
            cnx.close()
1759
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1760
                                   description='API.SPACE_METER_RELATION_NOT_FOUND')
1761
1762
        cursor.execute(" DELETE FROM tbl_spaces_meters WHERE space_id = %s AND meter_id = %s ", (id_, mid))
1763
        cnx.commit()
1764
1765
        cursor.close()
1766
        cnx.close()
1767
1768
        resp.status = falcon.HTTP_204
1769
1770
1771 View Code Duplication
class SpaceMicrogridCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1772
    def __init__(self):
1773
        """Initializes Class"""
1774
        pass
1775
1776
    @staticmethod
1777
    def on_options(req, resp, id_):
1778
        resp.status = falcon.HTTP_200
1779
1780
    @staticmethod
1781
    def on_get(req, resp, id_):
1782
        if 'API-KEY' not in req.headers or \
1783
                not isinstance(req.headers['API-KEY'], str) or \
1784
                len(str.strip(req.headers['API-KEY'])) == 0:
1785
            access_control(req)
1786
        else:
1787
            api_key_control(req)
1788
        if not id_.isdigit() or int(id_) <= 0:
1789
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1790
                                   description='API.INVALID_SPACE_ID')
1791
1792
        cnx = mysql.connector.connect(**config.myems_system_db)
1793
        cursor = cnx.cursor()
1794
1795
        cursor.execute(" SELECT name "
1796
                       " FROM tbl_spaces "
1797
                       " WHERE id = %s ", (id_,))
1798
        if cursor.fetchone() is None:
1799
            cursor.close()
1800
            cnx.close()
1801
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1802
                                   description='API.SPACE_NOT_FOUND')
1803
1804
        query = (" SELECT e.id, e.name, e.uuid, e.phase_of_lifecycle "
1805
                 " FROM tbl_spaces s, tbl_spaces_microgrids se, tbl_microgrids e "
1806
                 " WHERE se.space_id = s.id AND e.id = se.microgrid_id AND s.id = %s "
1807
                 " ORDER BY e.phase_of_lifecycle, e.id ")
1808
        cursor.execute(query, (id_,))
1809
        rows = cursor.fetchall()
1810
1811
        result = list()
1812
        if rows is not None and len(rows) > 0:
1813
            for row in rows:
1814
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1815
                result.append(meta_result)
1816
1817
        resp.text = json.dumps(result)
1818
1819
    @staticmethod
1820
    @user_logger
1821
    def on_post(req, resp, id_):
1822
        """Handles POST requests"""
1823
        admin_control(req)
1824
        try:
1825
            raw_json = req.stream.read().decode('utf-8')
1826
        except Exception as ex:
1827
            raise falcon.HTTPError(status=falcon.HTTP_400,
1828
                                   title='API.BAD_REQUEST',
1829
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1830
1831
        if not id_.isdigit() or int(id_) <= 0:
1832
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1833
                                   description='API.INVALID_SPACE_ID')
1834
1835
        new_values = json.loads(raw_json)
1836
1837
        if 'microgrid_id' not in new_values['data'].keys() or \
1838
                not isinstance(new_values['data']['microgrid_id'], int) or \
1839
                new_values['data']['microgrid_id'] <= 0:
1840
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1841
                                   description='API.INVALID_MICROGRID_ID')
1842
        microgrid_id = new_values['data']['microgrid_id']
1843
1844
        cnx = mysql.connector.connect(**config.myems_system_db)
1845
        cursor = cnx.cursor()
1846
1847
        cursor.execute(" SELECT name "
1848
                       " from tbl_spaces "
1849
                       " WHERE id = %s ", (id_,))
1850
        if cursor.fetchone() is None:
1851
            cursor.close()
1852
            cnx.close()
1853
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1854
                                   description='API.SPACE_NOT_FOUND')
1855
1856
        cursor.execute(" SELECT name "
1857
                       " FROM tbl_microgrids "
1858
                       " WHERE id = %s ", (microgrid_id,))
1859
        if cursor.fetchone() is None:
1860
            cursor.close()
1861
            cnx.close()
1862
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1863
                                   description='API.MICROGRID_NOT_FOUND')
1864
1865
        query = (" SELECT id " 
1866
                 " FROM tbl_spaces_microgrids "
1867
                 " WHERE space_id = %s AND microgrid_id = %s")
1868
        cursor.execute(query, (id_, microgrid_id,))
1869
        if cursor.fetchone() is not None:
1870
            cursor.close()
1871
            cnx.close()
1872
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1873
                                   description='API.SPACE_MICROGRID_RELATION_EXISTS')
1874
1875
        add_row = (" INSERT INTO tbl_spaces_microgrids (space_id, microgrid_id) "
1876
                   " VALUES (%s, %s) ")
1877
        cursor.execute(add_row, (id_, microgrid_id,))
1878
        cnx.commit()
1879
        cursor.close()
1880
        cnx.close()
1881
1882
        resp.status = falcon.HTTP_201
1883
        resp.location = '/spaces/' + str(id_) + '/microgrids/' + str(microgrid_id)
1884
1885
1886 View Code Duplication
class SpaceMicrogridItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1887
    def __init__(self):
1888
        """Initializes Class"""
1889
        pass
1890
1891
    @staticmethod
1892
    def on_options(req, resp, id_, mid):
1893
        resp.status = falcon.HTTP_200
1894
1895
    @staticmethod
1896
    @user_logger
1897
    def on_delete(req, resp, id_, mid):
1898
        admin_control(req)
1899
        if not id_.isdigit() or int(id_) <= 0:
1900
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1901
                                   description='API.INVALID_SPACE_ID')
1902
1903
        if not mid.isdigit() or int(mid) <= 0:
1904
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1905
                                   description='API.INVALID_MICROGRID_ID')
1906
1907
        cnx = mysql.connector.connect(**config.myems_system_db)
1908
        cursor = cnx.cursor()
1909
1910
        cursor.execute(" SELECT name "
1911
                       " FROM tbl_spaces "
1912
                       " WHERE id = %s ", (id_,))
1913
        if cursor.fetchone() is None:
1914
            cursor.close()
1915
            cnx.close()
1916
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1917
                                   description='API.SPACE_NOT_FOUND')
1918
1919
        cursor.execute(" SELECT name "
1920
                       " FROM tbl_microgrids "
1921
                       " WHERE id = %s ", (mid,))
1922
        if cursor.fetchone() is None:
1923
            cursor.close()
1924
            cnx.close()
1925
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1926
                                   description='API.MICROGRID_NOT_FOUND')
1927
1928
        cursor.execute(" SELECT id "
1929
                       " FROM tbl_spaces_microgrids "
1930
                       " WHERE space_id = %s AND microgrid_id = %s ", (id_, mid))
1931
        if cursor.fetchone() is None:
1932
            cursor.close()
1933
            cnx.close()
1934
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1935
                                   description='API.SPACE_MICROGRID_RELATION_NOT_FOUND')
1936
1937
        cursor.execute(" DELETE FROM tbl_spaces_microgrids "
1938
                       " WHERE space_id = %s AND microgrid_id = %s ", (id_, mid))
1939
        cnx.commit()
1940
1941
        cursor.close()
1942
        cnx.close()
1943
1944
        resp.status = falcon.HTTP_204
1945
1946
1947 View Code Duplication
class SpaceOfflineMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1948
    def __init__(self):
1949
        """Initializes Class"""
1950
        pass
1951
1952
    @staticmethod
1953
    def on_options(req, resp, id_):
1954
        resp.status = falcon.HTTP_200
1955
1956
    @staticmethod
1957
    def on_get(req, resp, id_):
1958
        if 'API-KEY' not in req.headers or \
1959
                not isinstance(req.headers['API-KEY'], str) or \
1960
                len(str.strip(req.headers['API-KEY'])) == 0:
1961
            access_control(req)
1962
        else:
1963
            api_key_control(req)
1964
        if not id_.isdigit() or int(id_) <= 0:
1965
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1966
                                   description='API.INVALID_SPACE_ID')
1967
1968
        cnx = mysql.connector.connect(**config.myems_system_db)
1969
        cursor = cnx.cursor()
1970
1971
        cursor.execute(" SELECT name "
1972
                       " FROM tbl_spaces "
1973
                       " WHERE id = %s ", (id_,))
1974
        if cursor.fetchone() is None:
1975
            cursor.close()
1976
            cnx.close()
1977
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1978
                                   description='API.SPACE_NOT_FOUND')
1979
1980
        query = (" SELECT id, name, uuid "
1981
                 " FROM tbl_energy_categories ")
1982
        cursor.execute(query)
1983
        rows_energy_categories = cursor.fetchall()
1984
1985
        energy_category_dict = dict()
1986
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1987
            for row in rows_energy_categories:
1988
                energy_category_dict[row[0]] = {"id": row[0],
1989
                                                "name": row[1],
1990
                                                "uuid": row[2]}
1991
1992
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1993
                 " FROM tbl_spaces s, tbl_spaces_offline_meters sm, tbl_offline_meters m "
1994
                 " WHERE sm.space_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
1995
                 " ORDER BY m.id ")
1996
        cursor.execute(query, (id_,))
1997
        rows = cursor.fetchall()
1998
1999
        result = list()
2000
        if rows is not None and len(rows) > 0:
2001
            for row in rows:
2002
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
2003
                               "energy_category": energy_category_dict.get(row[3], None)}
2004
                result.append(meta_result)
2005
2006
        resp.text = json.dumps(result)
2007
2008
    @staticmethod
2009
    @user_logger
2010
    def on_post(req, resp, id_):
2011
        """Handles POST requests"""
2012
        admin_control(req)
2013
        try:
2014
            raw_json = req.stream.read().decode('utf-8')
2015
        except Exception as ex:
2016
            raise falcon.HTTPError(status=falcon.HTTP_400,
2017
                                   title='API.BAD_REQUEST',
2018
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2019
2020
        if not id_.isdigit() or int(id_) <= 0:
2021
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2022
                                   description='API.INVALID_SPACE_ID')
2023
2024
        new_values = json.loads(raw_json)
2025
2026
        if 'offline_meter_id' not in new_values['data'].keys() or \
2027
                not isinstance(new_values['data']['offline_meter_id'], int) or \
2028
                new_values['data']['offline_meter_id'] <= 0:
2029
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2030
                                   description='API.INVALID_OFFLINE_METER_ID')
2031
        offline_meter_id = new_values['data']['offline_meter_id']
2032
2033
        cnx = mysql.connector.connect(**config.myems_system_db)
2034
        cursor = cnx.cursor()
2035
2036
        cursor.execute(" SELECT name "
2037
                       " from tbl_spaces "
2038
                       " WHERE id = %s ", (id_,))
2039
        if cursor.fetchone() is None:
2040
            cursor.close()
2041
            cnx.close()
2042
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2043
                                   description='API.SPACE_NOT_FOUND')
2044
2045
        cursor.execute(" SELECT name "
2046
                       " FROM tbl_offline_meters "
2047
                       " WHERE id = %s ", (offline_meter_id,))
2048
        if cursor.fetchone() is None:
2049
            cursor.close()
2050
            cnx.close()
2051
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2052
                                   description='API.OFFLINE_METER_NOT_FOUND')
2053
2054
        query = (" SELECT id " 
2055
                 " FROM tbl_spaces_offline_meters "
2056
                 " WHERE space_id = %s AND offline_meter_id = %s")
2057
        cursor.execute(query, (id_, offline_meter_id,))
2058
        if cursor.fetchone() is not None:
2059
            cursor.close()
2060
            cnx.close()
2061
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2062
                                   description='API.SPACE_OFFLINE_METER_RELATION_EXISTS')
2063
2064
        add_row = (" INSERT INTO tbl_spaces_offline_meters (space_id, offline_meter_id) "
2065
                   " VALUES (%s, %s) ")
2066
        cursor.execute(add_row, (id_, offline_meter_id,))
2067
        cnx.commit()
2068
        cursor.close()
2069
        cnx.close()
2070
2071
        resp.status = falcon.HTTP_201
2072
        resp.location = '/spaces/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
2073
2074
2075 View Code Duplication
class SpaceOfflineMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2076
    def __init__(self):
2077
        """Initializes Class"""
2078
        pass
2079
2080
    @staticmethod
2081
    def on_options(req, resp, id_, mid):
2082
        resp.status = falcon.HTTP_200
2083
2084
    @staticmethod
2085
    @user_logger
2086
    def on_delete(req, resp, id_, mid):
2087
        admin_control(req)
2088
        if not id_.isdigit() or int(id_) <= 0:
2089
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2090
                                   description='API.INVALID_SPACE_ID')
2091
2092
        if not mid.isdigit() or int(mid) <= 0:
2093
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2094
                                   description='API.INVALID_OFFLINE_METER_ID')
2095
2096
        cnx = mysql.connector.connect(**config.myems_system_db)
2097
        cursor = cnx.cursor()
2098
2099
        cursor.execute(" SELECT name "
2100
                       " FROM tbl_spaces "
2101
                       " WHERE id = %s ", (id_,))
2102
        if cursor.fetchone() is None:
2103
            cursor.close()
2104
            cnx.close()
2105
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2106
                                   description='API.SPACE_NOT_FOUND')
2107
2108
        cursor.execute(" SELECT name "
2109
                       " FROM tbl_offline_meters "
2110
                       " WHERE id = %s ", (mid,))
2111
        if cursor.fetchone() is None:
2112
            cursor.close()
2113
            cnx.close()
2114
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2115
                                   description='API.OFFLINE_METER_NOT_FOUND')
2116
2117
        cursor.execute(" SELECT id "
2118
                       " FROM tbl_spaces_offline_meters "
2119
                       " WHERE space_id = %s AND offline_meter_id = %s ", (id_, mid))
2120
        if cursor.fetchone() is None:
2121
            cursor.close()
2122
            cnx.close()
2123
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2124
                                   description='API.SPACE_OFFLINE_METER_RELATION_NOT_FOUND')
2125
2126
        cursor.execute(" DELETE FROM tbl_spaces_offline_meters "
2127
                       " WHERE space_id = %s AND offline_meter_id = %s ", (id_, mid))
2128
        cnx.commit()
2129
2130
        cursor.close()
2131
        cnx.close()
2132
2133
        resp.status = falcon.HTTP_204
2134
2135
2136 View Code Duplication
class SpacePhotovoltaicPowerStationCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2137
    def __init__(self):
2138
        """Initializes Class"""
2139
        pass
2140
2141
    @staticmethod
2142
    def on_options(req, resp, id_):
2143
        resp.status = falcon.HTTP_200
2144
2145
    @staticmethod
2146
    def on_get(req, resp, id_):
2147
        if 'API-KEY' not in req.headers or \
2148
                not isinstance(req.headers['API-KEY'], str) or \
2149
                len(str.strip(req.headers['API-KEY'])) == 0:
2150
            access_control(req)
2151
        else:
2152
            api_key_control(req)
2153
        if not id_.isdigit() or int(id_) <= 0:
2154
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2155
                                   description='API.INVALID_SPACE_ID')
2156
2157
        cnx = mysql.connector.connect(**config.myems_system_db)
2158
        cursor = cnx.cursor()
2159
2160
        cursor.execute(" SELECT name "
2161
                       " FROM tbl_spaces "
2162
                       " WHERE id = %s ", (id_,))
2163
        if cursor.fetchone() is None:
2164
            cursor.close()
2165
            cnx.close()
2166
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2167
                                   description='API.SPACE_NOT_FOUND')
2168
2169
        query = (" SELECT e.id, e.name, e.uuid, e.phase_of_lifecycle "
2170
                 " FROM tbl_spaces s, tbl_spaces_photovoltaic_power_stations se, tbl_photovoltaic_power_stations e "
2171
                 " WHERE se.space_id = s.id AND e.id = se.photovoltaic_power_station_id AND s.id = %s "
2172
                 " ORDER BY e.phase_of_lifecycle, e.id ")
2173
        cursor.execute(query, (id_,))
2174
        rows = cursor.fetchall()
2175
2176
        result = list()
2177
        if rows is not None and len(rows) > 0:
2178
            for row in rows:
2179
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2180
                result.append(meta_result)
2181
2182
        resp.text = json.dumps(result)
2183
2184
    @staticmethod
2185
    @user_logger
2186
    def on_post(req, resp, id_):
2187
        """Handles POST requests"""
2188
        admin_control(req)
2189
        try:
2190
            raw_json = req.stream.read().decode('utf-8')
2191
        except Exception as ex:
2192
            raise falcon.HTTPError(status=falcon.HTTP_400,
2193
                                   title='API.BAD_REQUEST',
2194
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2195
2196
        if not id_.isdigit() or int(id_) <= 0:
2197
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2198
                                   description='API.INVALID_SPACE_ID')
2199
2200
        new_values = json.loads(raw_json)
2201
2202
        if 'photovoltaic_power_station_id' not in new_values['data'].keys() or \
2203
                not isinstance(new_values['data']['photovoltaic_power_station_id'], int) or \
2204
                new_values['data']['photovoltaic_power_station_id'] <= 0:
2205
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2206
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
2207
        photovoltaic_power_station_id = new_values['data']['photovoltaic_power_station_id']
2208
2209
        cnx = mysql.connector.connect(**config.myems_system_db)
2210
        cursor = cnx.cursor()
2211
2212
        cursor.execute(" SELECT name "
2213
                       " from tbl_spaces "
2214
                       " WHERE id = %s ", (id_,))
2215
        if cursor.fetchone() is None:
2216
            cursor.close()
2217
            cnx.close()
2218
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2219
                                   description='API.SPACE_NOT_FOUND')
2220
2221
        cursor.execute(" SELECT name "
2222
                       " FROM tbl_photovoltaic_power_stations "
2223
                       " WHERE id = %s ", (photovoltaic_power_station_id,))
2224
        if cursor.fetchone() is None:
2225
            cursor.close()
2226
            cnx.close()
2227
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2228
                                   description='API.PHOTOVOLTAIC_POWER_STATION_NOT_FOUND')
2229
2230
        query = (" SELECT id " 
2231
                 " FROM tbl_spaces_photovoltaic_power_stations "
2232
                 " WHERE space_id = %s AND photovoltaic_power_station_id = %s")
2233
        cursor.execute(query, (id_, photovoltaic_power_station_id,))
2234
        if cursor.fetchone() is not None:
2235
            cursor.close()
2236
            cnx.close()
2237
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2238
                                   description='API.SPACE_PHOTOVOLTAIC_POWER_STATION_RELATION_EXISTS')
2239
2240
        add_row = (" INSERT INTO tbl_spaces_photovoltaic_power_stations (space_id, photovoltaic_power_station_id) "
2241
                   " VALUES (%s, %s) ")
2242
        cursor.execute(add_row, (id_, photovoltaic_power_station_id,))
2243
        cnx.commit()
2244
        cursor.close()
2245
        cnx.close()
2246
2247
        resp.status = falcon.HTTP_201
2248
        resp.location = '/spaces/' + str(id_) + '/photovoltaicpowerstations/' + str(photovoltaic_power_station_id)
2249
2250
2251 View Code Duplication
class SpacePhotovoltaicPowerStationItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2252
    def __init__(self):
2253
        """Initializes Class"""
2254
        pass
2255
2256
    @staticmethod
2257
    def on_options(req, resp, id_, eid):
2258
        resp.status = falcon.HTTP_200
2259
2260
    @staticmethod
2261
    @user_logger
2262
    def on_delete(req, resp, id_, eid):
2263
        admin_control(req)
2264
        if not id_.isdigit() or int(id_) <= 0:
2265
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2266
                                   description='API.INVALID_SPACE_ID')
2267
2268
        if not eid.isdigit() or int(eid) <= 0:
2269
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2270
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
2271
2272
        cnx = mysql.connector.connect(**config.myems_system_db)
2273
        cursor = cnx.cursor()
2274
2275
        cursor.execute(" SELECT name "
2276
                       " FROM tbl_spaces "
2277
                       " WHERE id = %s ", (id_,))
2278
        if cursor.fetchone() is None:
2279
            cursor.close()
2280
            cnx.close()
2281
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2282
                                   description='API.SPACE_NOT_FOUND')
2283
2284
        cursor.execute(" SELECT name "
2285
                       " FROM tbl_photovoltaic_power_stations "
2286
                       " WHERE id = %s ", (eid,))
2287
        if cursor.fetchone() is None:
2288
            cursor.close()
2289
            cnx.close()
2290
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2291
                                   description='API.PHOTOVOLTAIC_POWER_STATION_NOT_FOUND')
2292
2293
        cursor.execute(" SELECT id "
2294
                       " FROM tbl_spaces_photovoltaic_power_stations "
2295
                       " WHERE space_id = %s AND photovoltaic_power_station_id = %s ", (id_, eid))
2296
        if cursor.fetchone() is None:
2297
            cursor.close()
2298
            cnx.close()
2299
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2300
                                   description='API.SPACE_PHOTOVOLTAIC_POWER_STATION_RELATION_NOT_FOUND')
2301
2302
        cursor.execute(" DELETE FROM tbl_spaces_photovoltaic_power_stations "
2303
                       " WHERE space_id = %s AND photovoltaic_power_station_id = %s ", (id_, eid))
2304
        cnx.commit()
2305
2306
        cursor.close()
2307
        cnx.close()
2308
2309
        resp.status = falcon.HTTP_204
2310
2311
2312 View Code Duplication
class SpacePointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2313
    def __init__(self):
2314
        """Initializes Class"""
2315
        pass
2316
2317
    @staticmethod
2318
    def on_options(req, resp, id_):
2319
        resp.status = falcon.HTTP_200
2320
2321
    @staticmethod
2322
    def on_get(req, resp, id_):
2323
        if 'API-KEY' not in req.headers or \
2324
                not isinstance(req.headers['API-KEY'], str) or \
2325
                len(str.strip(req.headers['API-KEY'])) == 0:
2326
            access_control(req)
2327
        else:
2328
            api_key_control(req)
2329
        if not id_.isdigit() or int(id_) <= 0:
2330
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2331
                                   description='API.INVALID_SPACE_ID')
2332
2333
        cnx = mysql.connector.connect(**config.myems_system_db)
2334
        cursor = cnx.cursor()
2335
2336
        cursor.execute(" SELECT name "
2337
                       " FROM tbl_spaces "
2338
                       " WHERE id = %s ", (id_,))
2339
        if cursor.fetchone() is None:
2340
            cursor.close()
2341
            cnx.close()
2342
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2343
                                   description='API.SPACE_NOT_FOUND')
2344
2345
        query = (" SELECT id, name, uuid "
2346
                 " FROM tbl_data_sources ")
2347
        cursor.execute(query)
2348
        rows_data_sources = cursor.fetchall()
2349
2350
        data_source_dict = dict()
2351
        if rows_data_sources is not None and len(rows_data_sources) > 0:
2352
            for row in rows_data_sources:
2353
                data_source_dict[row[0]] = {"id": row[0],
2354
                                            "name": row[1],
2355
                                            "uuid": row[2]}
2356
2357
        query = (" SELECT p.id, p.name, p.data_source_id "
2358
                 " FROM tbl_spaces s, tbl_spaces_points sp, tbl_points p "
2359
                 " WHERE sp.space_id = s.id AND p.id = sp.point_id AND s.id = %s "
2360
                 " ORDER BY p.id ")
2361
        cursor.execute(query, (id_,))
2362
        rows = cursor.fetchall()
2363
2364
        result = list()
2365
        if rows is not None and len(rows) > 0:
2366
            for row in rows:
2367
                meta_result = {"id": row[0], "name": row[1], "data_source": data_source_dict.get(row[2], None)}
2368
                result.append(meta_result)
2369
2370
        resp.text = json.dumps(result)
2371
2372
    @staticmethod
2373
    @user_logger
2374
    def on_post(req, resp, id_):
2375
        """Handles POST requests"""
2376
        admin_control(req)
2377
        try:
2378
            raw_json = req.stream.read().decode('utf-8')
2379
        except Exception as ex:
2380
            raise falcon.HTTPError(status=falcon.HTTP_400,
2381
                                   title='API.BAD_REQUEST',
2382
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2383
2384
        if not id_.isdigit() or int(id_) <= 0:
2385
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2386
                                   description='API.INVALID_SPACE_ID')
2387
2388
        new_values = json.loads(raw_json)
2389
2390
        if 'point_id' not in new_values['data'].keys() or \
2391
                not isinstance(new_values['data']['point_id'], int) or \
2392
                new_values['data']['point_id'] <= 0:
2393
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2394
                                   description='API.INVALID_POINT_ID')
2395
        point_id = new_values['data']['point_id']
2396
2397
        cnx = mysql.connector.connect(**config.myems_system_db)
2398
        cursor = cnx.cursor()
2399
2400
        cursor.execute(" SELECT name "
2401
                       " from tbl_spaces "
2402
                       " WHERE id = %s ", (id_,))
2403
        if cursor.fetchone() is None:
2404
            cursor.close()
2405
            cnx.close()
2406
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2407
                                   description='API.SPACE_NOT_FOUND')
2408
2409
        cursor.execute(" SELECT name "
2410
                       " FROM tbl_points "
2411
                       " WHERE id = %s ", (point_id,))
2412
        if cursor.fetchone() is None:
2413
            cursor.close()
2414
            cnx.close()
2415
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2416
                                   description='API.POINT_NOT_FOUND')
2417
2418
        query = (" SELECT id " 
2419
                 " FROM tbl_spaces_points "
2420
                 " WHERE space_id = %s AND point_id = %s")
2421
        cursor.execute(query, (id_, point_id,))
2422
        if cursor.fetchone() is not None:
2423
            cursor.close()
2424
            cnx.close()
2425
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2426
                                   description='API.SPACE_POINT_RELATION_EXISTS')
2427
2428
        add_row = (" INSERT INTO tbl_spaces_points (space_id, point_id) "
2429
                   " VALUES (%s, %s) ")
2430
        cursor.execute(add_row, (id_, point_id,))
2431
        cnx.commit()
2432
        cursor.close()
2433
        cnx.close()
2434
2435
        resp.status = falcon.HTTP_201
2436
        resp.location = '/spaces/' + str(id_) + '/points/' + str(point_id)
2437
2438
2439 View Code Duplication
class SpacePointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2440
    def __init__(self):
2441
        """Initializes Class"""
2442
        pass
2443
2444
    @staticmethod
2445
    def on_options(req, resp, id_, pid):
2446
        resp.status = falcon.HTTP_200
2447
2448
    @staticmethod
2449
    @user_logger
2450
    def on_delete(req, resp, id_, pid):
2451
        admin_control(req)
2452
        if not id_.isdigit() or int(id_) <= 0:
2453
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2454
                                   description='API.INVALID_SPACE_ID')
2455
2456
        if not pid.isdigit() or int(pid) <= 0:
2457
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2458
                                   description='API.INVALID_POINT_ID')
2459
2460
        cnx = mysql.connector.connect(**config.myems_system_db)
2461
        cursor = cnx.cursor()
2462
2463
        cursor.execute(" SELECT name "
2464
                       " FROM tbl_spaces "
2465
                       " WHERE id = %s ", (id_,))
2466
        if cursor.fetchone() is None:
2467
            cursor.close()
2468
            cnx.close()
2469
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2470
                                   description='API.SPACE_NOT_FOUND')
2471
2472
        cursor.execute(" SELECT name "
2473
                       " FROM tbl_points "
2474
                       " WHERE id = %s ", (pid,))
2475
        if cursor.fetchone() is None:
2476
            cursor.close()
2477
            cnx.close()
2478
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2479
                                   description='API.POINT_NOT_FOUND')
2480
2481
        cursor.execute(" SELECT id "
2482
                       " FROM tbl_spaces_points "
2483
                       " WHERE space_id = %s AND point_id = %s ", (id_, pid))
2484
        if cursor.fetchone() is None:
2485
            cursor.close()
2486
            cnx.close()
2487
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2488
                                   description='API.SPACE_POINT_RELATION_NOT_FOUND')
2489
2490
        cursor.execute(" DELETE FROM tbl_spaces_points "
2491
                       " WHERE space_id = %s AND point_id = %s ", (id_, pid))
2492
        cnx.commit()
2493
2494
        cursor.close()
2495
        cnx.close()
2496
2497
        resp.status = falcon.HTTP_204
2498
2499
2500 View Code Duplication
class SpaceSensorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2501
    def __init__(self):
2502
        """Initializes Class"""
2503
        pass
2504
2505
    @staticmethod
2506
    def on_options(req, resp, id_):
2507
        resp.status = falcon.HTTP_200
2508
2509
    @staticmethod
2510
    def on_get(req, resp, id_):
2511
        if 'API-KEY' not in req.headers or \
2512
                not isinstance(req.headers['API-KEY'], str) or \
2513
                len(str.strip(req.headers['API-KEY'])) == 0:
2514
            access_control(req)
2515
        else:
2516
            api_key_control(req)
2517
        if not id_.isdigit() or int(id_) <= 0:
2518
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2519
                                   description='API.INVALID_SPACE_ID')
2520
2521
        cnx = mysql.connector.connect(**config.myems_system_db)
2522
        cursor = cnx.cursor()
2523
2524
        cursor.execute(" SELECT name "
2525
                       " FROM tbl_spaces "
2526
                       " WHERE id = %s ", (id_,))
2527
        if cursor.fetchone() is None:
2528
            cursor.close()
2529
            cnx.close()
2530
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2531
                                   description='API.SPACE_NOT_FOUND')
2532
2533
        query = (" SELECT se.id, se.name, se.uuid "
2534
                 " FROM tbl_spaces sp, tbl_spaces_sensors ss, tbl_sensors se "
2535
                 " WHERE ss.space_id = sp.id AND se.id = ss.sensor_id AND sp.id = %s "
2536
                 " ORDER BY se.id ")
2537
        cursor.execute(query, (id_,))
2538
        rows = cursor.fetchall()
2539
2540
        result = list()
2541
        if rows is not None and len(rows) > 0:
2542
            for row in rows:
2543
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2544
                result.append(meta_result)
2545
2546
        resp.text = json.dumps(result)
2547
2548
    @staticmethod
2549
    @user_logger
2550
    def on_post(req, resp, id_):
2551
        """Handles POST requests"""
2552
        admin_control(req)
2553
        try:
2554
            raw_json = req.stream.read().decode('utf-8')
2555
        except Exception as ex:
2556
            raise falcon.HTTPError(status=falcon.HTTP_400,
2557
                                   title='API.BAD_REQUEST',
2558
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2559
2560
        if not id_.isdigit() or int(id_) <= 0:
2561
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2562
                                   description='API.INVALID_SPACE_ID')
2563
2564
        new_values = json.loads(raw_json)
2565
2566
        if 'sensor_id' not in new_values['data'].keys() or \
2567
                not isinstance(new_values['data']['sensor_id'], int) or \
2568
                new_values['data']['sensor_id'] <= 0:
2569
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2570
                                   description='API.INVALID_SENSOR_ID')
2571
        sensor_id = new_values['data']['sensor_id']
2572
2573
        cnx = mysql.connector.connect(**config.myems_system_db)
2574
        cursor = cnx.cursor()
2575
2576
        cursor.execute(" SELECT name "
2577
                       " from tbl_spaces "
2578
                       " WHERE id = %s ", (id_,))
2579
        if cursor.fetchone() is None:
2580
            cursor.close()
2581
            cnx.close()
2582
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2583
                                   description='API.SPACE_NOT_FOUND')
2584
2585
        cursor.execute(" SELECT name "
2586
                       " FROM tbl_sensors "
2587
                       " WHERE id = %s ", (sensor_id,))
2588
        if cursor.fetchone() is None:
2589
            cursor.close()
2590
            cnx.close()
2591
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2592
                                   description='API.SENSOR_NOT_FOUND')
2593
2594
        query = (" SELECT id " 
2595
                 " FROM tbl_spaces_sensors "
2596
                 " WHERE space_id = %s AND sensor_id = %s")
2597
        cursor.execute(query, (id_, sensor_id,))
2598
        if cursor.fetchone() is not None:
2599
            cursor.close()
2600
            cnx.close()
2601
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2602
                                   description='API.SPACE_SENSOR_RELATION_EXISTS')
2603
2604
        add_row = (" INSERT INTO tbl_spaces_sensors (space_id, sensor_id) "
2605
                   " VALUES (%s, %s) ")
2606
        cursor.execute(add_row, (id_, sensor_id,))
2607
        cnx.commit()
2608
        cursor.close()
2609
        cnx.close()
2610
2611
        resp.status = falcon.HTTP_201
2612
        resp.location = '/spaces/' + str(id_) + '/sensors/' + str(sensor_id)
2613
2614
2615 View Code Duplication
class SpaceSensorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2616
    def __init__(self):
2617
        """Initializes Class"""
2618
        pass
2619
2620
    @staticmethod
2621
    def on_options(req, resp, id_, sid):
2622
        resp.status = falcon.HTTP_200
2623
2624
    @staticmethod
2625
    @user_logger
2626
    def on_delete(req, resp, id_, sid):
2627
        admin_control(req)
2628
        if not id_.isdigit() or int(id_) <= 0:
2629
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2630
                                   description='API.INVALID_SPACE_ID')
2631
2632
        if not sid.isdigit() or int(sid) <= 0:
2633
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2634
                                   description='API.INVALID_SENSOR_ID')
2635
2636
        cnx = mysql.connector.connect(**config.myems_system_db)
2637
        cursor = cnx.cursor()
2638
2639
        cursor.execute(" SELECT name "
2640
                       " FROM tbl_spaces "
2641
                       " WHERE id = %s ", (id_,))
2642
        if cursor.fetchone() is None:
2643
            cursor.close()
2644
            cnx.close()
2645
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2646
                                   description='API.SPACE_NOT_FOUND')
2647
2648
        cursor.execute(" SELECT name "
2649
                       " FROM tbl_sensors "
2650
                       " WHERE id = %s ", (sid,))
2651
        if cursor.fetchone() is None:
2652
            cursor.close()
2653
            cnx.close()
2654
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2655
                                   description='API.SENSOR_NOT_FOUND')
2656
2657
        cursor.execute(" SELECT id "
2658
                       " FROM tbl_spaces_sensors "
2659
                       " WHERE space_id = %s AND sensor_id = %s ", (id_, sid))
2660
        if cursor.fetchone() is None:
2661
            cursor.close()
2662
            cnx.close()
2663
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2664
                                   description='API.SPACE_SENSOR_RELATION_NOT_FOUND')
2665
2666
        cursor.execute(" DELETE FROM tbl_spaces_sensors WHERE space_id = %s AND sensor_id = %s ", (id_, sid))
2667
        cnx.commit()
2668
2669
        cursor.close()
2670
        cnx.close()
2671
2672
        resp.status = falcon.HTTP_204
2673
2674
2675 View Code Duplication
class SpaceShopfloorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2676
    def __init__(self):
2677
        """Initializes Class"""
2678
        pass
2679
2680
    @staticmethod
2681
    def on_options(req, resp, id_):
2682
        resp.status = falcon.HTTP_200
2683
2684
    @staticmethod
2685
    def on_get(req, resp, id_):
2686
        if 'API-KEY' not in req.headers or \
2687
                not isinstance(req.headers['API-KEY'], str) or \
2688
                len(str.strip(req.headers['API-KEY'])) == 0:
2689
            access_control(req)
2690
        else:
2691
            api_key_control(req)
2692
        if not id_.isdigit() or int(id_) <= 0:
2693
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2694
                                   description='API.INVALID_SPACE_ID')
2695
2696
        cnx = mysql.connector.connect(**config.myems_system_db)
2697
        cursor = cnx.cursor()
2698
2699
        cursor.execute(" SELECT name "
2700
                       " FROM tbl_spaces "
2701
                       " WHERE id = %s ", (id_,))
2702
        if cursor.fetchone() is None:
2703
            cursor.close()
2704
            cnx.close()
2705
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2706
                                   description='API.SPACE_NOT_FOUND')
2707
2708
        query = (" SELECT sf.id, sf.name, sf.uuid "
2709
                 " FROM tbl_spaces sp, tbl_spaces_shopfloors ss, tbl_shopfloors sf "
2710
                 " WHERE ss.space_id = sp.id AND sf.id = ss.shopfloor_id AND sp.id = %s "
2711
                 " ORDER BY sf.id ")
2712
        cursor.execute(query, (id_,))
2713
        rows = cursor.fetchall()
2714
2715
        result = list()
2716
        if rows is not None and len(rows) > 0:
2717
            for row in rows:
2718
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2719
                result.append(meta_result)
2720
2721
        resp.text = json.dumps(result)
2722
2723
    @staticmethod
2724
    @user_logger
2725
    def on_post(req, resp, id_):
2726
        """Handles POST requests"""
2727
        admin_control(req)
2728
        try:
2729
            raw_json = req.stream.read().decode('utf-8')
2730
        except Exception as ex:
2731
            raise falcon.HTTPError(status=falcon.HTTP_400,
2732
                                   title='API.BAD_REQUEST',
2733
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2734
2735
        if not id_.isdigit() or int(id_) <= 0:
2736
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2737
                                   description='API.INVALID_SPACE_ID')
2738
2739
        new_values = json.loads(raw_json)
2740
2741
        if 'shopfloor_id' not in new_values['data'].keys() or \
2742
                not isinstance(new_values['data']['shopfloor_id'], int) or \
2743
                new_values['data']['shopfloor_id'] <= 0:
2744
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2745
                                   description='API.INVALID_SHOPFLOOR_ID')
2746
        shopfloor_id = new_values['data']['shopfloor_id']
2747
2748
        cnx = mysql.connector.connect(**config.myems_system_db)
2749
        cursor = cnx.cursor()
2750
2751
        cursor.execute(" SELECT name "
2752
                       " from tbl_spaces "
2753
                       " WHERE id = %s ", (id_,))
2754
        if cursor.fetchone() is None:
2755
            cursor.close()
2756
            cnx.close()
2757
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2758
                                   description='API.SPACE_NOT_FOUND')
2759
2760
        cursor.execute(" SELECT name "
2761
                       " FROM tbl_shopfloors "
2762
                       " WHERE id = %s ", (shopfloor_id,))
2763
        if cursor.fetchone() is None:
2764
            cursor.close()
2765
            cnx.close()
2766
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2767
                                   description='API.SHOPFLOOR_NOT_FOUND')
2768
2769
        query = (" SELECT id " 
2770
                 " FROM tbl_spaces_shopfloors "
2771
                 " WHERE space_id = %s AND shopfloor_id = %s")
2772
        cursor.execute(query, (id_, shopfloor_id,))
2773
        if cursor.fetchone() is not None:
2774
            cursor.close()
2775
            cnx.close()
2776
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2777
                                   description='API.SPACE_SHOPFLOOR_RELATION_EXISTS')
2778
2779
        add_row = (" INSERT INTO tbl_spaces_shopfloors (space_id, shopfloor_id) "
2780
                   " VALUES (%s, %s) ")
2781
        cursor.execute(add_row, (id_, shopfloor_id,))
2782
        cnx.commit()
2783
        cursor.close()
2784
        cnx.close()
2785
2786
        resp.status = falcon.HTTP_201
2787
        resp.location = '/spaces/' + str(id_) + '/shopfloors/' + str(shopfloor_id)
2788
2789
2790 View Code Duplication
class SpaceShopfloorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2791
    def __init__(self):
2792
        """Initializes Class"""
2793
        pass
2794
2795
    @staticmethod
2796
    def on_options(req, resp, id_, sid):
2797
        resp.status = falcon.HTTP_200
2798
2799
    @staticmethod
2800
    @user_logger
2801
    def on_delete(req, resp, id_, sid):
2802
        admin_control(req)
2803
        if not id_.isdigit() or int(id_) <= 0:
2804
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2805
                                   description='API.INVALID_SPACE_ID')
2806
2807
        if not sid.isdigit() or int(sid) <= 0:
2808
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2809
                                   description='API.INVALID_SHOPFLOOR_ID')
2810
2811
        cnx = mysql.connector.connect(**config.myems_system_db)
2812
        cursor = cnx.cursor()
2813
2814
        cursor.execute(" SELECT name "
2815
                       " FROM tbl_spaces "
2816
                       " WHERE id = %s ", (id_,))
2817
        if cursor.fetchone() is None:
2818
            cursor.close()
2819
            cnx.close()
2820
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2821
                                   description='API.SPACE_NOT_FOUND')
2822
2823
        cursor.execute(" SELECT name "
2824
                       " FROM tbl_shopfloors "
2825
                       " WHERE id = %s ", (sid,))
2826
        if cursor.fetchone() is None:
2827
            cursor.close()
2828
            cnx.close()
2829
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2830
                                   description='API.SHOPFLOOR_NOT_FOUND')
2831
2832
        cursor.execute(" SELECT id "
2833
                       " FROM tbl_spaces_shopfloors "
2834
                       " WHERE space_id = %s AND shopfloor_id = %s ", (id_, sid))
2835
        if cursor.fetchone() is None:
2836
            cursor.close()
2837
            cnx.close()
2838
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2839
                                   description='API.SPACE_SHOPFLOOR_RELATION_NOT_FOUND')
2840
2841
        cursor.execute(" DELETE FROM tbl_spaces_shopfloors WHERE space_id = %s AND shopfloor_id = %s ", (id_, sid))
2842
        cnx.commit()
2843
2844
        cursor.close()
2845
        cnx.close()
2846
2847
        resp.status = falcon.HTTP_204
2848
2849
2850 View Code Duplication
class SpaceStoreCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2851
    def __init__(self):
2852
        """Initializes Class"""
2853
        pass
2854
2855
    @staticmethod
2856
    def on_options(req, resp, id_):
2857
        resp.status = falcon.HTTP_200
2858
2859
    @staticmethod
2860
    def on_get(req, resp, id_):
2861
        if 'API-KEY' not in req.headers or \
2862
                not isinstance(req.headers['API-KEY'], str) or \
2863
                len(str.strip(req.headers['API-KEY'])) == 0:
2864
            access_control(req)
2865
        else:
2866
            api_key_control(req)
2867
        if not id_.isdigit() or int(id_) <= 0:
2868
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2869
                                   description='API.INVALID_SPACE_ID')
2870
2871
        cnx = mysql.connector.connect(**config.myems_system_db)
2872
        cursor = cnx.cursor()
2873
2874
        cursor.execute(" SELECT name "
2875
                       " FROM tbl_spaces "
2876
                       " WHERE id = %s ", (id_,))
2877
        if cursor.fetchone() is None:
2878
            cursor.close()
2879
            cnx.close()
2880
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2881
                                   description='API.SPACE_NOT_FOUND')
2882
2883
        query = (" SELECT t.id, t.name, t.uuid "
2884
                 " FROM tbl_spaces s, tbl_spaces_stores st, tbl_stores t "
2885
                 " WHERE st.space_id = s.id AND t.id = st.store_id AND s.id = %s "
2886
                 " ORDER BY t.id ")
2887
        cursor.execute(query, (id_,))
2888
        rows = cursor.fetchall()
2889
2890
        result = list()
2891
        if rows is not None and len(rows) > 0:
2892
            for row in rows:
2893
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2894
                result.append(meta_result)
2895
2896
        resp.text = json.dumps(result)
2897
2898
    @staticmethod
2899
    @user_logger
2900
    def on_post(req, resp, id_):
2901
        """Handles POST requests"""
2902
        admin_control(req)
2903
        try:
2904
            raw_json = req.stream.read().decode('utf-8')
2905
        except Exception as ex:
2906
            raise falcon.HTTPError(status=falcon.HTTP_400,
2907
                                   title='API.BAD_REQUEST',
2908
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2909
2910
        if not id_.isdigit() or int(id_) <= 0:
2911
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2912
                                   description='API.INVALID_SPACE_ID')
2913
2914
        new_values = json.loads(raw_json)
2915
2916
        if 'store_id' not in new_values['data'].keys() or \
2917
                not isinstance(new_values['data']['store_id'], int) or \
2918
                new_values['data']['store_id'] <= 0:
2919
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2920
                                   description='API.INVALID_STORE_ID')
2921
        store_id = new_values['data']['store_id']
2922
2923
        cnx = mysql.connector.connect(**config.myems_system_db)
2924
        cursor = cnx.cursor()
2925
2926
        cursor.execute(" SELECT name "
2927
                       " from tbl_spaces "
2928
                       " WHERE id = %s ", (id_,))
2929
        if cursor.fetchone() is None:
2930
            cursor.close()
2931
            cnx.close()
2932
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2933
                                   description='API.SPACE_NOT_FOUND')
2934
2935
        cursor.execute(" SELECT name "
2936
                       " FROM tbl_stores "
2937
                       " WHERE id = %s ", (store_id,))
2938
        if cursor.fetchone() is None:
2939
            cursor.close()
2940
            cnx.close()
2941
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2942
                                   description='API.STORE_NOT_FOUND')
2943
2944
        query = (" SELECT id " 
2945
                 " FROM tbl_spaces_stores "
2946
                 " WHERE space_id = %s AND store_id = %s")
2947
        cursor.execute(query, (id_, store_id,))
2948
        if cursor.fetchone() is not None:
2949
            cursor.close()
2950
            cnx.close()
2951
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2952
                                   description='API.SPACE_STORE_RELATION_EXISTS')
2953
2954
        add_row = (" INSERT INTO tbl_spaces_stores (space_id, store_id) "
2955
                   " VALUES (%s, %s) ")
2956
        cursor.execute(add_row, (id_, store_id,))
2957
        cnx.commit()
2958
        cursor.close()
2959
        cnx.close()
2960
2961
        resp.status = falcon.HTTP_201
2962
        resp.location = '/spaces/' + str(id_) + '/stores/' + str(store_id)
2963
2964
2965 View Code Duplication
class SpaceStoreItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2966
    def __init__(self):
2967
        """Initializes Class"""
2968
        pass
2969
2970
    @staticmethod
2971
    def on_options(req, resp, id_, tid):
2972
        resp.status = falcon.HTTP_200
2973
2974
    @staticmethod
2975
    @user_logger
2976
    def on_delete(req, resp, id_, tid):
2977
        admin_control(req)
2978
        if not id_.isdigit() or int(id_) <= 0:
2979
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2980
                                   description='API.INVALID_SPACE_ID')
2981
2982
        if not tid.isdigit() or int(tid) <= 0:
2983
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2984
                                   description='API.INVALID_STORE_ID')
2985
2986
        cnx = mysql.connector.connect(**config.myems_system_db)
2987
        cursor = cnx.cursor()
2988
2989
        cursor.execute(" SELECT name "
2990
                       " FROM tbl_spaces "
2991
                       " WHERE id = %s ", (id_,))
2992
        if cursor.fetchone() is None:
2993
            cursor.close()
2994
            cnx.close()
2995
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2996
                                   description='API.SPACE_NOT_FOUND')
2997
2998
        cursor.execute(" SELECT name "
2999
                       " FROM tbl_stores "
3000
                       " WHERE id = %s ", (tid,))
3001
        if cursor.fetchone() is None:
3002
            cursor.close()
3003
            cnx.close()
3004
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3005
                                   description='API.STORE_NOT_FOUND')
3006
3007
        cursor.execute(" SELECT id "
3008
                       " FROM tbl_spaces_stores "
3009
                       " WHERE space_id = %s AND store_id = %s ", (id_, tid))
3010
        if cursor.fetchone() is None:
3011
            cursor.close()
3012
            cnx.close()
3013
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3014
                                   description='API.SPACE_STORE_RELATION_NOT_FOUND')
3015
3016
        cursor.execute(" DELETE FROM tbl_spaces_stores WHERE space_id = %s AND store_id = %s ", (id_, tid))
3017
        cnx.commit()
3018
3019
        cursor.close()
3020
        cnx.close()
3021
3022
        resp.status = falcon.HTTP_204
3023
3024
3025 View Code Duplication
class SpaceTenantCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3026
    def __init__(self):
3027
        """Initializes Class"""
3028
        pass
3029
3030
    @staticmethod
3031
    def on_options(req, resp, id_):
3032
        resp.status = falcon.HTTP_200
3033
3034
    @staticmethod
3035
    def on_get(req, resp, id_):
3036
        if 'API-KEY' not in req.headers or \
3037
                not isinstance(req.headers['API-KEY'], str) or \
3038
                len(str.strip(req.headers['API-KEY'])) == 0:
3039
            access_control(req)
3040
        else:
3041
            api_key_control(req)
3042
        if not id_.isdigit() or int(id_) <= 0:
3043
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3044
                                   description='API.INVALID_SPACE_ID')
3045
3046
        cnx = mysql.connector.connect(**config.myems_system_db)
3047
        cursor = cnx.cursor()
3048
3049
        cursor.execute(" SELECT name "
3050
                       " FROM tbl_spaces "
3051
                       " WHERE id = %s ", (id_,))
3052
        if cursor.fetchone() is None:
3053
            cursor.close()
3054
            cnx.close()
3055
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3056
                                   description='API.SPACE_NOT_FOUND')
3057
3058
        query = (" SELECT t.id, t.name, t.uuid "
3059
                 " FROM tbl_spaces s, tbl_spaces_tenants st, tbl_tenants t "
3060
                 " WHERE st.space_id = s.id AND t.id = st.tenant_id AND s.id = %s "
3061
                 " ORDER BY t.id ")
3062
        cursor.execute(query, (id_,))
3063
        rows = cursor.fetchall()
3064
3065
        result = list()
3066
        if rows is not None and len(rows) > 0:
3067
            for row in rows:
3068
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
3069
                result.append(meta_result)
3070
3071
        resp.text = json.dumps(result)
3072
3073
    @staticmethod
3074
    @user_logger
3075
    def on_post(req, resp, id_):
3076
        """Handles POST requests"""
3077
        admin_control(req)
3078
        try:
3079
            raw_json = req.stream.read().decode('utf-8')
3080
        except Exception as ex:
3081
            raise falcon.HTTPError(status=falcon.HTTP_400,
3082
                                   title='API.BAD_REQUEST',
3083
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3084
3085
        if not id_.isdigit() or int(id_) <= 0:
3086
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3087
                                   description='API.INVALID_SPACE_ID')
3088
3089
        new_values = json.loads(raw_json)
3090
3091
        if 'tenant_id' not in new_values['data'].keys() or \
3092
                not isinstance(new_values['data']['tenant_id'], int) or \
3093
                new_values['data']['tenant_id'] <= 0:
3094
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3095
                                   description='API.INVALID_TENANT_ID')
3096
        tenant_id = new_values['data']['tenant_id']
3097
3098
        cnx = mysql.connector.connect(**config.myems_system_db)
3099
        cursor = cnx.cursor()
3100
3101
        cursor.execute(" SELECT name "
3102
                       " from tbl_spaces "
3103
                       " WHERE id = %s ", (id_,))
3104
        if cursor.fetchone() is None:
3105
            cursor.close()
3106
            cnx.close()
3107
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3108
                                   description='API.SPACE_NOT_FOUND')
3109
3110
        cursor.execute(" SELECT name "
3111
                       " FROM tbl_tenants "
3112
                       " WHERE id = %s ", (tenant_id,))
3113
        if cursor.fetchone() is None:
3114
            cursor.close()
3115
            cnx.close()
3116
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3117
                                   description='API.TENANT_NOT_FOUND')
3118
3119
        query = (" SELECT id " 
3120
                 " FROM tbl_spaces_tenants "
3121
                 " WHERE space_id = %s AND tenant_id = %s")
3122
        cursor.execute(query, (id_, tenant_id,))
3123
        if cursor.fetchone() is not None:
3124
            cursor.close()
3125
            cnx.close()
3126
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3127
                                   description='API.SPACE_TENANT_RELATION_EXISTS')
3128
3129
        add_row = (" INSERT INTO tbl_spaces_tenants (space_id, tenant_id) "
3130
                   " VALUES (%s, %s) ")
3131
        cursor.execute(add_row, (id_, tenant_id,))
3132
        cnx.commit()
3133
        cursor.close()
3134
        cnx.close()
3135
3136
        resp.status = falcon.HTTP_201
3137
        resp.location = '/spaces/' + str(id_) + '/tenants/' + str(tenant_id)
3138
3139
3140 View Code Duplication
class SpaceTenantItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3141
    def __init__(self):
3142
        """Initializes Class"""
3143
        pass
3144
3145
    @staticmethod
3146
    def on_options(req, resp, id_, tid):
3147
        resp.status = falcon.HTTP_200
3148
3149
    @staticmethod
3150
    @user_logger
3151
    def on_delete(req, resp, id_, tid):
3152
        admin_control(req)
3153
        if not id_.isdigit() or int(id_) <= 0:
3154
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3155
                                   description='API.INVALID_SPACE_ID')
3156
3157
        if not tid.isdigit() or int(tid) <= 0:
3158
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3159
                                   description='API.INVALID_TENANT_ID')
3160
3161
        cnx = mysql.connector.connect(**config.myems_system_db)
3162
        cursor = cnx.cursor()
3163
3164
        cursor.execute(" SELECT name "
3165
                       " FROM tbl_spaces "
3166
                       " WHERE id = %s ", (id_,))
3167
        if cursor.fetchone() is None:
3168
            cursor.close()
3169
            cnx.close()
3170
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3171
                                   description='API.SPACE_NOT_FOUND')
3172
3173
        cursor.execute(" SELECT name "
3174
                       " FROM tbl_tenants "
3175
                       " WHERE id = %s ", (tid,))
3176
        if cursor.fetchone() is None:
3177
            cursor.close()
3178
            cnx.close()
3179
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3180
                                   description='API.TENANT_NOT_FOUND')
3181
3182
        cursor.execute(" SELECT id "
3183
                       " FROM tbl_spaces_tenants "
3184
                       " WHERE space_id = %s AND tenant_id = %s ", (id_, tid))
3185
        if cursor.fetchone() is None:
3186
            cursor.close()
3187
            cnx.close()
3188
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3189
                                   description='API.SPACE_TENANT_RELATION_NOT_FOUND')
3190
3191
        cursor.execute(" DELETE FROM tbl_spaces_tenants WHERE space_id = %s AND tenant_id = %s ", (id_, tid))
3192
        cnx.commit()
3193
3194
        cursor.close()
3195
        cnx.close()
3196
3197
        resp.status = falcon.HTTP_204
3198
3199
3200 View Code Duplication
class SpaceVirtualMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3201
    def __init__(self):
3202
        """Initializes Class"""
3203
        pass
3204
3205
    @staticmethod
3206
    def on_options(req, resp, id_):
3207
        resp.status = falcon.HTTP_200
3208
3209
    @staticmethod
3210
    def on_get(req, resp, id_):
3211
        if 'API-KEY' not in req.headers or \
3212
                not isinstance(req.headers['API-KEY'], str) or \
3213
                len(str.strip(req.headers['API-KEY'])) == 0:
3214
            access_control(req)
3215
        else:
3216
            api_key_control(req)
3217
        if not id_.isdigit() or int(id_) <= 0:
3218
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3219
                                   description='API.INVALID_SPACE_ID')
3220
3221
        cnx = mysql.connector.connect(**config.myems_system_db)
3222
        cursor = cnx.cursor()
3223
3224
        cursor.execute(" SELECT name "
3225
                       " FROM tbl_spaces "
3226
                       " WHERE id = %s ", (id_,))
3227
        if cursor.fetchone() is None:
3228
            cursor.close()
3229
            cnx.close()
3230
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3231
                                   description='API.SPACE_NOT_FOUND')
3232
3233
        query = (" SELECT id, name, uuid "
3234
                 " FROM tbl_energy_categories ")
3235
        cursor.execute(query)
3236
        rows_energy_categories = cursor.fetchall()
3237
3238
        energy_category_dict = dict()
3239
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
3240
            for row in rows_energy_categories:
3241
                energy_category_dict[row[0]] = {"id": row[0],
3242
                                                "name": row[1],
3243
                                                "uuid": row[2]}
3244
3245
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
3246
                 " FROM tbl_spaces s, tbl_spaces_virtual_meters sm, tbl_virtual_meters m "
3247
                 " WHERE sm.space_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
3248
                 " ORDER BY m.id ")
3249
        cursor.execute(query, (id_,))
3250
        rows = cursor.fetchall()
3251
3252
        result = list()
3253
        if rows is not None and len(rows) > 0:
3254
            for row in rows:
3255
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
3256
                               "energy_category": energy_category_dict.get(row[3], None)}
3257
                result.append(meta_result)
3258
3259
        resp.text = json.dumps(result)
3260
3261
    @staticmethod
3262
    @user_logger
3263
    def on_post(req, resp, id_):
3264
        """Handles POST requests"""
3265
        admin_control(req)
3266
        try:
3267
            raw_json = req.stream.read().decode('utf-8')
3268
        except Exception as ex:
3269
            raise falcon.HTTPError(status=falcon.HTTP_400,
3270
                                   title='API.BAD_REQUEST',
3271
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3272
3273
        if not id_.isdigit() or int(id_) <= 0:
3274
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3275
                                   description='API.INVALID_SPACE_ID')
3276
3277
        new_values = json.loads(raw_json)
3278
3279
        if 'virtual_meter_id' not in new_values['data'].keys() or \
3280
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
3281
                new_values['data']['virtual_meter_id'] <= 0:
3282
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3283
                                   description='API.INVALID_VIRTUAL_METER_ID')
3284
        virtual_meter_id = new_values['data']['virtual_meter_id']
3285
3286
        cnx = mysql.connector.connect(**config.myems_system_db)
3287
        cursor = cnx.cursor()
3288
3289
        cursor.execute(" SELECT name "
3290
                       " from tbl_spaces "
3291
                       " WHERE id = %s ", (id_,))
3292
        if cursor.fetchone() is None:
3293
            cursor.close()
3294
            cnx.close()
3295
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3296
                                   description='API.SPACE_NOT_FOUND')
3297
3298
        cursor.execute(" SELECT name "
3299
                       " FROM tbl_virtual_meters "
3300
                       " WHERE id = %s ", (virtual_meter_id,))
3301
        if cursor.fetchone() is None:
3302
            cursor.close()
3303
            cnx.close()
3304
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3305
                                   description='API.VIRTUAL_METER_NOT_FOUND')
3306
3307
        query = (" SELECT id " 
3308
                 " FROM tbl_spaces_virtual_meters "
3309
                 " WHERE space_id = %s AND virtual_meter_id = %s")
3310
        cursor.execute(query, (id_, virtual_meter_id,))
3311
        if cursor.fetchone() is not None:
3312
            cursor.close()
3313
            cnx.close()
3314
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3315
                                   description='API.SPACE_VIRTUAL_METER_RELATION_EXISTS')
3316
3317
        add_row = (" INSERT INTO tbl_spaces_virtual_meters (space_id, virtual_meter_id) "
3318
                   " VALUES (%s, %s) ")
3319
        cursor.execute(add_row, (id_, virtual_meter_id,))
3320
        cnx.commit()
3321
        cursor.close()
3322
        cnx.close()
3323
3324
        resp.status = falcon.HTTP_201
3325
        resp.location = '/spaces/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
3326
3327
3328 View Code Duplication
class SpaceVirtualMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3329
    def __init__(self):
3330
        """Initializes Class"""
3331
        pass
3332
3333
    @staticmethod
3334
    def on_options(req, resp, id_, mid):
3335
        resp.status = falcon.HTTP_200
3336
3337
    @staticmethod
3338
    @user_logger
3339
    def on_delete(req, resp, id_, mid):
3340
        admin_control(req)
3341
        if not id_.isdigit() or int(id_) <= 0:
3342
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3343
                                   description='API.INVALID_SPACE_ID')
3344
3345
        if not mid.isdigit() or int(mid) <= 0:
3346
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3347
                                   description='API.INVALID_VIRTUAL_METER_ID')
3348
3349
        cnx = mysql.connector.connect(**config.myems_system_db)
3350
        cursor = cnx.cursor()
3351
3352
        cursor.execute(" SELECT name "
3353
                       " FROM tbl_spaces "
3354
                       " WHERE id = %s ", (id_,))
3355
        if cursor.fetchone() is None:
3356
            cursor.close()
3357
            cnx.close()
3358
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3359
                                   description='API.SPACE_NOT_FOUND')
3360
3361
        cursor.execute(" SELECT name "
3362
                       " FROM tbl_virtual_meters "
3363
                       " WHERE id = %s ", (mid,))
3364
        if cursor.fetchone() is None:
3365
            cursor.close()
3366
            cnx.close()
3367
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3368
                                   description='API.VIRTUAL_METER_NOT_FOUND')
3369
3370
        cursor.execute(" SELECT id "
3371
                       " FROM tbl_spaces_virtual_meters "
3372
                       " WHERE space_id = %s AND virtual_meter_id = %s ", (id_, mid))
3373
        if cursor.fetchone() is None:
3374
            cursor.close()
3375
            cnx.close()
3376
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3377
                                   description='API.SPACE_VIRTUAL_METER_RELATION_NOT_FOUND')
3378
3379
        cursor.execute(" DELETE FROM tbl_spaces_virtual_meters "
3380
                       " WHERE space_id = %s AND virtual_meter_id = %s ", (id_, mid))
3381
        cnx.commit()
3382
3383
        cursor.close()
3384
        cnx.close()
3385
3386
        resp.status = falcon.HTTP_204
3387
3388
3389
class SpaceTreeCollection:
3390
    def __init__(self):
3391
        """Initializes Class"""
3392
        pass
3393
3394
    @staticmethod
3395
    def on_options(req, resp):
3396
        resp.status = falcon.HTTP_200
3397
3398
    @staticmethod
3399
    def on_get(req, resp):
3400
        access_control(req)
3401
        if 'USER-UUID' not in req.headers or \
3402
                not isinstance(req.headers['USER-UUID'], str) or \
3403
                len(str.strip(req.headers['USER-UUID'])) == 0:
3404
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3405
                                   description='API.INVALID_USER_UUID')
3406
        user_uuid = str.strip(req.headers['USER-UUID'])
3407
3408
        if 'TOKEN' not in req.headers or \
3409
                not isinstance(req.headers['TOKEN'], str) or \
3410
                len(str.strip(req.headers['TOKEN'])) == 0:
3411
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3412
                                   description='API.INVALID_TOKEN')
3413
        token = str.strip(req.headers['TOKEN'])
3414
3415
        # Verify User Session
3416
        cnx = mysql.connector.connect(**config.myems_user_db)
3417
        cursor = cnx.cursor()
3418
        query = (" SELECT utc_expires "
3419
                 " FROM tbl_sessions "
3420
                 " WHERE user_uuid = %s AND token = %s")
3421
        cursor.execute(query, (user_uuid, token,))
3422
        row = cursor.fetchone()
3423
3424
        if row is None:
3425
            cursor.close()
3426
            cnx.close()
3427
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3428
                                   description='API.USER_SESSION_NOT_FOUND')
3429
        else:
3430
            utc_expires = row[0]
3431
            if datetime.utcnow() > utc_expires:
3432
                cursor.close()
3433
                cnx.close()
3434
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3435
                                       description='API.USER_SESSION_TIMEOUT')
3436
        # get privilege
3437
        query = (" SELECT is_admin, privilege_id "
3438
                 " FROM tbl_users "
3439
                 " WHERE uuid = %s ")
3440
        cursor.execute(query, (user_uuid,))
3441
        row = cursor.fetchone()
3442
        if row is None:
3443
            cursor.close()
3444
            cnx.close()
3445
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.USER_NOT_FOUND')
3446
        else:
3447
            is_admin = bool(row[0])
3448
            privilege_id = row[1]
3449
3450
        # get space_id in privilege
3451
        if is_admin:
3452
            space_id = 1
3453
        elif privilege_id is None:
3454
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3455
                                   description='API.PRIVILEGE_NOT_FOUND')
3456
        else:
3457
            query = (" SELECT data "
3458
                     " FROM tbl_privileges "
3459
                     " WHERE id = %s ")
3460
            cursor.execute(query, (privilege_id,))
3461
            row = cursor.fetchone()
3462
            cursor.close()
3463
            cnx.close()
3464
3465
            if row is None:
3466
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3467
                                       description='API.PRIVILEGE_NOT_FOUND')
3468
            try:
3469
                data = json.loads(row[0])
3470
            except Exception as ex:
3471
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR', description=str(ex))
3472
3473
            if 'spaces' not in data or len(data['spaces']) == 0:
3474
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3475
                                       description='API.SPACE_NOT_FOUND_IN_PRIVILEGE')
3476
3477
            space_id = data['spaces'][0]
3478
            if space_id is None:
3479
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3480
                                       description='API.PRIVILEGE_NOT_FOUND')
3481
        # get all spaces
3482
        cnx = mysql.connector.connect(**config.myems_system_db)
3483
        cursor = cnx.cursor()
3484
3485
        query = (" SELECT id, name, parent_space_id "
3486
                 " FROM tbl_spaces "
3487
                 " ORDER BY id ")
3488
        cursor.execute(query)
3489
        rows_spaces = cursor.fetchall()
3490
        node_dict = dict()
3491
        if rows_spaces is not None and len(rows_spaces) > 0:
3492
            for row in rows_spaces:
3493
                parent_node = node_dict[row[2]] if row[2] is not None else None
3494
                node_dict[row[0]] = AnyNode(id=row[0], parent=parent_node, name=row[1])
3495
3496
        cursor.close()
3497
        cnx.close()
3498
        resp.text = JsonExporter(sort_keys=True).export(node_dict[space_id], )
3499
3500
3501
# Get energy categories of all meters in the space tree
3502
class SpaceTreeMetersEnergyCategoryCollection:
3503
    def __init__(self):
3504
        """Initializes Class"""
3505
        pass
3506
3507
    @staticmethod
3508
    def on_options(req, resp, id_):
3509
        resp.status = falcon.HTTP_200
3510
3511
    @staticmethod
3512
    def on_get(req, resp, id_):
3513
        if 'API-KEY' not in req.headers or \
3514
                not isinstance(req.headers['API-KEY'], str) or \
3515
                len(str.strip(req.headers['API-KEY'])) == 0:
3516
            access_control(req)
3517
        else:
3518
            api_key_control(req)
3519
        ################################################################################################################
3520
        # Step 1: valid parameters
3521
        ################################################################################################################
3522
        if not id_.isdigit() or int(id_) <= 0:
3523
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3524
                                   description='API.INVALID_SPACE_ID')
3525
3526
        cnx = mysql.connector.connect(**config.myems_system_db)
3527
        cursor = cnx.cursor()
3528
3529
        cursor.execute(" SELECT name "
3530
                       " FROM tbl_spaces "
3531
                       " WHERE id = %s ", (id_,))
3532
        if cursor.fetchone() is None:
3533
            cursor.close()
3534
            cnx.close()
3535
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3536
                                   description='API.SPACE_NOT_FOUND')
3537
3538
        ################################################################################################################
3539
        # Step 2: build a space tree
3540
        ################################################################################################################
3541
        query = (" SELECT id, name, parent_space_id "
3542
                 " FROM tbl_spaces "
3543
                 " ORDER BY id ")
3544
        cursor.execute(query)
3545
        rows_spaces = cursor.fetchall()
3546
        node_dict = dict()
3547
        if rows_spaces is not None and len(rows_spaces) > 0:
3548
            for row in rows_spaces:
3549
                parent_node = node_dict[row[2]] if row[2] is not None else None
3550
                node_dict[row[0]] = AnyNode(id=row[0], parent=parent_node, name=row[1])
3551
        ################################################################################################################
3552
        # Step 3: query energy categories of all meters in the space tree
3553
        ################################################################################################################
3554
        space_dict = dict()
3555
3556
        for node in LevelOrderIter(node_dict[int(id_)]):
3557
            space_dict[node.id] = node.name
3558
3559
        cursor.execute(" SELECT distinct(m.energy_category_id), ec.name AS energy_category_name, ec.uuid "
3560
                       " FROM tbl_spaces s, tbl_spaces_meters sm, tbl_meters m, tbl_energy_categories ec  "
3561
                       " WHERE s.id IN ( " + ', '.join(map(str, space_dict.keys())) + ") "
3562
                       "       AND sm.space_id = s.id AND sm.meter_id = m.id  AND m.energy_category_id = ec.id ", )
3563
        rows_energy_categories = cursor.fetchall()
3564
3565
        result = list()
3566
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
3567
            for row in rows_energy_categories:
3568
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
3569
                result.append(meta_result)
3570
3571
        resp.text = json.dumps(result)
3572
3573
3574 View Code Duplication
class SpaceWorkingCalendarCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3575
    def __init__(self):
3576
        """Initializes SpaceWorkingCalendarCollection Class"""
3577
        pass
3578
3579
    @staticmethod
3580
    def on_options(req, resp, id_):
3581
        resp.status = falcon.HTTP_200
3582
3583
    @staticmethod
3584
    def on_get(req, resp, id_):
3585
        if 'API-KEY' not in req.headers or \
3586
                not isinstance(req.headers['API-KEY'], str) or \
3587
                len(str.strip(req.headers['API-KEY'])) == 0:
3588
            access_control(req)
3589
        else:
3590
            api_key_control(req)
3591
        if not id_.isdigit() or int(id_) <= 0:
3592
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3593
                                   description='API.INVALID_SPACE_ID')
3594
3595
        cnx = mysql.connector.connect(**config.myems_system_db)
3596
        cursor = cnx.cursor()
3597
3598
        cursor.execute(" SELECT name "
3599
                       " FROM tbl_spaces "
3600
                       " WHERE id = %s ", (id_,))
3601
        if cursor.fetchone() is None:
3602
            cursor.close()
3603
            cnx.close()
3604
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3605
                                   description='API.SPACE_NOT_FOUND')
3606
3607
        query = (" SELECT wc.id, wc.name, wc.description "
3608
                 " FROM tbl_spaces s, tbl_spaces_working_calendars swc, tbl_working_calendars wc "
3609
                 " WHERE swc.space_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
3610
                 " ORDER BY wc.id ")
3611
        cursor.execute(query, (id_,))
3612
        rows = cursor.fetchall()
3613
3614
        result = list()
3615
        if rows is not None and len(rows) > 0:
3616
            for row in rows:
3617
                meta_result = {"id": row[0], "name": row[1], "description": row[2]}
3618
                result.append(meta_result)
3619
3620
        resp.text = json.dumps(result)
3621
3622
    @staticmethod
3623
    @user_logger
3624
    def on_post(req, resp, id_):
3625
        """Handles POST requests"""
3626
        admin_control(req)
3627
        try:
3628
            raw_json = req.stream.read().decode('utf-8')
3629
        except Exception as ex:
3630
            raise falcon.HTTPError(status=falcon.HTTP_400,
3631
                                   title='API.BAD_REQUEST',
3632
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3633
3634
        if not id_.isdigit() or int(id_) <= 0:
3635
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3636
                                   description='API.INVALID_SPACE_ID')
3637
3638
        new_values = json.loads(raw_json)
3639
3640
        if 'working_calendar_id' not in new_values['data'].keys() or \
3641
                not isinstance(new_values['data']['working_calendar_id'], int) or \
3642
                new_values['data']['working_calendar_id'] <= 0:
3643
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3644
                                   description='API.INVALID_WORKING_CALENDAR_ID')
3645
        working_calendar_id = new_values['data']['working_calendar_id']
3646
3647
        cnx = mysql.connector.connect(**config.myems_system_db)
3648
        cursor = cnx.cursor()
3649
3650
        cursor.execute(" SELECT name "
3651
                       " from tbl_spaces "
3652
                       " WHERE id = %s ", (id_,))
3653
        if cursor.fetchone() is None:
3654
            cursor.close()
3655
            cnx.close()
3656
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3657
                                   description='API.SPACE_NOT_FOUND')
3658
3659
        cursor.execute(" SELECT name "
3660
                       " FROM tbl_working_calendars "
3661
                       " WHERE id = %s ", (working_calendar_id,))
3662
        if cursor.fetchone() is None:
3663
            cursor.close()
3664
            cnx.close()
3665
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3666
                                   description='API.WORKING_CALENDAR_NOT_FOUND')
3667
3668
        query = (" SELECT id " 
3669
                 " FROM tbl_spaces_working_calendars "
3670
                 " WHERE space_id = %s AND working_calendar_id = %s")
3671
        cursor.execute(query, (id_, working_calendar_id,))
3672
        if cursor.fetchone() is not None:
3673
            cursor.close()
3674
            cnx.close()
3675
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3676
                                   description='API.SPACE_WORKING_CALENDAR_RELATION_EXISTS')
3677
3678
        add_row = (" INSERT INTO tbl_spaces_working_calendars (space_id, working_calendar_id) "
3679
                   " VALUES (%s, %s) ")
3680
        cursor.execute(add_row, (id_, working_calendar_id,))
3681
        cnx.commit()
3682
        cursor.close()
3683
        cnx.close()
3684
3685
        resp.status = falcon.HTTP_201
3686
        resp.location = '/spaces/' + str(id_) + '/workingcalendars/' + str(working_calendar_id)
3687
3688
3689 View Code Duplication
class SpaceWorkingCalendarItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3690
    def __init__(self):
3691
        """Initializes SpaceWorkingCalendarItem Class"""
3692
        pass
3693
3694
    @staticmethod
3695
    def on_options(req, resp, id_, wcid):
3696
        resp.status = falcon.HTTP_200
3697
3698
    @staticmethod
3699
    @user_logger
3700
    def on_delete(req, resp, id_, wcid):
3701
        admin_control(req)
3702
        if not id_.isdigit() or int(id_) <= 0:
3703
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3704
                                   description='API.INVALID_SPACE_ID')
3705
3706
        if not wcid.isdigit() or int(wcid) <= 0:
3707
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3708
                                   description='API.INVALID_WORKING_CALENDAR_ID')
3709
3710
        cnx = mysql.connector.connect(**config.myems_system_db)
3711
        cursor = cnx.cursor()
3712
3713
        cursor.execute(" SELECT name "
3714
                       " FROM tbl_spaces "
3715
                       " WHERE id = %s ", (id_,))
3716
        if cursor.fetchone() is None:
3717
            cursor.close()
3718
            cnx.close()
3719
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3720
                                   description='API.SPACE_NOT_FOUND')
3721
3722
        cursor.execute(" SELECT name "
3723
                       " FROM tbl_working_calendars "
3724
                       " WHERE id = %s ", (wcid,))
3725
        if cursor.fetchone() is None:
3726
            cursor.close()
3727
            cnx.close()
3728
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3729
                                   description='API.WORKING_CALENDAR_NOT_FOUND')
3730
3731
        cursor.execute(" SELECT id "
3732
                       " FROM tbl_spaces_working_calendars "
3733
                       " WHERE space_id = %s AND working_calendar_id = %s ", (id_, wcid))
3734
        if cursor.fetchone() is None:
3735
            cursor.close()
3736
            cnx.close()
3737
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3738
                                   description='API.SPACE_WORKING_CALENDAR_RELATION_NOT_FOUND')
3739
3740
        cursor.execute(" DELETE FROM tbl_spaces_working_calendars "
3741
                       " WHERE space_id = %s AND working_calendar_id = %s ", (id_, wcid))
3742
        cnx.commit()
3743
3744
        cursor.close()
3745
        cnx.close()
3746
3747
        resp.status = falcon.HTTP_204
3748
3749
3750 View Code Duplication
class SpaceCommandCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3751
    def __init__(self):
3752
        """Initializes Class"""
3753
        pass
3754
3755
    @staticmethod
3756
    def on_options(req, resp, id_):
3757
        resp.status = falcon.HTTP_200
3758
3759
    @staticmethod
3760
    def on_get(req, resp, id_):
3761
        if 'API-KEY' not in req.headers or \
3762
                not isinstance(req.headers['API-KEY'], str) or \
3763
                len(str.strip(req.headers['API-KEY'])) == 0:
3764
            access_control(req)
3765
        else:
3766
            api_key_control(req)
3767
        if not id_.isdigit() or int(id_) <= 0:
3768
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3769
                                   description='API.INVALID_SPACE_ID')
3770
3771
        cnx = mysql.connector.connect(**config.myems_system_db)
3772
        cursor = cnx.cursor()
3773
3774
        cursor.execute(" SELECT name "
3775
                       " FROM tbl_spaces "
3776
                       " WHERE id = %s ", (id_,))
3777
        if cursor.fetchone() is None:
3778
            cursor.close()
3779
            cnx.close()
3780
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3781
                                   description='API.SPACE_NOT_FOUND')
3782
3783
        query = (" SELECT c.id, c.name, c.uuid "
3784
                 " FROM tbl_spaces s, tbl_spaces_commands sc, tbl_commands c "
3785
                 " WHERE sc.space_id = s.id AND c.id = sc.command_id AND s.id = %s "
3786
                 " ORDER BY c.id ")
3787
        cursor.execute(query, (id_,))
3788
        rows = cursor.fetchall()
3789
3790
        result = list()
3791
        if rows is not None and len(rows) > 0:
3792
            for row in rows:
3793
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
3794
                result.append(meta_result)
3795
3796
        resp.text = json.dumps(result)
3797
3798
    @staticmethod
3799
    @user_logger
3800
    def on_post(req, resp, id_):
3801
        """Handles POST requests"""
3802
        admin_control(req)
3803
        try:
3804
            raw_json = req.stream.read().decode('utf-8')
3805
        except Exception as ex:
3806
            raise falcon.HTTPError(status=falcon.HTTP_400,
3807
                                   title='API.BAD_REQUEST',
3808
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3809
3810
        if not id_.isdigit() or int(id_) <= 0:
3811
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3812
                                   description='API.INVALID_SPACE_ID')
3813
3814
        new_values = json.loads(raw_json)
3815
3816
        if 'command_id' not in new_values['data'].keys() or \
3817
                not isinstance(new_values['data']['command_id'], int) or \
3818
                new_values['data']['command_id'] <= 0:
3819
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3820
                                   description='API.INVALID_COMMAND_ID')
3821
        command_id = new_values['data']['command_id']
3822
3823
        cnx = mysql.connector.connect(**config.myems_system_db)
3824
        cursor = cnx.cursor()
3825
3826
        cursor.execute(" SELECT name "
3827
                       " from tbl_spaces "
3828
                       " WHERE id = %s ", (id_,))
3829
        if cursor.fetchone() is None:
3830
            cursor.close()
3831
            cnx.close()
3832
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3833
                                   description='API.SPACE_NOT_FOUND')
3834
3835
        cursor.execute(" SELECT name "
3836
                       " FROM tbl_commands "
3837
                       " WHERE id = %s ", (command_id,))
3838
        if cursor.fetchone() is None:
3839
            cursor.close()
3840
            cnx.close()
3841
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3842
                                   description='API.COMMAND_NOT_FOUND')
3843
3844
        query = (" SELECT id " 
3845
                 " FROM tbl_spaces_commands "
3846
                 " WHERE space_id = %s AND command_id = %s")
3847
        cursor.execute(query, (id_, command_id,))
3848
        if cursor.fetchone() is not None:
3849
            cursor.close()
3850
            cnx.close()
3851
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3852
                                   description='API.SPACE_COMMAND_RELATION_EXISTS')
3853
3854
        add_row = (" INSERT INTO tbl_spaces_commands (space_id, command_id) "
3855
                   " VALUES (%s, %s) ")
3856
        cursor.execute(add_row, (id_, command_id,))
3857
        cnx.commit()
3858
        cursor.close()
3859
        cnx.close()
3860
3861
        resp.status = falcon.HTTP_201
3862
        resp.location = '/spaces/' + str(id_) + '/commands/' + str(command_id)
3863
3864
3865 View Code Duplication
class SpaceCommandItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3866
    def __init__(self):
3867
        """Initializes Class"""
3868
        pass
3869
3870
    @staticmethod
3871
    def on_options(req, resp, id_, cid):
3872
        resp.status = falcon.HTTP_200
3873
3874
    @staticmethod
3875
    @user_logger
3876
    def on_delete(req, resp, id_, cid):
3877
        admin_control(req)
3878
        if not id_.isdigit() or int(id_) <= 0:
3879
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3880
                                   description='API.INVALID_SPACE_ID')
3881
3882
        if not cid.isdigit() or int(cid) <= 0:
3883
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3884
                                   description='API.INVALID_COMMAND_ID')
3885
3886
        cnx = mysql.connector.connect(**config.myems_system_db)
3887
        cursor = cnx.cursor()
3888
3889
        cursor.execute(" SELECT name "
3890
                       " FROM tbl_spaces "
3891
                       " WHERE id = %s ", (id_,))
3892
        if cursor.fetchone() is None:
3893
            cursor.close()
3894
            cnx.close()
3895
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3896
                                   description='API.SPACE_NOT_FOUND')
3897
3898
        cursor.execute(" SELECT name "
3899
                       " FROM tbl_commands "
3900
                       " WHERE id = %s ", (cid,))
3901
        if cursor.fetchone() is None:
3902
            cursor.close()
3903
            cnx.close()
3904
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3905
                                   description='API.COMMAND_NOT_FOUND')
3906
3907
        cursor.execute(" SELECT id "
3908
                       " FROM tbl_spaces_commands "
3909
                       " WHERE space_id = %s AND command_id = %s ", (id_, cid))
3910
        if cursor.fetchone() is None:
3911
            cursor.close()
3912
            cnx.close()
3913
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3914
                                   description='API.SPACE_COMMAND_RELATION_NOT_FOUND')
3915
3916
        cursor.execute(" DELETE FROM tbl_spaces_commands WHERE space_id = %s AND command_id = %s ", (id_, cid))
3917
        cnx.commit()
3918
3919
        cursor.close()
3920
        cnx.close()
3921
3922
        resp.status = falcon.HTTP_204
3923
3924
3925
class SpaceExport:
3926
    def __init__(self):
3927
        """Initializes Class"""
3928
        pass
3929
3930
    @staticmethod
3931
    def on_options(req, resp, id_):
3932
        resp.status = falcon.HTTP_200
3933
3934
    @staticmethod
3935
    def on_get(req, resp, id_):
3936
        if 'API-KEY' not in req.headers or \
3937
                not isinstance(req.headers['API-KEY'], str) or \
3938
                len(str.strip(req.headers['API-KEY'])) == 0:
3939
            access_control(req)
3940
        else:
3941
            api_key_control(req)
3942
        if not id_.isdigit() or int(id_) <= 0:
3943
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3944
                                   description='API.INVALID_METER_ID')
3945
3946
        cnx = mysql.connector.connect(**config.myems_system_db)
3947
        cursor = cnx.cursor()
3948
3949
        query = (" SELECT id, name, uuid "
3950
                 " FROM tbl_spaces ")
3951
        cursor.execute(query)
3952
        rows_spaces = cursor.fetchall()
3953
3954
        space_dict = dict()
3955
        if rows_spaces is not None and len(rows_spaces) > 0:
3956
            for row in rows_spaces:
3957
                space_dict[row[0]] = {"id": row[0],
3958
                                      "name": row[1],
3959
                                      "uuid": row[2]}
3960
3961
        query = (" SELECT id, name, utc_offset "
3962
                 " FROM tbl_timezones ")
3963
        cursor.execute(query)
3964
        rows_timezones = cursor.fetchall()
3965
3966
        timezone_dict = dict()
3967
        if rows_timezones is not None and len(rows_timezones) > 0:
3968
            for row in rows_timezones:
3969
                timezone_dict[row[0]] = {"id": row[0],
3970
                                         "name": row[1],
3971
                                         "utc_offset": row[2]}
3972
3973
        query = (" SELECT id, name, uuid "
3974
                 " FROM tbl_contacts ")
3975
        cursor.execute(query)
3976
        rows_contacts = cursor.fetchall()
3977
3978
        contact_dict = dict()
3979
        if rows_contacts is not None and len(rows_contacts) > 0:
3980
            for row in rows_contacts:
3981
                contact_dict[row[0]] = {"id": row[0],
3982
                                        "name": row[1],
3983
                                        "uuid": row[2]}
3984
3985
        query = (" SELECT id, name, uuid "
3986
                 " FROM tbl_cost_centers ")
3987
        cursor.execute(query)
3988
        rows_cost_centers = cursor.fetchall()
3989
3990
        cost_center_dict = dict()
3991
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
3992
            for row in rows_cost_centers:
3993
                cost_center_dict[row[0]] = {"id": row[0],
3994
                                            "name": row[1],
3995
                                            "uuid": row[2]}
3996
3997
        query = (" SELECT id, name, uuid, "
3998
                 "        parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
3999
                 "        contact_id, cost_center_id, latitude, longitude, description "
4000
                 " FROM tbl_spaces "
4001
                 " WHERE id = %s ")
4002
        cursor.execute(query, (id_,))
4003
        row = cursor.fetchone()
4004
4005
        if row is None:
4006
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4007
                                   description='API.SPACE_NOT_FOUND')
4008
        else:
4009
            meta_result = {"id": row[0],
4010
                           "name": row[1],
4011
                           "uuid": row[2],
4012
                           "parent_space_id": space_dict.get(row[3], None),
4013
                           "area": row[4],
4014
                           "timezone": timezone_dict.get(row[5], None),
4015
                           "is_input_counted": bool(row[6]),
4016
                           "is_output_counted": bool(row[7]),
4017
                           "contact": contact_dict.get(row[8], None),
4018
                           "cost_center": cost_center_dict.get(row[9], None),
4019
                           "latitude": row[10],
4020
                           "longitude": row[11],
4021
                           "description": row[12],
4022
                           "children": None,
4023
                           "commands": None,
4024
                           "meters": None,
4025
                           "offline_meters": None,
4026
                           "virtual_meters": None,
4027
                           "shopfloors": None,
4028
                           "combined_equipments": None,
4029
                           "equipments": None,
4030
                           "points": None,
4031
                           "sensors": None,
4032
                           "tenants": None,
4033
                           "stores": None,
4034
                           "working_calendars": None
4035
                           }
4036
            query = (" SELECT id, name, uuid, "
4037
                     "        parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
4038
                     "        contact_id, cost_center_id, latitude, longitude, description "
4039
                     " FROM tbl_spaces "
4040
                     " WHERE id = %s ")
4041
            cursor.execute(query, (id_,))
4042
            row_current_space = cursor.fetchone()
4043
            if row_current_space is None:
4044
                cursor.close()
4045
                cnx.close()
4046
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4047
                                       description='API.SPACE_NOT_FOUND')
4048
            # note: row_current_space will be used at the end
4049
4050
            query = (" SELECT id, name, uuid "
4051
                     " FROM tbl_spaces ")
4052
            cursor.execute(query)
4053
            rows_spaces = cursor.fetchall()
4054
4055
            space_dict = dict()
4056
            if rows_spaces is not None and len(rows_spaces) > 0:
4057
                for row in rows_spaces:
4058
                    space_dict[row[0]] = {"id": row[0],
4059
                                          "name": row[1],
4060
                                          "uuid": row[2]}
4061
4062
            query = (" SELECT id, name, utc_offset "
4063
                     " FROM tbl_timezones ")
4064
            cursor.execute(query)
4065
            rows_timezones = cursor.fetchall()
4066
4067
            timezone_dict = dict()
4068
            if rows_timezones is not None and len(rows_timezones) > 0:
4069
                for row in rows_timezones:
4070
                    timezone_dict[row[0]] = {"id": row[0],
4071
                                             "name": row[1],
4072
                                             "utc_offset": row[2]}
4073
4074
            query = (" SELECT id, name, uuid "
4075
                     " FROM tbl_contacts ")
4076
            cursor.execute(query)
4077
            rows_contacts = cursor.fetchall()
4078
4079
            contact_dict = dict()
4080
            if rows_contacts is not None and len(rows_contacts) > 0:
4081
                for row in rows_contacts:
4082
                    contact_dict[row[0]] = {"id": row[0],
4083
                                            "name": row[1],
4084
                                            "uuid": row[2]}
4085
4086
            query = (" SELECT id, name, uuid "
4087
                     " FROM tbl_cost_centers ")
4088
            cursor.execute(query)
4089
            rows_cost_centers = cursor.fetchall()
4090
4091
            cost_center_dict = dict()
4092
            if rows_cost_centers is not None and len(rows_cost_centers) > 0:
4093
                for row in rows_cost_centers:
4094
                    cost_center_dict[row[0]] = {"id": row[0],
4095
                                                "name": row[1],
4096
                                                "uuid": row[2]}
4097
            result = dict()
4098
            result['current'] = dict()
4099
            result['current']['id'] = row_current_space[0]
4100
            result['current']['name'] = row_current_space[1]
4101
            result['current']['uuid'] = row_current_space[2]
4102
            result['current']['parent_space'] = space_dict.get(row_current_space[3], None)
4103
            result['current']['area'] = row_current_space[4]
4104
            result['current']['timezone'] = timezone_dict.get(row_current_space[5], None)
4105
            result['current']['is_input_counted'] = bool(row_current_space[6])
4106
            result['current']['is_output_counted'] = bool(row_current_space[7])
4107
            result['current']['contact'] = contact_dict.get(row_current_space[8], None)
4108
            result['current']['cost_center'] = cost_center_dict.get(row_current_space[9], None)
4109
            result['current']['latitude'] = row_current_space[10]
4110
            result['current']['longitude'] = row_current_space[11]
4111
            result['current']['description'] = row_current_space[12]
4112
            result['current']['qrcode'] = 'space:' + row_current_space[2]
4113
4114
            result['children'] = list()
4115
4116
            query = (" SELECT id, name, uuid, "
4117
                     "        parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
4118
                     "        contact_id, cost_center_id, latitude, longitude, description "
4119
                     " FROM tbl_spaces "
4120
                     " WHERE parent_space_id = %s "
4121
                     " ORDER BY id ")
4122
            cursor.execute(query, (id_,))
4123
            rows_spaces = cursor.fetchall()
4124
4125 View Code Duplication
            if rows_spaces is not None and len(rows_spaces) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4126
                for row in rows_spaces:
4127
                    children_result = {"id": row[0],
4128
                                       "name": row[1],
4129
                                       "uuid": row[2],
4130
                                       "parent_space": space_dict.get(row[3], None),
4131
                                       "area": row[4],
4132
                                       "timezone": timezone_dict.get(row[5], None),
4133
                                       "is_input_counted": bool(row[6]),
4134
                                       "is_output_counted": bool(row[7]),
4135
                                       "contact": contact_dict.get(row[8], None),
4136
                                       "cost_center": cost_center_dict.get(row[9], None),
4137
                                       "latitude": row[10],
4138
                                       "longitude": row[11],
4139
                                       "description": row[12]}
4140
                    result['children'].append(children_result)
4141
                meta_result['children'] = result['children']
4142
            query = (" SELECT c.id, c.name, c.uuid "
4143
                     " FROM tbl_spaces s, tbl_spaces_commands sc, tbl_commands c "
4144
                     " WHERE sc.space_id = s.id AND c.id = sc.command_id AND s.id = %s "
4145
                     " ORDER BY c.id ")
4146
            cursor.execute(query, (id_,))
4147
            rows = cursor.fetchall()
4148
4149
            command_result = list()
4150
            if rows is not None and len(rows) > 0:
4151
                for row in rows:
4152
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
4153
                    command_result.append(result)
4154
                meta_result['commands'] = command_result
4155
            query = (" SELECT id, name, uuid "
4156
                     " FROM tbl_energy_categories ")
4157
            cursor.execute(query)
4158
            rows_energy_categories = cursor.fetchall()
4159
4160
            energy_category_dict = dict()
4161
            if rows_energy_categories is not None and len(rows_energy_categories) > 0:
4162
                for row in rows_energy_categories:
4163
                    energy_category_dict[row[0]] = {"id": row[0],
4164
                                                    "name": row[1],
4165
                                                    "uuid": row[2]}
4166
4167
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
4168
                     " FROM tbl_spaces s, tbl_spaces_meters sm, tbl_meters m "
4169
                     " WHERE sm.space_id = s.id AND m.id = sm.meter_id AND s.id = %s "
4170
                     " ORDER BY m.id ")
4171
            cursor.execute(query, (id_,))
4172
            rows = cursor.fetchall()
4173
4174
            meter_result = list()
4175
            if rows is not None and len(rows) > 0:
4176
                for row in rows:
4177
                    result = {"id": row[0], "name": row[1], "uuid": row[2],
4178
                              "energy_category": energy_category_dict.get(row[3], None)}
4179
                    meter_result.append(result)
4180
                meta_result['meters'] = meter_result
4181
            query = (" SELECT id, name, uuid "
4182
                     " FROM tbl_energy_categories ")
4183
            cursor.execute(query)
4184
            rows_energy_categories = cursor.fetchall()
4185
4186
            energy_category_dict = dict()
4187
            if rows_energy_categories is not None and len(rows_energy_categories) > 0:
4188
                for row in rows_energy_categories:
4189
                    energy_category_dict[row[0]] = {"id": row[0],
4190
                                                    "name": row[1],
4191
                                                    "uuid": row[2]}
4192
4193
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
4194
                     " FROM tbl_spaces s, tbl_spaces_offline_meters sm, tbl_offline_meters m "
4195
                     " WHERE sm.space_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
4196
                     " ORDER BY m.id ")
4197
            cursor.execute(query, (id_,))
4198
            rows = cursor.fetchall()
4199
4200
            offlinemeter_result = list()
4201
            if rows is not None and len(rows) > 0:
4202
                for row in rows:
4203
                    result = {"id": row[0], "name": row[1], "uuid": row[2],
4204
                              "energy_category": energy_category_dict.get(row[3], None)}
4205
                    offlinemeter_result.append(result)
4206
                meta_result['offline_meters'] = offlinemeter_result
4207
            query = (" SELECT id, name, uuid "
4208
                     " FROM tbl_energy_categories ")
4209
            cursor.execute(query)
4210
            rows_energy_categories = cursor.fetchall()
4211
4212
            energy_category_dict = dict()
4213
            if rows_energy_categories is not None and len(rows_energy_categories) > 0:
4214
                for row in rows_energy_categories:
4215
                    energy_category_dict[row[0]] = {"id": row[0],
4216
                                                    "name": row[1],
4217
                                                    "uuid": row[2]}
4218
4219
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
4220
                     " FROM tbl_spaces s, tbl_spaces_virtual_meters sm, tbl_virtual_meters m "
4221
                     " WHERE sm.space_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
4222
                     " ORDER BY m.id ")
4223
            cursor.execute(query, (id_,))
4224
            rows = cursor.fetchall()
4225
4226
            virtualmeter_result = list()
4227
            if rows is not None and len(rows) > 0:
4228
                for row in rows:
4229
                    result = {"id": row[0], "name": row[1], "uuid": row[2],
4230
                              "energy_category": energy_category_dict.get(row[3], None)}
4231
                    virtualmeter_result.append(result)
4232
                meta_result['virtual_meters'] = virtualmeter_result
4233
            query = (" SELECT sf.id, sf.name, sf.uuid "
4234
                     " FROM tbl_spaces sp, tbl_spaces_shopfloors ss, tbl_shopfloors sf "
4235
                     " WHERE ss.space_id = sp.id AND sf.id = ss.shopfloor_id AND sp.id = %s "
4236
                     " ORDER BY sf.id ")
4237
            cursor.execute(query, (id_,))
4238
            rows = cursor.fetchall()
4239
4240
            shopfloor_result = list()
4241
            if rows is not None and len(rows) > 0:
4242
                for row in rows:
4243
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
4244
                    shopfloor_result.append(result)
4245
                meta_result['shopfloors'] = shopfloor_result
4246
            query = (" SELECT e.id, e.name, e.uuid "
4247
                     " FROM tbl_spaces s, tbl_spaces_combined_equipments se, tbl_combined_equipments e "
4248
                     " WHERE se.space_id = s.id AND e.id = se.combined_equipment_id AND s.id = %s "
4249
                     " ORDER BY e.id ")
4250
            cursor.execute(query, (id_,))
4251
            rows = cursor.fetchall()
4252
4253
            combinedequipment_result = list()
4254
            if rows is not None and len(rows) > 0:
4255
                for row in rows:
4256
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
4257
                    combinedequipment_result.append(result)
4258
                meta_result['combined_equipments'] = combinedequipment_result
4259
            query = (" SELECT e.id, e.name, e.uuid "
4260
                     " FROM tbl_spaces s, tbl_spaces_equipments se, tbl_equipments e "
4261
                     " WHERE se.space_id = s.id AND e.id = se.equipment_id AND s.id = %s "
4262
                     " ORDER BY e.id ")
4263
            cursor.execute(query, (id_,))
4264
            rows = cursor.fetchall()
4265
4266
            equipment_result = list()
4267
            if rows is not None and len(rows) > 0:
4268
                for row in rows:
4269
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
4270
                    equipment_result.append(result)
4271
                meta_result['equipments'] = equipment_result
4272
            query = (" SELECT id, name, uuid "
4273
                     " FROM tbl_data_sources ")
4274
            cursor.execute(query)
4275
            rows_data_sources = cursor.fetchall()
4276
4277
            data_source_dict = dict()
4278
            if rows_data_sources is not None and len(rows_data_sources) > 0:
4279
                for row in rows_data_sources:
4280
                    data_source_dict[row[0]] = {"id": row[0],
4281
                                                "name": row[1],
4282
                                                "uuid": row[2]}
4283
4284
            query = (" SELECT p.id, p.name, p.data_source_id "
4285
                     " FROM tbl_spaces s, tbl_spaces_points sp, tbl_points p "
4286
                     " WHERE sp.space_id = s.id AND p.id = sp.point_id AND s.id = %s "
4287
                     " ORDER BY p.id ")
4288
            cursor.execute(query, (id_,))
4289
            rows = cursor.fetchall()
4290
4291
            point_result = list()
4292
            if rows is not None and len(rows) > 0:
4293
                for row in rows:
4294
                    result = {"id": row[0], "name": row[1], "data_source": data_source_dict.get(row[2], None)}
4295
                    point_result.append(result)
4296
                meta_result['points'] = point_result
4297
            query = (" SELECT se.id, se.name, se.uuid "
4298
                     " FROM tbl_spaces sp, tbl_spaces_sensors ss, tbl_sensors se "
4299
                     " WHERE ss.space_id = sp.id AND se.id = ss.sensor_id AND sp.id = %s "
4300
                     " ORDER BY se.id ")
4301
            cursor.execute(query, (id_,))
4302
            rows = cursor.fetchall()
4303
4304
            sensor_result = list()
4305
            if rows is not None and len(rows) > 0:
4306
                for row in rows:
4307
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
4308
                    sensor_result.append(result)
4309
                meta_result['sensors'] = sensor_result
4310
            query = (" SELECT t.id, t.name, t.uuid "
4311
                     " FROM tbl_spaces s, tbl_spaces_tenants st, tbl_tenants t "
4312
                     " WHERE st.space_id = s.id AND t.id = st.tenant_id AND s.id = %s "
4313
                     " ORDER BY t.id ")
4314
            cursor.execute(query, (id_,))
4315
            rows = cursor.fetchall()
4316
4317
            tenant_result = list()
4318
            if rows is not None and len(rows) > 0:
4319
                for row in rows:
4320
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
4321
                    tenant_result.append(result)
4322
                meta_result['tenants'] = tenant_result
4323
            query = (" SELECT t.id, t.name, t.uuid "
4324
                     " FROM tbl_spaces s, tbl_spaces_stores st, tbl_stores t "
4325
                     " WHERE st.space_id = s.id AND t.id = st.store_id AND s.id = %s "
4326
                     " ORDER BY t.id ")
4327
            cursor.execute(query, (id_,))
4328
            rows = cursor.fetchall()
4329
4330
            store_result = list()
4331
            if rows is not None and len(rows) > 0:
4332
                for row in rows:
4333
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
4334
                    store_result.append(result)
4335
                meta_result['stores'] = store_result
4336
            query = (" SELECT wc.id, wc.name, wc.description "
4337
                     " FROM tbl_spaces s, tbl_spaces_working_calendars swc, tbl_working_calendars wc "
4338
                     " WHERE swc.space_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
4339
                     " ORDER BY wc.id ")
4340
            cursor.execute(query, (id_,))
4341
            rows = cursor.fetchall()
4342
4343
            workingcalendar_result = list()
4344
            if rows is not None and len(rows) > 0:
4345
                for row in rows:
4346
                    result = {"id": row[0], "name": row[1], "description": row[2]}
4347
                    workingcalendar_result.append(result)
4348
                meta_result['working_calendars'] = workingcalendar_result
4349
        cursor.close()
4350
        cnx.close()
4351
        resp.text = json.dumps(meta_result)
4352
4353
4354
class SpaceImport:
4355
    def __init__(self):
4356
        """Initializes Class"""
4357
        pass
4358
4359
    @staticmethod
4360
    def on_options(req, resp):
4361
        resp.status = falcon.HTTP_200
4362
4363
    @staticmethod
4364
    @user_logger
4365
    def on_post(req, resp):
4366
        """Handles POST requests"""
4367
        admin_control(req)
4368
        try:
4369
            raw_json = req.stream.read().decode('utf-8')
4370
            new_values = json.loads(raw_json)
4371
        except Exception as ex:
4372
            raise falcon.HTTPError(status=falcon.HTTP_400,
4373
                                   title='API.BAD_REQUEST',
4374
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4375
4376
        if 'name' not in new_values.keys() or \
4377
                not isinstance(new_values['name'], str) or \
4378
                len(str.strip(new_values['name'])) == 0:
4379
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4380
                                   description='API.INVALID_SPACE_NAME')
4381
        name = str.strip(new_values['name'])
4382
4383
        if 'id' in new_values['parent_space_id'].keys():
4384
            if new_values['parent_space_id']['id'] <= 0:
4385
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4386
                                       description='API.INVALID_PARENT_SPACE_ID')
4387
            parent_space_id = new_values['parent_space_id']['id']
4388
        else:
4389
            parent_space_id = None
4390
4391
        if 'area' not in new_values.keys() or \
4392
                not (isinstance(new_values['area'], float) or
4393
                     isinstance(new_values['area'], int)) or \
4394
                new_values['area'] <= 0.0:
4395
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4396
                                   description='API.INVALID_AREA_VALUE')
4397
        area = new_values['area']
4398
4399
        if 'id' not in new_values['timezone'].keys() or \
4400
                not isinstance(new_values['timezone']['id'], int) or \
4401
                new_values['timezone']['id'] <= 0:
4402
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4403
                                   description='API.INVALID_TIMEZONE_ID')
4404
        timezone_id = new_values['timezone']['id']
4405
4406
        if 'is_input_counted' not in new_values.keys() or \
4407
                not isinstance(new_values['is_input_counted'], bool):
4408
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4409
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
4410
        is_input_counted = new_values['is_input_counted']
4411
4412
        if 'is_output_counted' not in new_values.keys() or \
4413
                not isinstance(new_values['is_output_counted'], bool):
4414
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4415
                                   description='API.INVALID_IS_OUTPUT_COUNTED_VALUE')
4416
        is_output_counted = new_values['is_output_counted']
4417
4418
        if 'id' in new_values['contact'].keys():
4419
            if new_values['contact']['id'] <= 0:
4420
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4421
                                       description='API.INVALID_CONTACT_ID')
4422
            contact_id = new_values['contact']['id']
4423
        else:
4424
            contact_id = None
4425
4426
        if 'id' in new_values['cost_center'].keys():
4427
            if new_values['cost_center']['id'] <= 0:
4428
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4429
                                       description='API.INVALID_COST_CENTER_ID')
4430
            cost_center_id = new_values['cost_center']['id']
4431
        else:
4432
            cost_center_id = None
4433
4434 View Code Duplication
        if 'latitude' in new_values.keys() and new_values['latitude'] is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4435
            if not (isinstance(new_values['latitude'], float) or
4436
                    isinstance(new_values['latitude'], int)) or \
4437
                    new_values['latitude'] < -90.0 or \
4438
                    new_values['latitude'] > 90.0:
4439
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4440
                                       description='API.INVALID_LATITUDE_VALUE')
4441
            latitude = new_values['latitude']
4442
        else:
4443
            latitude = None
4444
4445 View Code Duplication
        if 'longitude' in new_values.keys() and new_values['longitude'] is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4446
            if not (isinstance(new_values['longitude'], float) or
4447
                    isinstance(new_values['longitude'], int)) or \
4448
                    new_values['longitude'] < -180.0 or \
4449
                    new_values['longitude'] > 180.0:
4450
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4451
                                       description='API.INVALID_LONGITUDE_VALUE')
4452
            longitude = new_values['longitude']
4453
        else:
4454
            longitude = None
4455
4456
        if 'description' in new_values.keys() and \
4457
                new_values['description'] is not None and \
4458
                len(str(new_values['description'])) > 0:
4459
            description = str.strip(new_values['description'])
4460
        else:
4461
            description = None
4462
4463
        cnx = mysql.connector.connect(**config.myems_system_db)
4464
        cursor = cnx.cursor()
4465
4466
        cursor.execute(" SELECT name "
4467
                       " FROM tbl_spaces "
4468
                       " WHERE name = %s ", (name,))
4469
        if cursor.fetchone() is not None:
4470
            cursor.close()
4471
            cnx.close()
4472
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4473
                                   description='API.SPACE_NAME_IS_ALREADY_IN_USE')
4474
4475 View Code Duplication
        if parent_space_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4476
            cursor.execute(" SELECT name "
4477
                           " FROM tbl_spaces "
4478
                           " WHERE id = %s ",
4479
                           (new_values['parent_space_id']['id'],))
4480
            row = cursor.fetchone()
4481
            if row is None:
4482
                cursor.close()
4483
                cnx.close()
4484
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4485
                                       description='API.PARENT_SPACE_NOT_FOUND')
4486
4487
        cursor.execute(" SELECT name "
4488
                       " FROM tbl_timezones "
4489
                       " WHERE id = %s ",
4490
                       (new_values['timezone']['id'],))
4491
        if cursor.fetchone() is None:
4492
            cursor.close()
4493
            cnx.close()
4494
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4495
                                   description='API.TIMEZONE_NOT_FOUND')
4496 View Code Duplication
        if contact_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4497
            cursor.execute(" SELECT name "
4498
                           " FROM tbl_contacts "
4499
                           " WHERE id = %s ",
4500
                           (new_values['contact']['id'],))
4501
            row = cursor.fetchone()
4502
            if row is None:
4503
                cursor.close()
4504
                cnx.close()
4505
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4506
                                       description='API.CONTACT_NOT_FOUND')
4507
4508
        if cost_center_id is not None:
4509
            cursor.execute(" SELECT name "
4510
                           " FROM tbl_cost_centers "
4511
                           " WHERE id = %s ",
4512
                           (new_values['cost_center']['id'],))
4513
            row = cursor.fetchone()
4514
            if row is None:
4515
                cursor.close()
4516
                cnx.close()
4517
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4518
                                       description='API.COST_CENTER_NOT_FOUND')
4519
4520
        add_values = (" INSERT INTO tbl_spaces "
4521
                      "    (name, uuid, parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
4522
                      "     contact_id, cost_center_id, latitude, longitude, description) "
4523
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
4524
        cursor.execute(add_values, (name,
4525
                                    str(uuid.uuid4()),
4526
                                    parent_space_id,
4527
                                    area,
4528
                                    timezone_id,
4529
                                    is_input_counted,
4530
                                    is_output_counted,
4531
                                    contact_id,
4532
                                    cost_center_id,
4533
                                    latitude,
4534
                                    longitude,
4535
                                    description))
4536
        new_id = cursor.lastrowid
4537
        if new_values['commands'] is not None and len(new_values['commands']) > 0:
4538
            for command in new_values['commands']:
4539
                cursor.execute(" SELECT name "
4540
                               " FROM tbl_commands "
4541
                               " WHERE id = %s ", (command['id'],))
4542
                if cursor.fetchone() is None:
4543
                    cursor.close()
4544
                    cnx.close()
4545
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4546
                                           description='API.COMMAND_NOT_FOUND')
4547
4548
                query = (" SELECT id "
4549
                         " FROM tbl_spaces_commands "
4550
                         " WHERE space_id = %s AND command_id = %s")
4551
                cursor.execute(query, (new_id, command['id'],))
4552
                if cursor.fetchone() is not None:
4553
                    cursor.close()
4554
                    cnx.close()
4555
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4556
                                           description='API.SPACE_COMMAND_RELATION_EXISTS')
4557
4558
                add_row = (" INSERT INTO tbl_spaces_commands (space_id, command_id) "
4559
                           " VALUES (%s, %s) ")
4560
                cursor.execute(add_row, (new_id, command['id'],))
4561
        if new_values['meters'] is not None and len(new_values['meters']) > 0:
4562
            for meter in new_values['meters']:
4563
                cursor.execute(" SELECT name "
4564
                               " FROM tbl_meters "
4565
                               " WHERE id = %s ", (meter['id'],))
4566
                if cursor.fetchone() is None:
4567
                    cursor.close()
4568
                    cnx.close()
4569
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4570
                                           description='API.METER_NOT_FOUND')
4571
4572
                query = (" SELECT id "
4573
                         " FROM tbl_spaces_meters "
4574
                         " WHERE space_id = %s AND meter_id = %s")
4575
                cursor.execute(query, (new_id, meter['id'],))
4576
                if cursor.fetchone() is not None:
4577
                    cursor.close()
4578
                    cnx.close()
4579
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4580
                                           description='API.SPACE_METER_RELATION_EXISTS')
4581
4582
                add_row = (" INSERT INTO tbl_spaces_meters (space_id, meter_id) "
4583
                           " VALUES (%s, %s) ")
4584
                cursor.execute(add_row, (new_id, meter['id'],))
4585
        if new_values['offline_meters'] is not None and len(new_values['offline_meters']) > 0:
4586
            for offline_meter in new_values['offline_meters']:
4587
                cursor.execute(" SELECT name "
4588
                               " FROM tbl_offline_meters "
4589
                               " WHERE id = %s ", (offline_meter['id'],))
4590
                if cursor.fetchone() is None:
4591
                    cursor.close()
4592
                    cnx.close()
4593
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4594
                                           description='API.OFFLINE_METER_NOT_FOUND')
4595
4596
                query = (" SELECT id "
4597
                         " FROM tbl_spaces_offline_meters "
4598
                         " WHERE space_id = %s AND offline_meter_id = %s")
4599
                cursor.execute(query, (new_id, offline_meter['id'],))
4600
                if cursor.fetchone() is not None:
4601
                    cursor.close()
4602
                    cnx.close()
4603
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4604
                                           description='API.SPACE_OFFLINE_METER_RELATION_EXISTS')
4605
4606
                add_row = (" INSERT INTO tbl_spaces_offline_meters (space_id, offline_meter_id) "
4607
                           " VALUES (%s, %s) ")
4608
                cursor.execute(add_row, (new_id, offline_meter['id'],))
4609
        if new_values['virtual_meters'] is not None and len(new_values['virtual_meters']) > 0:
4610
            for virtual_meter in new_values['virtual_meters']:
4611
                cursor.execute(" SELECT name "
4612
                               " FROM tbl_virtual_meters "
4613
                               " WHERE id = %s ", (virtual_meter['id'],))
4614
                if cursor.fetchone() is None:
4615
                    cursor.close()
4616
                    cnx.close()
4617
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4618
                                           description='API.VIRTUAL_METER_NOT_FOUND')
4619
4620
                query = (" SELECT id "
4621
                         " FROM tbl_spaces_virtual_meters "
4622
                         " WHERE space_id = %s AND virtual_meter_id = %s")
4623
                cursor.execute(query, (new_id, virtual_meter['id'],))
4624
                if cursor.fetchone() is not None:
4625
                    cursor.close()
4626
                    cnx.close()
4627
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4628
                                           description='API.SPACE_VIRTUAL_METER_RELATION_EXISTS')
4629
4630
                add_row = (" INSERT INTO tbl_spaces_virtual_meters (space_id, virtual_meter_id) "
4631
                           " VALUES (%s, %s) ")
4632
                cursor.execute(add_row, (new_id, virtual_meter['id'],))
4633
        if new_values['shopfloors'] is not None and len(new_values['shopfloors']) > 0:
4634
            for shopfloor in new_values['shopfloors']:
4635
                cursor.execute(" SELECT name "
4636
                               " FROM tbl_shopfloors "
4637
                               " WHERE id = %s ", (shopfloor['id'],))
4638
                if cursor.fetchone() is None:
4639
                    cursor.close()
4640
                    cnx.close()
4641
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4642
                                           description='API.SHOPFLOOR_NOT_FOUND')
4643
4644
                query = (" SELECT id "
4645
                         " FROM tbl_spaces_shopfloors "
4646
                         " WHERE space_id = %s AND shopfloor_id = %s")
4647
                cursor.execute(query, (new_id, shopfloor['id'],))
4648
                if cursor.fetchone() is not None:
4649
                    cursor.close()
4650
                    cnx.close()
4651
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4652
                                           description='API.SPACE_SHOPFLOOR_RELATION_EXISTS')
4653
4654
                add_row = (" INSERT INTO tbl_spaces_shopfloors (space_id, shopfloor_id) "
4655
                           " VALUES (%s, %s) ")
4656
                cursor.execute(add_row, (new_id, shopfloor['id'],))
4657
        if new_values['combined_equipments'] is not None and len(new_values['combined_equipments']) > 0:
4658
            for combined_equipment in new_values['combined_equipments']:
4659
                cursor.execute(" SELECT name "
4660
                               " FROM tbl_combined_equipments "
4661
                               " WHERE id = %s ", (combined_equipment['id'],))
4662
                if cursor.fetchone() is None:
4663
                    cursor.close()
4664
                    cnx.close()
4665
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4666
                                           description='API.COMBINED_EQUIPMENT_NOT_FOUND')
4667
4668
                query = (" SELECT id "
4669
                         " FROM tbl_spaces_combined_equipments "
4670
                         " WHERE space_id = %s AND combined_equipment_id = %s")
4671
                cursor.execute(query, (new_id, combined_equipment['id'],))
4672
                if cursor.fetchone() is not None:
4673
                    cursor.close()
4674
                    cnx.close()
4675
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4676
                                           description='API.SPACE_COMBINED_EQUIPMENT_RELATION_EXISTS')
4677
4678
                add_row = (" INSERT INTO tbl_spaces_combined_equipments (space_id, combined_equipment_id) "
4679
                           " VALUES (%s, %s) ")
4680
                cursor.execute(add_row, (new_id, combined_equipment['id'],))
4681
        if new_values['equipments'] is not None and len(new_values['equipments']) > 0:
4682
            for equipment in new_values['equipments']:
4683
                cursor.execute(" SELECT name "
4684
                               " FROM tbl_equipments "
4685
                               " WHERE id = %s ", (equipment['id'],))
4686
                if cursor.fetchone() is None:
4687
                    cursor.close()
4688
                    cnx.close()
4689
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4690
                                           description='API.EQUIPMENT_NOT_FOUND')
4691
4692
                query = (" SELECT id "
4693
                         " FROM tbl_spaces_equipments "
4694
                         " WHERE space_id = %s AND equipment_id = %s")
4695
                cursor.execute(query, (new_id, equipment['id'],))
4696
                if cursor.fetchone() is not None:
4697
                    cursor.close()
4698
                    cnx.close()
4699
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4700
                                           description='API.SPACE_EQUIPMENT_RELATION_EXISTS')
4701
4702
                add_row = (" INSERT INTO tbl_spaces_equipments (space_id, equipment_id) "
4703
                           " VALUES (%s, %s) ")
4704
                cursor.execute(add_row, (new_id, equipment['id'],))
4705
        if new_values['points'] is not None and len(new_values['points']) > 0:
4706
            for point in new_values['points']:
4707
                cursor.execute(" SELECT name "
4708
                               " FROM tbl_points "
4709
                               " WHERE id = %s ", (point['id'],))
4710
                if cursor.fetchone() is None:
4711
                    cursor.close()
4712
                    cnx.close()
4713
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4714
                                           description='API.POINT_NOT_FOUND')
4715
4716
                query = (" SELECT id "
4717
                         " FROM tbl_spaces_points "
4718
                         " WHERE space_id = %s AND point_id = %s")
4719
                cursor.execute(query, (new_id, point['id'],))
4720
                if cursor.fetchone() is not None:
4721
                    cursor.close()
4722
                    cnx.close()
4723
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4724
                                           description='API.SPACE_POINT_RELATION_EXISTS')
4725
4726
                add_row = (" INSERT INTO tbl_spaces_points (space_id, point_id) "
4727
                           " VALUES (%s, %s) ")
4728
                cursor.execute(add_row, (new_id, point['id'],))
4729
        if new_values['sensors'] is not None and len(new_values['sensors']) > 0:
4730
            for sensor in new_values['sensors']:
4731
                cursor.execute(" SELECT name "
4732
                               " FROM tbl_sensors "
4733
                               " WHERE id = %s ", (sensor['id'],))
4734
                if cursor.fetchone() is None:
4735
                    cursor.close()
4736
                    cnx.close()
4737
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4738
                                           description='API.SENSOR_NOT_FOUND')
4739
4740
                query = (" SELECT id "
4741
                         " FROM tbl_spaces_sensors "
4742
                         " WHERE space_id = %s AND sensor_id = %s")
4743
                cursor.execute(query, (new_id, sensor['id'],))
4744
                if cursor.fetchone() is not None:
4745
                    cursor.close()
4746
                    cnx.close()
4747
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4748
                                           description='API.SPACE_SENSOR_RELATION_EXISTS')
4749
4750
                add_row = (" INSERT INTO tbl_spaces_sensors (space_id, sensor_id) "
4751
                           " VALUES (%s, %s) ")
4752
                cursor.execute(add_row, (new_id, sensor['id'],))
4753
        if new_values['tenants'] is not None and len(new_values['tenants']) > 0:
4754
            for tenant in new_values['tenants']:
4755
                cursor.execute(" SELECT name "
4756
                               " FROM tbl_tenants "
4757
                               " WHERE id = %s ", (tenant['id'],))
4758
                if cursor.fetchone() is None:
4759
                    cursor.close()
4760
                    cnx.close()
4761
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4762
                                           description='API.TENANT_NOT_FOUND')
4763
4764
                query = (" SELECT id "
4765
                         " FROM tbl_spaces_tenants "
4766
                         " WHERE space_id = %s AND tenant_id = %s")
4767
                cursor.execute(query, (new_id, tenant['id'],))
4768
                if cursor.fetchone() is not None:
4769
                    cursor.close()
4770
                    cnx.close()
4771
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4772
                                           description='API.SPACE_TENANT_RELATION_EXISTS')
4773
4774
                add_row = (" INSERT INTO tbl_spaces_tenants (space_id, tenant_id) "
4775
                           " VALUES (%s, %s) ")
4776
                cursor.execute(add_row, (new_id, tenant['id'],))
4777
        if new_values['stores'] is not None and len(new_values['stores']) > 0:
4778
            for store in new_values['stores']:
4779
                cursor.execute(" SELECT name "
4780
                               " FROM tbl_stores "
4781
                               " WHERE id = %s ", (store['id'],))
4782
                if cursor.fetchone() is None:
4783
                    cursor.close()
4784
                    cnx.close()
4785
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4786
                                           description='API.STORE_NOT_FOUND')
4787
4788
                query = (" SELECT id "
4789
                         " FROM tbl_spaces_stores "
4790
                         " WHERE space_id = %s AND store_id = %s")
4791
                cursor.execute(query, (new_id, store['id'],))
4792
                if cursor.fetchone() is not None:
4793
                    cursor.close()
4794
                    cnx.close()
4795
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4796
                                           description='API.SPACE_STORE_RELATION_EXISTS')
4797
4798
                add_row = (" INSERT INTO tbl_spaces_stores (space_id, store_id) "
4799
                           " VALUES (%s, %s) ")
4800
                cursor.execute(add_row, (new_id, store['id'],))
4801
            if new_values['working_calendars'] is not None and len(new_values['working_calendars']) > 0:
4802
                for working_calendar in new_values['working_calendars']:
4803
                    cursor.execute(" SELECT name "
4804
                                   " FROM tbl_working_calendars "
4805
                                   " WHERE id = %s ", (working_calendar['id'],))
4806
                    if cursor.fetchone() is None:
4807
                        cursor.close()
4808
                        cnx.close()
4809
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4810
                                               description='API.WORKING_CALENDAR_NOT_FOUND')
4811
4812
                    query = (" SELECT id "
4813
                             " FROM tbl_spaces_working_calendars "
4814
                             " WHERE space_id = %s AND working_calendar_id = %s")
4815
                    cursor.execute(query, (new_id, working_calendar['id'],))
4816
                    if cursor.fetchone() is not None:
4817
                        cursor.close()
4818
                        cnx.close()
4819
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4820
                                               description='API.SPACE_WORKING_CALENDAR_RELATION_EXISTS')
4821
4822
                    add_row = (" INSERT INTO tbl_spaces_working_calendars (space_id, working_calendar_id) "
4823
                               " VALUES (%s, %s) ")
4824
                    cursor.execute(add_row, (new_id, working_calendar['id'],))
4825
        cnx.commit()
4826
        cursor.close()
4827
        cnx.close()
4828
4829
        resp.status = falcon.HTTP_201
4830
        resp.location = '/spaces/' + str(new_id)
4831
4832
4833
class SpaceClone:
4834
    def __init__(self):
4835
        """Initializes Class"""
4836
        pass
4837
4838
    @staticmethod
4839
    def on_options(req, resp, id_):
4840
        resp.status = falcon.HTTP_200
4841
4842
    @staticmethod
4843
    @user_logger
4844
    def on_post(req, resp, id_):
4845
        # check parameters
4846
        if 'API-KEY' not in req.headers or \
4847
                not isinstance(req.headers['API-KEY'], str) or \
4848
                len(str.strip(req.headers['API-KEY'])) == 0:
4849
            access_control(req)
4850
        else:
4851
            api_key_control(req)
4852
        if not id_.isdigit() or int(id_) <= 0:
4853
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4854
                                   description='API.INVALID_SPACE_ID')
4855
        if int(id_) == 1:
4856
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4857
                                   description='API.THIS_SPACE_CANNOT_BE_CLONED')
4858
        # connect the database
4859
        cnx = mysql.connector.connect(**config.myems_system_db)
4860
        cursor = cnx.cursor()
4861
        # query all spaces
4862
        query = (" SELECT id, name, uuid "
4863
                 " FROM tbl_spaces ")
4864
        cursor.execute(query)
4865
        rows_spaces = cursor.fetchall()
4866
4867
        space_dict = dict()
4868
        if rows_spaces is not None and len(rows_spaces) > 0:
4869
            for row in rows_spaces:
4870
                space_dict[row[0]] = {"id": row[0],
4871
                                      "name": row[1],
4872
                                      "uuid": row[2]}
4873
        # query all timezones
4874
        query = (" SELECT id, name, utc_offset "
4875
                 " FROM tbl_timezones ")
4876
        cursor.execute(query)
4877
        rows_timezones = cursor.fetchall()
4878
4879
        timezone_dict = dict()
4880
        if rows_timezones is not None and len(rows_timezones) > 0:
4881
            for row in rows_timezones:
4882
                timezone_dict[row[0]] = {"id": row[0],
4883
                                         "name": row[1],
4884
                                         "utc_offset": row[2]}
4885
        # query all contacts
4886
        query = (" SELECT id, name, uuid "
4887
                 " FROM tbl_contacts ")
4888
        cursor.execute(query)
4889
        rows_contacts = cursor.fetchall()
4890
4891
        contact_dict = dict()
4892
        if rows_contacts is not None and len(rows_contacts) > 0:
4893
            for row in rows_contacts:
4894
                contact_dict[row[0]] = {"id": row[0],
4895
                                        "name": row[1],
4896
                                        "uuid": row[2]}
4897
        # query all cost centers
4898
        query = (" SELECT id, name, uuid "
4899
                 " FROM tbl_cost_centers ")
4900
        cursor.execute(query)
4901
        rows_cost_centers = cursor.fetchall()
4902
4903
        cost_center_dict = dict()
4904
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
4905
            for row in rows_cost_centers:
4906
                cost_center_dict[row[0]] = {"id": row[0],
4907
                                            "name": row[1],
4908
                                            "uuid": row[2]}
4909
4910
        # query the source space
4911
        query = (" SELECT id, name, uuid, "
4912
                 "        parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
4913
                 "        contact_id, cost_center_id, latitude, longitude, description "
4914
                 " FROM tbl_spaces "
4915
                 " WHERE id = %s ")
4916
        cursor.execute(query, (id_,))
4917
        row = cursor.fetchone()
4918
4919
        if row is None:
4920
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4921
                                   description='API.SPACE_NOT_FOUND')
4922
        else:
4923
            # save the source space properties to meta_result
4924
            meta_result = {"id": row[0],
4925
                           "name": row[1],
4926
                           "uuid": row[2],
4927
                           "parent_space_id": row[3],
4928
                           "area": row[4],
4929
                           "timezone_id": row[5],
4930
                           "is_input_counted": bool(row[6]),
4931
                           "is_output_counted": bool(row[7]),
4932
                           "contact_id": row[8],
4933
                           "cost_center_id": row[9],
4934
                           "latitude": row[10],
4935
                           "longitude": row[11],
4936
                           "description": row[12],
4937
                           "commands": None,
4938
                           "meters": None,
4939
                           "offline_meters": None,
4940
                           "virtual_meters": None,
4941
                           "shopfloors": None,
4942
                           "combined_equipments": None,
4943
                           "equipments": None,
4944
                           "points": None,
4945
                           "sensors": None,
4946
                           "tenants": None,
4947
                           "stores": None,
4948
                           "working_calendars": None
4949
                           }
4950
4951
            # query associated commands
4952
            query = (" SELECT c.id, c.name "
4953
                     " FROM tbl_spaces s, tbl_spaces_commands sc, tbl_commands c "
4954
                     " WHERE sc.space_id = s.id AND c.id = sc.command_id AND s.id = %s "
4955
                     " ORDER BY c.id ")
4956
            cursor.execute(query, (id_,))
4957
            rows = cursor.fetchall()
4958
4959
            command_list = list()
4960
            if rows is not None and len(rows) > 0:
4961
                for row in rows:
4962
                    result = {"id": row[0], "name": row[1]}
4963
                    command_list.append(result)
4964
                meta_result['commands'] = command_list
4965
4966
            # query associated meters
4967
            query = (" SELECT m.id, m.name "
4968
                     " FROM tbl_spaces s, tbl_spaces_meters sm, tbl_meters m "
4969
                     " WHERE sm.space_id = s.id AND m.id = sm.meter_id AND s.id = %s "
4970
                     " ORDER BY m.id ")
4971
            cursor.execute(query, (id_,))
4972
            rows = cursor.fetchall()
4973
4974
            meter_list = list()
4975
            if rows is not None and len(rows) > 0:
4976
                for row in rows:
4977
                    result = {"id": row[0], "name": row[1]}
4978
                    meter_list.append(result)
4979
                meta_result['meters'] = meter_list
4980
4981
            # query associated offline meters
4982
            query = (" SELECT m.id, m.name "
4983
                     " FROM tbl_spaces s, tbl_spaces_offline_meters sm, tbl_offline_meters m "
4984
                     " WHERE sm.space_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
4985
                     " ORDER BY m.id ")
4986
            cursor.execute(query, (id_,))
4987
            rows = cursor.fetchall()
4988
4989
            offline_meter_list = list()
4990
            if rows is not None and len(rows) > 0:
4991
                for row in rows:
4992
                    result = {"id": row[0], "name": row[1]}
4993
                    offline_meter_list.append(result)
4994
                meta_result['offline_meters'] = offline_meter_list
4995
4996
            # query associated virtual meters
4997
            query = (" SELECT m.id, m.name "
4998
                     " FROM tbl_spaces s, tbl_spaces_virtual_meters sm, tbl_virtual_meters m "
4999
                     " WHERE sm.space_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
5000
                     " ORDER BY m.id ")
5001
            cursor.execute(query, (id_,))
5002
            rows = cursor.fetchall()
5003
5004
            virtual_meter_list = list()
5005
            if rows is not None and len(rows) > 0:
5006
                for row in rows:
5007
                    result = {"id": row[0], "name": row[1]}
5008
                    virtual_meter_list.append(result)
5009
                meta_result['virtual_meters'] = virtual_meter_list
5010
5011
            # query associated shopfloors
5012
            query = (" SELECT sf.id, sf.name "
5013
                     " FROM tbl_spaces sp, tbl_spaces_shopfloors ss, tbl_shopfloors sf "
5014
                     " WHERE ss.space_id = sp.id AND sf.id = ss.shopfloor_id AND sp.id = %s "
5015
                     " ORDER BY sf.id ")
5016
            cursor.execute(query, (id_,))
5017
            rows = cursor.fetchall()
5018
5019
            shopfloor_list = list()
5020
            if rows is not None and len(rows) > 0:
5021
                for row in rows:
5022
                    result = {"id": row[0], "name": row[1]}
5023
                    shopfloor_list.append(result)
5024
                meta_result['shopfloors'] = shopfloor_list
5025
5026
            # query associated combined equipments
5027
            query = (" SELECT e.id, e.name "
5028
                     " FROM tbl_spaces s, tbl_spaces_combined_equipments se, tbl_combined_equipments e "
5029
                     " WHERE se.space_id = s.id AND e.id = se.combined_equipment_id AND s.id = %s "
5030
                     " ORDER BY e.id ")
5031
            cursor.execute(query, (id_,))
5032
            rows = cursor.fetchall()
5033
5034
            combined_equipment_list = list()
5035
            if rows is not None and len(rows) > 0:
5036
                for row in rows:
5037
                    result = {"id": row[0], "name": row[1]}
5038
                    combined_equipment_list.append(result)
5039
                meta_result['combined_equipments'] = combined_equipment_list
5040
5041
            # query associated equipments
5042
            query = (" SELECT e.id, e.name "
5043
                     " FROM tbl_spaces s, tbl_spaces_equipments se, tbl_equipments e "
5044
                     " WHERE se.space_id = s.id AND e.id = se.equipment_id AND s.id = %s "
5045
                     " ORDER BY e.id ")
5046
            cursor.execute(query, (id_,))
5047
            rows = cursor.fetchall()
5048
5049
            equipment_list = list()
5050
            if rows is not None and len(rows) > 0:
5051
                for row in rows:
5052
                    result = {"id": row[0], "name": row[1]}
5053
                    equipment_list.append(result)
5054
                meta_result['equipments'] = equipment_list
5055
5056
            # query associated points
5057
            query = (" SELECT p.id, p.name "
5058
                     " FROM tbl_spaces s, tbl_spaces_points sp, tbl_points p "
5059
                     " WHERE sp.space_id = s.id AND p.id = sp.point_id AND s.id = %s "
5060
                     " ORDER BY p.id ")
5061
            cursor.execute(query, (id_,))
5062
            rows = cursor.fetchall()
5063
5064
            point_result = list()
5065
            if rows is not None and len(rows) > 0:
5066
                for row in rows:
5067
                    result = {"id": row[0], "name": row[1]}
5068
                    point_result.append(result)
5069
                meta_result['points'] = point_result
5070
5071
            # query associated sensors
5072
            query = (" SELECT se.id, se.name "
5073
                     " FROM tbl_spaces sp, tbl_spaces_sensors ss, tbl_sensors se "
5074
                     " WHERE ss.space_id = sp.id AND se.id = ss.sensor_id AND sp.id = %s "
5075
                     " ORDER BY se.id ")
5076
            cursor.execute(query, (id_,))
5077
            rows = cursor.fetchall()
5078
5079
            sensor_list = list()
5080
            if rows is not None and len(rows) > 0:
5081
                for row in rows:
5082
                    result = {"id": row[0], "name": row[1]}
5083
                    sensor_list.append(result)
5084
                meta_result['sensors'] = sensor_list
5085
5086
            # query associated tenants
5087
            query = (" SELECT t.id, t.name "
5088
                     " FROM tbl_spaces s, tbl_spaces_tenants st, tbl_tenants t "
5089
                     " WHERE st.space_id = s.id AND t.id = st.tenant_id AND s.id = %s "
5090
                     " ORDER BY t.id ")
5091
            cursor.execute(query, (id_,))
5092
            rows = cursor.fetchall()
5093
5094
            tenant_list = list()
5095
            if rows is not None and len(rows) > 0:
5096
                for row in rows:
5097
                    result = {"id": row[0], "name": row[1]}
5098
                    tenant_list.append(result)
5099
                meta_result['tenants'] = tenant_list
5100
5101
            # query associated stores
5102
            query = (" SELECT t.id, t.name "
5103
                     " FROM tbl_spaces s, tbl_spaces_stores st, tbl_stores t "
5104
                     " WHERE st.space_id = s.id AND t.id = st.store_id AND s.id = %s "
5105
                     " ORDER BY t.id ")
5106
            cursor.execute(query, (id_,))
5107
            rows = cursor.fetchall()
5108
5109
            store_list = list()
5110
            if rows is not None and len(rows) > 0:
5111
                for row in rows:
5112
                    result = {"id": row[0], "name": row[1]}
5113
                    store_list.append(result)
5114
                meta_result['stores'] = store_list
5115
5116
            # query associated working calendars
5117
            query = (" SELECT wc.id, wc.name "
5118
                     " FROM tbl_spaces s, tbl_spaces_working_calendars swc, tbl_working_calendars wc "
5119
                     " WHERE swc.space_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
5120
                     " ORDER BY wc.id ")
5121
            cursor.execute(query, (id_,))
5122
            rows = cursor.fetchall()
5123
5124
            working_calendar_list = list()
5125
            if rows is not None and len(rows) > 0:
5126
                for row in rows:
5127
                    result = {"id": row[0], "name": row[1]}
5128
                    working_calendar_list.append(result)
5129
                meta_result['working_calendars'] = working_calendar_list
5130
5131
            # generate name for new space
5132
            timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
5133
            if config.utc_offset[0] == '-':
5134
                timezone_offset = -timezone_offset
5135
            new_name = (str.strip(meta_result['name']) +
5136
                        (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds'))
5137
5138
            # save new space to database
5139
            add_values = (" INSERT INTO tbl_spaces "
5140
                          "    (name, uuid, parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
5141
                          "     contact_id, cost_center_id, latitude, longitude, description) "
5142
                          " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
5143
            cursor.execute(add_values, (new_name,
5144
                                        str(uuid.uuid4()),
5145
                                        meta_result['parent_space_id'],
5146
                                        meta_result['area'],
5147
                                        meta_result['timezone_id'],
5148
                                        meta_result['is_input_counted'],
5149
                                        meta_result['is_output_counted'],
5150
                                        meta_result['contact_id'],
5151
                                        meta_result['cost_center_id'],
5152
                                        meta_result['latitude'],
5153
                                        meta_result['longitude'],
5154
                                        meta_result['description']))
5155
            new_id = cursor.lastrowid
5156
5157
            # associate commands with new space
5158
            if meta_result['commands'] is not None and len(meta_result['commands']) > 0:
5159
                for command in meta_result['commands']:
5160
                    cursor.execute(" SELECT name "
5161
                                   " FROM tbl_commands "
5162
                                   " WHERE id = %s ", (command['id'],))
5163
                    if cursor.fetchone() is None:
5164
                        cursor.close()
5165
                        cnx.close()
5166
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5167
                                               description='API.COMMAND_NOT_FOUND')
5168
5169
                    query = (" SELECT id "
5170
                             " FROM tbl_spaces_commands "
5171
                             " WHERE space_id = %s AND command_id = %s")
5172
                    cursor.execute(query, (new_id, command['id'],))
5173
                    if cursor.fetchone() is not None:
5174
                        cursor.close()
5175
                        cnx.close()
5176
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5177
                                               description='API.SPACE_COMMAND_RELATION_EXISTS')
5178
5179
                    add_row = (" INSERT INTO tbl_spaces_commands (space_id, command_id) "
5180
                               " VALUES (%s, %s) ")
5181
                    cursor.execute(add_row, (new_id, command['id'],))
5182
5183
            # associate meters with new space
5184
            if meta_result['meters'] is not None and len(meta_result['meters']) > 0:
5185
                for meter in meta_result['meters']:
5186
                    cursor.execute(" SELECT name "
5187
                                   " FROM tbl_meters "
5188
                                   " WHERE id = %s ", (meter['id'],))
5189
                    if cursor.fetchone() is None:
5190
                        cursor.close()
5191
                        cnx.close()
5192
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5193
                                               description='API.METER_NOT_FOUND')
5194
5195
                    query = (" SELECT id "
5196
                             " FROM tbl_spaces_meters "
5197
                             " WHERE space_id = %s AND meter_id = %s")
5198
                    cursor.execute(query, (new_id, meter['id'],))
5199
                    if cursor.fetchone() is not None:
5200
                        cursor.close()
5201
                        cnx.close()
5202
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5203
                                               description='API.SPACE_METER_RELATION_EXISTS')
5204
5205
                    add_row = (" INSERT INTO tbl_spaces_meters (space_id, meter_id) "
5206
                               " VALUES (%s, %s) ")
5207
                    cursor.execute(add_row, (new_id, meter['id'],))
5208
5209
            # associate offline meters with new space
5210
            if meta_result['offline_meters'] is not None and len(meta_result['offline_meters']) > 0:
5211
                for offline_meter in meta_result['offline_meters']:
5212
                    cursor.execute(" SELECT name "
5213
                                   " FROM tbl_offline_meters "
5214
                                   " WHERE id = %s ", (offline_meter['id'],))
5215
                    if cursor.fetchone() is None:
5216
                        cursor.close()
5217
                        cnx.close()
5218
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5219
                                               description='API.OFFLINE_METER_NOT_FOUND')
5220
5221
                    query = (" SELECT id "
5222
                             " FROM tbl_spaces_offline_meters "
5223
                             " WHERE space_id = %s AND offline_meter_id = %s")
5224
                    cursor.execute(query, (new_id, offline_meter['id'],))
5225
                    if cursor.fetchone() is not None:
5226
                        cursor.close()
5227
                        cnx.close()
5228
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5229
                                               description='API.SPACE_OFFLINE_METER_RELATION_EXISTS')
5230
5231
                    add_row = (" INSERT INTO tbl_spaces_offline_meters (space_id, offline_meter_id) "
5232
                               " VALUES (%s, %s) ")
5233
                    cursor.execute(add_row, (new_id, offline_meter['id'],))
5234
5235
            # associate virtual meters with new space
5236
            if meta_result['virtual_meters'] is not None and len(meta_result['virtual_meters']) > 0:
5237
                for virtual_meter in meta_result['virtual_meters']:
5238
                    cursor.execute(" SELECT name "
5239
                                   " FROM tbl_virtual_meters "
5240
                                   " WHERE id = %s ", (virtual_meter['id'],))
5241
                    if cursor.fetchone() is None:
5242
                        cursor.close()
5243
                        cnx.close()
5244
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5245
                                               description='API.VIRTUAL_METER_NOT_FOUND')
5246
5247
                    query = (" SELECT id "
5248
                             " FROM tbl_spaces_virtual_meters "
5249
                             " WHERE space_id = %s AND virtual_meter_id = %s")
5250
                    cursor.execute(query, (new_id, virtual_meter['id'],))
5251
                    if cursor.fetchone() is not None:
5252
                        cursor.close()
5253
                        cnx.close()
5254
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5255
                                               description='API.SPACE_VIRTUAL_METER_RELATION_EXISTS')
5256
5257
                    add_row = (" INSERT INTO tbl_spaces_virtual_meters (space_id, virtual_meter_id) "
5258
                               " VALUES (%s, %s) ")
5259
                    cursor.execute(add_row, (new_id, virtual_meter['id'],))
5260
5261
            # associate shopfloors with new space
5262
            if meta_result['shopfloors'] is not None and len(meta_result['shopfloors']) > 0:
5263
                for shopfloor in meta_result['shopfloors']:
5264
                    cursor.execute(" SELECT name "
5265
                                   " FROM tbl_shopfloors "
5266
                                   " WHERE id = %s ", (shopfloor['id'],))
5267
                    if cursor.fetchone() is None:
5268
                        cursor.close()
5269
                        cnx.close()
5270
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5271
                                               description='API.SHOPFLOOR_NOT_FOUND')
5272
5273
                    query = (" SELECT id "
5274
                             " FROM tbl_spaces_shopfloors "
5275
                             " WHERE space_id = %s AND shopfloor_id = %s")
5276
                    cursor.execute(query, (new_id, shopfloor['id'],))
5277
                    if cursor.fetchone() is not None:
5278
                        cursor.close()
5279
                        cnx.close()
5280
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5281
                                               description='API.SPACE_SHOPFLOOR_RELATION_EXISTS')
5282
5283
                    add_row = (" INSERT INTO tbl_spaces_shopfloors (space_id, shopfloor_id) "
5284
                               " VALUES (%s, %s) ")
5285
                    cursor.execute(add_row, (new_id, shopfloor['id'],))
5286
5287
            # associate combined equipments with new space
5288
            if meta_result['combined_equipments'] is not None and len(meta_result['combined_equipments']) > 0:
5289
                for combined_equipment in meta_result['combined_equipments']:
5290
                    cursor.execute(" SELECT name "
5291
                                   " FROM tbl_combined_equipments "
5292
                                   " WHERE id = %s ", (combined_equipment['id'],))
5293
                    if cursor.fetchone() is None:
5294
                        cursor.close()
5295
                        cnx.close()
5296
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5297
                                               description='API.COMBINED_EQUIPMENT_NOT_FOUND')
5298
5299
                    query = (" SELECT id "
5300
                             " FROM tbl_spaces_combined_equipments "
5301
                             " WHERE space_id = %s AND combined_equipment_id = %s")
5302
                    cursor.execute(query, (new_id, combined_equipment['id'],))
5303
                    if cursor.fetchone() is not None:
5304
                        cursor.close()
5305
                        cnx.close()
5306
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5307
                                               description='API.SPACE_COMBINED_EQUIPMENT_RELATION_EXISTS')
5308
5309
                    add_row = (" INSERT INTO tbl_spaces_combined_equipments (space_id, combined_equipment_id) "
5310
                               " VALUES (%s, %s) ")
5311
                    cursor.execute(add_row, (new_id, combined_equipment['id'],))
5312
5313
            # associate equipments with new space
5314
            if meta_result['equipments'] is not None and len(meta_result['equipments']) > 0:
5315
                for equipment in meta_result['equipments']:
5316
                    cursor.execute(" SELECT name "
5317
                                   " FROM tbl_equipments "
5318
                                   " WHERE id = %s ", (equipment['id'],))
5319
                    if cursor.fetchone() is None:
5320
                        cursor.close()
5321
                        cnx.close()
5322
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5323
                                               description='API.EQUIPMENT_NOT_FOUND')
5324
5325
                    query = (" SELECT id "
5326
                             " FROM tbl_spaces_equipments "
5327
                             " WHERE space_id = %s AND equipment_id = %s")
5328
                    cursor.execute(query, (new_id, equipment['id'],))
5329
                    if cursor.fetchone() is not None:
5330
                        cursor.close()
5331
                        cnx.close()
5332
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5333
                                               description='API.SPACE_EQUIPMENT_RELATION_EXISTS')
5334
5335
                    add_row = (" INSERT INTO tbl_spaces_equipments (space_id, equipment_id) "
5336
                               " VALUES (%s, %s) ")
5337
                    cursor.execute(add_row, (new_id, equipment['id'],))
5338
5339
            # associate points with new space
5340
            if meta_result['points'] is not None and len(meta_result['points']) > 0:
5341
                for point in meta_result['points']:
5342
                    cursor.execute(" SELECT name "
5343
                                   " FROM tbl_points "
5344
                                   " WHERE id = %s ", (point['id'],))
5345
                    if cursor.fetchone() is None:
5346
                        cursor.close()
5347
                        cnx.close()
5348
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5349
                                               description='API.POINT_NOT_FOUND')
5350
5351
                    query = (" SELECT id "
5352
                             " FROM tbl_spaces_points "
5353
                             " WHERE space_id = %s AND point_id = %s")
5354
                    cursor.execute(query, (new_id, point['id'],))
5355
                    if cursor.fetchone() is not None:
5356
                        cursor.close()
5357
                        cnx.close()
5358
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5359
                                               description='API.SPACE_POINT_RELATION_EXISTS')
5360
5361
                    add_row = (" INSERT INTO tbl_spaces_points (space_id, point_id) "
5362
                               " VALUES (%s, %s) ")
5363
                    cursor.execute(add_row, (new_id, point['id'],))
5364
5365
            # associate sensors with new space
5366
            if meta_result['sensors'] is not None and len(meta_result['sensors']) > 0:
5367
                for sensor in meta_result['sensors']:
5368
                    cursor.execute(" SELECT name "
5369
                                   " FROM tbl_sensors "
5370
                                   " WHERE id = %s ", (sensor['id'],))
5371
                    if cursor.fetchone() is None:
5372
                        cursor.close()
5373
                        cnx.close()
5374
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5375
                                               description='API.SENSOR_NOT_FOUND')
5376
5377
                    query = (" SELECT id "
5378
                             " FROM tbl_spaces_sensors "
5379
                             " WHERE space_id = %s AND sensor_id = %s")
5380
                    cursor.execute(query, (new_id, sensor['id'],))
5381
                    if cursor.fetchone() is not None:
5382
                        cursor.close()
5383
                        cnx.close()
5384
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5385
                                               description='API.SPACE_SENSOR_RELATION_EXISTS')
5386
5387
                    add_row = (" INSERT INTO tbl_spaces_sensors (space_id, sensor_id) "
5388
                               " VALUES (%s, %s) ")
5389
                    cursor.execute(add_row, (new_id, sensor['id'],))
5390
5391
            # associate tenants with new space
5392
            if meta_result['tenants'] is not None and len(meta_result['tenants']) > 0:
5393
                for tenant in meta_result['tenants']:
5394
                    cursor.execute(" SELECT name "
5395
                                   " FROM tbl_tenants "
5396
                                   " WHERE id = %s ", (tenant['id'],))
5397
                    if cursor.fetchone() is None:
5398
                        cursor.close()
5399
                        cnx.close()
5400
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5401
                                               description='API.TENANT_NOT_FOUND')
5402
5403
                    query = (" SELECT id "
5404
                             " FROM tbl_spaces_tenants "
5405
                             " WHERE space_id = %s AND tenant_id = %s")
5406
                    cursor.execute(query, (new_id, tenant['id'],))
5407
                    if cursor.fetchone() is not None:
5408
                        cursor.close()
5409
                        cnx.close()
5410
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5411
                                               description='API.SPACE_TENANT_RELATION_EXISTS')
5412
5413
                    add_row = (" INSERT INTO tbl_spaces_tenants (space_id, tenant_id) "
5414
                               " VALUES (%s, %s) ")
5415
                    cursor.execute(add_row, (new_id, tenant['id'],))
5416
5417
            # associate stores with new space
5418
            if meta_result['stores'] is not None and len(meta_result['stores']) > 0:
5419
                for store in meta_result['stores']:
5420
                    cursor.execute(" SELECT name "
5421
                                   " FROM tbl_stores "
5422
                                   " WHERE id = %s ", (store['id'],))
5423
                    if cursor.fetchone() is None:
5424
                        cursor.close()
5425
                        cnx.close()
5426
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5427
                                               description='API.STORE_NOT_FOUND')
5428
5429
                    query = (" SELECT id "
5430
                             " FROM tbl_spaces_stores "
5431
                             " WHERE space_id = %s AND store_id = %s")
5432
                    cursor.execute(query, (new_id, store['id'],))
5433
                    if cursor.fetchone() is not None:
5434
                        cursor.close()
5435
                        cnx.close()
5436
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5437
                                               description='API.SPACE_STORE_RELATION_EXISTS')
5438
5439
                    add_row = (" INSERT INTO tbl_spaces_stores (space_id, store_id) "
5440
                               " VALUES (%s, %s) ")
5441
                    cursor.execute(add_row, (new_id, store['id'],))
5442
5443
            # associate working calendars with new space
5444
            if meta_result['working_calendars'] is not None and len(meta_result['working_calendars']) > 0:
5445
                for working_calendar in meta_result['working_calendars']:
5446
                    cursor.execute(" SELECT name "
5447
                                   " FROM tbl_working_calendars "
5448
                                   " WHERE id = %s ", (working_calendar['id'],))
5449
                    if cursor.fetchone() is None:
5450
                        cursor.close()
5451
                        cnx.close()
5452
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5453
                                               description='API.WORKING_CALENDAR_NOT_FOUND')
5454
5455
                    query = (" SELECT id "
5456
                             " FROM tbl_spaces_working_calendars "
5457
                             " WHERE space_id = %s AND working_calendar_id = %s")
5458
                    cursor.execute(query, (new_id, working_calendar['id'],))
5459
                    if cursor.fetchone() is not None:
5460
                        cursor.close()
5461
                        cnx.close()
5462
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5463
                                               description='API.SPACE_WORKING_CALENDAR_RELATION_EXISTS')
5464
5465
                    add_row = (" INSERT INTO tbl_spaces_working_calendars (space_id, working_calendar_id) "
5466
                               " VALUES (%s, %s) ")
5467
                    cursor.execute(add_row, (new_id, working_calendar['id'],))
5468
5469
            # todo: associate more objects with new space
5470
5471
            cnx.commit()
5472
            cursor.close()
5473
            cnx.close()
5474
5475
            resp.status = falcon.HTTP_201
5476
            resp.location = '/spaces/' + str(new_id)
5477
5478
5479 View Code Duplication
class SpaceEnergyFlowDiagramCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5480
    def __init__(self):
5481
        """Initializes Class"""
5482
        pass
5483
5484
    @staticmethod
5485
    def on_options(req, resp, id_):
5486
        resp.status = falcon.HTTP_200
5487
5488
    @staticmethod
5489
    def on_get(req, resp, id_):
5490
        if 'API-KEY' not in req.headers or \
5491
                not isinstance(req.headers['API-KEY'], str) or \
5492
                len(str.strip(req.headers['API-KEY'])) == 0:
5493
            access_control(req)
5494
        else:
5495
            api_key_control(req)
5496
        if not id_.isdigit() or int(id_) <= 0:
5497
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5498
                                   description='API.INVALID_SPACE_ID')
5499
5500
        cnx = mysql.connector.connect(**config.myems_system_db)
5501
        cursor = cnx.cursor()
5502
5503
        cursor.execute(" SELECT name "
5504
                       " FROM tbl_spaces "
5505
                       " WHERE id = %s ", (id_,))
5506
        if cursor.fetchone() is None:
5507
            cursor.close()
5508
            cnx.close()
5509
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5510
                                   description='API.SPACE_NOT_FOUND')
5511
5512
        query = (" SELECT e.id, e.name, e.uuid "
5513
                 " FROM tbl_spaces s, tbl_spaces_energy_flow_diagrams se, tbl_energy_flow_diagrams e "
5514
                 " WHERE se.space_id = s.id AND e.id = se.energy_flow_diagram_id AND s.id = %s "
5515
                 " ORDER BY e.id ")
5516
        cursor.execute(query, (id_,))
5517
        rows = cursor.fetchall()
5518
5519
        result = list()
5520
        if rows is not None and len(rows) > 0:
5521
            for row in rows:
5522
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
5523
                result.append(meta_result)
5524
5525
        resp.text = json.dumps(result)
5526
5527
    @staticmethod
5528
    @user_logger
5529
    def on_post(req, resp, id_):
5530
        """Handles POST requests"""
5531
        admin_control(req)
5532
        try:
5533
            raw_json = req.stream.read().decode('utf-8')
5534
        except Exception as ex:
5535
            raise falcon.HTTPError(status=falcon.HTTP_400,
5536
                                   title='API.BAD_REQUEST',
5537
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5538
5539
        if not id_.isdigit() or int(id_) <= 0:
5540
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5541
                                   description='API.INVALID_SPACE_ID')
5542
5543
        new_values = json.loads(raw_json)
5544
5545
        if 'energy_flow_diagram_id' not in new_values['data'].keys() or \
5546
                not isinstance(new_values['data']['energy_flow_diagram_id'], int) or \
5547
                new_values['data']['energy_flow_diagram_id'] <= 0:
5548
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5549
                                   description='API.INVALID_ENERGY_FLOW_DIAGRAM_ID')
5550
        energy_flow_diagram_id = new_values['data']['energy_flow_diagram_id']
5551
5552
        cnx = mysql.connector.connect(**config.myems_system_db)
5553
        cursor = cnx.cursor()
5554
5555
        cursor.execute(" SELECT name "
5556
                       " from tbl_spaces "
5557
                       " WHERE id = %s ", (id_,))
5558
        if cursor.fetchone() is None:
5559
            cursor.close()
5560
            cnx.close()
5561
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5562
                                   description='API.SPACE_NOT_FOUND')
5563
5564
        cursor.execute(" SELECT name "
5565
                       " FROM tbl_energy_flow_diagrams "
5566
                       " WHERE id = %s ", (energy_flow_diagram_id,))
5567
        if cursor.fetchone() is None:
5568
            cursor.close()
5569
            cnx.close()
5570
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5571
                                   description='API.ENERGY_FLOW_DIAGRAM_NOT_FOUND')
5572
5573
        query = (" SELECT id " 
5574
                 " FROM tbl_spaces_energy_flow_diagrams "
5575
                 " WHERE space_id = %s AND energy_flow_diagram_id = %s")
5576
        cursor.execute(query, (id_, energy_flow_diagram_id,))
5577
        if cursor.fetchone() is not None:
5578
            cursor.close()
5579
            cnx.close()
5580
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5581
                                   description='API.SPACE_ENERGY_FLOW_DIAGRAM_RELATION_EXISTS')
5582
5583
        add_row = (" INSERT INTO tbl_spaces_energy_flow_diagrams (space_id, energy_flow_diagram_id) "
5584
                   " VALUES (%s, %s) ")
5585
        cursor.execute(add_row, (id_, energy_flow_diagram_id,))
5586
        cnx.commit()
5587
        cursor.close()
5588
        cnx.close()
5589
5590
        resp.status = falcon.HTTP_201
5591
        resp.location = '/spaces/' + str(id_) + '/energyflowdiagrams/' + str(energy_flow_diagram_id)
5592
5593
5594 View Code Duplication
class SpaceEnergyFlowDiagramItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5595
    def __init__(self):
5596
        """Initializes Class"""
5597
        pass
5598
5599
    @staticmethod
5600
    def on_options(req, resp, id_, eid):
5601
        resp.status = falcon.HTTP_200
5602
5603
    @staticmethod
5604
    @user_logger
5605
    def on_delete(req, resp, id_, eid):
5606
        admin_control(req)
5607
        if not id_.isdigit() or int(id_) <= 0:
5608
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5609
                                   description='API.INVALID_SPACE_ID')
5610
5611
        if not eid.isdigit() or int(eid) <= 0:
5612
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5613
                                   description='API.INVALID_ENERGY_FLOW_DIAGRAM_ID')
5614
5615
        cnx = mysql.connector.connect(**config.myems_system_db)
5616
        cursor = cnx.cursor()
5617
5618
        cursor.execute(" SELECT name "
5619
                       " FROM tbl_spaces "
5620
                       " WHERE id = %s ", (id_,))
5621
        if cursor.fetchone() is None:
5622
            cursor.close()
5623
            cnx.close()
5624
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5625
                                   description='API.SPACE_NOT_FOUND')
5626
5627
        cursor.execute(" SELECT name "
5628
                       " FROM tbl_energy_flow_diagrams "
5629
                       " WHERE id = %s ", (eid,))
5630
        if cursor.fetchone() is None:
5631
            cursor.close()
5632
            cnx.close()
5633
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5634
                                   description='API.ENERGY_FLOW_DIAGRAM_NOT_FOUND')
5635
5636
        cursor.execute(" SELECT id "
5637
                       " FROM tbl_spaces_energy_flow_diagrams "
5638
                       " WHERE space_id = %s AND energy_flow_diagram_id = %s ", (id_, eid))
5639
        if cursor.fetchone() is None:
5640
            cursor.close()
5641
            cnx.close()
5642
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5643
                                   description='API.SPACE_ENERGY_FLOW_DIAGRAM_RELATION_NOT_FOUND')
5644
5645
        cursor.execute(" DELETE FROM tbl_spaces_energy_flow_diagrams "
5646
                       " WHERE space_id = %s AND energy_flow_diagram_id = %s ", (id_, eid))
5647
        cnx.commit()
5648
5649
        cursor.close()
5650
        cnx.close()
5651
5652
        resp.status = falcon.HTTP_204
5653
5654 View Code Duplication
class DistributionSystemCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5655
    def __init__(self):
5656
        """Initializes Class"""
5657
        pass
5658
5659
    @staticmethod
5660
    def on_options(req, resp, id_):
5661
        resp.status = falcon.HTTP_200
5662
5663
    @staticmethod
5664
    def on_get(req, resp, id_):
5665
        if 'API-KEY' not in req.headers or \
5666
                not isinstance(req.headers['API-KEY'], str) or \
5667
                len(str.strip(req.headers['API-KEY'])) == 0:
5668
            access_control(req)
5669
        else:
5670
            api_key_control(req)
5671
        if not id_.isdigit() or int(id_) <= 0:
5672
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5673
                                   description='API.INVALID_SPACE_ID')
5674
5675
        cnx = mysql.connector.connect(**config.myems_system_db)
5676
        cursor = cnx.cursor()
5677
5678
        cursor.execute(" SELECT name "
5679
                       " FROM tbl_spaces "
5680
                       " WHERE id = %s ", (id_,))
5681
        if cursor.fetchone() is None:
5682
            cursor.close()
5683
            cnx.close()
5684
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5685
                                   description='API.SPACE_NOT_FOUND')
5686
5687
        query = (" SELECT d.id, d.name, d.uuid "
5688
                 " FROM tbl_spaces s, tbl_spaces_distribution_systems sd, tbl_distribution_systems d "
5689
                 " WHERE sd.space_id = s.id AND d.id = sd.distribution_system_id AND s.id = %s "
5690
                 " ORDER BY d.id ")
5691
        cursor.execute(query, (id_,))
5692
        rows = cursor.fetchall()
5693
5694
        result = list()
5695
        if rows is not None and len(rows) > 0:
5696
            for row in rows:
5697
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
5698
                result.append(meta_result)
5699
5700
        resp.text = json.dumps(result)
5701
5702
    @staticmethod
5703
    @user_logger
5704
    def on_post(req, resp, id_):
5705
        """Handles POST requests"""
5706
        admin_control(req)
5707
        try:
5708
            raw_json = req.stream.read().decode('utf-8')
5709
        except Exception as ex:
5710
            raise falcon.HTTPError(status=falcon.HTTP_400,
5711
                                   title='API.BAD_REQUEST',
5712
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5713
5714
        if not id_.isdigit() or int(id_) <= 0:
5715
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5716
                                   description='API.INVALID_SPACE_ID')
5717
5718
        new_values = json.loads(raw_json)
5719
5720
        if 'distribution_system_id' not in new_values['data'].keys() or \
5721
                not isinstance(new_values['data']['distribution_system_id'], int) or \
5722
                new_values['data']['distribution_system_id'] <= 0:
5723
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5724
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
5725
        distribution_system_id = new_values['data']['distribution_system_id']
5726
5727
        cnx = mysql.connector.connect(**config.myems_system_db)
5728
        cursor = cnx.cursor()
5729
5730
        cursor.execute(" SELECT name "
5731
                       " from tbl_spaces "
5732
                       " WHERE id = %s ", (id_,))
5733
        if cursor.fetchone() is None:
5734
            cursor.close()
5735
            cnx.close()
5736
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5737
                                   description='API.SPACE_NOT_FOUND')
5738
5739
        cursor.execute(" SELECT name "
5740
                       " FROM tbl_distribution_systems "
5741
                       " WHERE id = %s ", (distribution_system_id,))
5742
        if cursor.fetchone() is None:
5743
            cursor.close()
5744
            cnx.close()
5745
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5746
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
5747
5748
        query = (" SELECT id " 
5749
                 " FROM tbl_spaces_distribution_systems "
5750
                 " WHERE space_id = %s AND distribution_system_id = %s")
5751
        cursor.execute(query, (id_, distribution_system_id,))
5752
        if cursor.fetchone() is not None:
5753
            cursor.close()
5754
            cnx.close()
5755
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5756
                                   description='API.SPACE_DISTRIBUTION_SYSTEM_RELATION_EXISTS')
5757
5758
        add_row = (" INSERT INTO tbl_spaces_distribution_systems (space_id, distribution_system_id) "
5759
                   " VALUES (%s, %s) ")
5760
        cursor.execute(add_row, (id_, distribution_system_id,))
5761
        cnx.commit()
5762
        cursor.close()
5763
        cnx.close()
5764
5765
        resp.status = falcon.HTTP_201
5766
        resp.location = '/spaces/' + str(id_) + '/distributionsystems/' + str(distribution_system_id)
5767
5768
5769 View Code Duplication
class DistributionSystemItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5770
    def __init__(self):
5771
        """Initializes Class"""
5772
        pass
5773
5774
    @staticmethod
5775
    def on_options(req, resp, id_, did):
5776
        resp.status = falcon.HTTP_200
5777
5778
    @staticmethod
5779
    @user_logger
5780
    def on_delete(req, resp, id_, did):
5781
        admin_control(req)
5782
        if not id_.isdigit() or int(id_) <= 0:
5783
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5784
                                   description='API.INVALID_SPACE_ID')
5785
5786
        if not did.isdigit() or int(did) <= 0:
5787
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5788
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
5789
5790
        cnx = mysql.connector.connect(**config.myems_system_db)
5791
        cursor = cnx.cursor()
5792
5793
        cursor.execute(" SELECT name "
5794
                       " FROM tbl_spaces "
5795
                       " WHERE id = %s ", (id_,))
5796
        if cursor.fetchone() is None:
5797
            cursor.close()
5798
            cnx.close()
5799
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5800
                                   description='API.SPACE_NOT_FOUND')
5801
5802
        cursor.execute(" SELECT name "
5803
                       " FROM tbl_distribution_systems "
5804
                       " WHERE id = %s ", (did,))
5805
        if cursor.fetchone() is None:
5806
            cursor.close()
5807
            cnx.close()
5808
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5809
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
5810
5811
        cursor.execute(" SELECT id "
5812
                       " FROM tbl_spaces_distribution_systems "
5813
                       " WHERE space_id = %s AND distribution_system_id = %s ", (id_, did))
5814
        if cursor.fetchone() is None:
5815
            cursor.close()
5816
            cnx.close()
5817
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5818
                                   description='API.SPACE_DISTRIBUTION_SYSTEM_RELATION_NOT_FOUND')
5819
5820
        cursor.execute(" DELETE FROM tbl_spaces_distribution_systems "
5821
                       " WHERE space_id = %s AND distribution_system_id = %s ", (id_, did))
5822
        cnx.commit()
5823
5824
        cursor.close()
5825
        cnx.close()
5826
5827
        resp.status = falcon.HTTP_204