core.space.SpaceClone.on_post()   F
last analyzed

Complexity

Conditions 114

Size

Total Lines 630
Code Lines 427

Duplication

Lines 0
Ratio 0 %

Importance

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