core.space.SpaceStoreCollection.on_get()   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 32
Code Lines 23

Duplication

Lines 32
Ratio 100 %

Importance

Changes 0
Metric Value
cc 7
eloc 23
nop 3
dl 32
loc 32
rs 7.9279
c 0
b 0
f 0
1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
import uuid
6
from datetime import datetime
7
from anytree import AnyNode
8
from anytree.exporter import JsonExporter
9
10
11
class SpaceCollection:
12
    @staticmethod
13
    def __init__():
14
        pass
15
16
    @staticmethod
17
    def on_options(req, resp):
18
        resp.status = falcon.HTTP_200
19
20
    @staticmethod
21
    def on_get(req, resp):
22
        cnx = mysql.connector.connect(**config.myems_system_db)
23
        cursor = cnx.cursor(dictionary=True)
24
25
        query = (" SELECT id, name, uuid "
26
                 " FROM tbl_spaces ")
27
        cursor.execute(query)
28
        rows_spaces = cursor.fetchall()
29
30
        space_dict = dict()
31
        if rows_spaces is not None and len(rows_spaces) > 0:
32
            for row in rows_spaces:
33
                space_dict[row['id']] = {"id": row['id'],
34
                                         "name": row['name'],
35
                                         "uuid": row['uuid']}
36
37
        query = (" SELECT id, name, utc_offset "
38
                 " FROM tbl_timezones ")
39
        cursor.execute(query)
40
        rows_timezones = cursor.fetchall()
41
42
        timezone_dict = dict()
43
        if rows_timezones is not None and len(rows_timezones) > 0:
44
            for row in rows_timezones:
45
                timezone_dict[row['id']] = {"id": row['id'],
46
                                            "name": row['name'],
47
                                            "utc_offset": row['utc_offset']}
48
49
        query = (" SELECT id, name, uuid "
50
                 " FROM tbl_contacts ")
51
        cursor.execute(query)
52
        rows_contacts = cursor.fetchall()
53
54
        contact_dict = dict()
55
        if rows_contacts is not None and len(rows_contacts) > 0:
56
            for row in rows_contacts:
57
                contact_dict[row['id']] = {"id": row['id'],
58
                                           "name": row['name'],
59
                                           "uuid": row['uuid']}
60
61
        query = (" SELECT id, name, uuid "
62
                 " FROM tbl_cost_centers ")
63
        cursor.execute(query)
64
        rows_cost_centers = cursor.fetchall()
65
66
        cost_center_dict = dict()
67
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
68
            for row in rows_cost_centers:
69
                cost_center_dict[row['id']] = {"id": row['id'],
70
                                               "name": row['name'],
71
                                               "uuid": row['uuid']}
72
73
        query = (" SELECT id, name, uuid, "
74
                 "        parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
75
                 "        contact_id, cost_center_id, description "
76
                 " FROM tbl_spaces "
77
                 " ORDER BY id ")
78
        cursor.execute(query)
79
        rows_spaces = cursor.fetchall()
80
81
        result = list()
82 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...
83
            for row in rows_spaces:
84
                timezone = timezone_dict.get(row['timezone_id'], None)
85
                contact = contact_dict.get(row['contact_id'], None)
86
                cost_center = cost_center_dict.get(row['cost_center_id'], None)
87
                parent_space = space_dict.get(row['parent_space_id'], None)
88
                meta_result = {"id": row['id'],
89
                               "name": row['name'],
90
                               "uuid": row['uuid'],
91
                               "parent_space": parent_space,
92
                               "area": row['area'],
93
                               "timezone": timezone,
94
                               "is_input_counted": bool(row['is_input_counted']),
95
                               "is_output_counted": bool(row['is_output_counted']),
96
                               "contact": contact,
97
                               "cost_center": cost_center,
98
                               "description": row['description']}
99
                result.append(meta_result)
100
101
        cursor.close()
102
        cnx.disconnect()
103
        resp.body = json.dumps(result)
104
105
    @staticmethod
106
    def on_post(req, resp):
107
        """Handles POST requests"""
108
        try:
109
            raw_json = req.stream.read().decode('utf-8')
110
            new_values = json.loads(raw_json)
111
        except Exception as ex:
112
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex)
113
114
        if 'name' not in new_values['data'].keys() or \
115
                not isinstance(new_values['data']['name'], str) or \
116
                len(str.strip(new_values['data']['name'])) == 0:
117
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
118
                                   description='API.INVALID_SPACE_NAME')
119
        name = str.strip(new_values['data']['name'])
120
121
        if 'parent_space_id' in new_values['data'].keys():
122
            if new_values['data']['parent_space_id'] <= 0:
123
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
124
                                       description='API.INVALID_PARENT_SPACE_ID')
125
            parent_space_id = new_values['data']['parent_space_id']
126
        else:
127
            parent_space_id = None
128
129
        if 'area' not in new_values['data'].keys() or \
130
                not (isinstance(new_values['data']['area'], float) or
131
                     isinstance(new_values['data']['area'], int)):
132
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
133
                                   description='API.INVALID_AREA_VALUE')
134
        area = new_values['data']['area']
135
136
        if 'timezone_id' not in new_values['data'].keys() or \
137
                not isinstance(new_values['data']['timezone_id'], int) or \
138
                new_values['data']['timezone_id'] <= 0:
139
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
140
                                   description='API.INVALID_TIMEZONE_ID')
141
        timezone_id = new_values['data']['timezone_id']
142
143
        if 'is_input_counted' not in new_values['data'].keys() or \
144
                not isinstance(new_values['data']['is_input_counted'], bool):
145
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
146
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
147
        is_input_counted = new_values['data']['is_input_counted']
148
149
        if 'is_output_counted' not in new_values['data'].keys() or \
150
                not isinstance(new_values['data']['is_output_counted'], bool):
151
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
152
                                   description='API.INVALID_IS_OUTPUT_COUNTED_VALUE')
153
        is_output_counted = new_values['data']['is_output_counted']
154
155
        if 'contact_id' in new_values['data'].keys():
156
            if new_values['data']['contact_id'] <= 0:
157
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
158
                                       description='API.INVALID_CONTACT_ID')
159
            contact_id = new_values['data']['contact_id']
160
        else:
161
            contact_id = None
162
163
        if 'cost_center_id' in new_values['data'].keys():
164
            if new_values['data']['cost_center_id'] <= 0:
165
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
166
                                       description='API.INVALID_COST_CENTER_ID')
167
            cost_center_id = new_values['data']['cost_center_id']
168
        else:
169
            cost_center_id = None
170
171
        if 'description' in new_values['data'].keys() and \
172
                new_values['data']['description'] is not None and \
173
                len(str(new_values['data']['description'])) > 0:
174
            description = str.strip(new_values['data']['description'])
175
        else:
176
            description = None
177
178
        cnx = mysql.connector.connect(**config.myems_system_db)
179
        cursor = cnx.cursor()
180
181
        cursor.execute(" SELECT name "
182
                       " FROM tbl_spaces "
183
                       " WHERE name = %s ", (name,))
184
        if cursor.fetchone() is not None:
185
            cursor.close()
186
            cnx.disconnect()
187
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
188
                                   description='API.SPACE_NAME_IS_ALREADY_IN_USE')
189
190 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...
191
            cursor.execute(" SELECT name "
192
                           " FROM tbl_spaces "
193
                           " WHERE id = %s ",
194
                           (new_values['data']['parent_space_id'],))
195
            row = cursor.fetchone()
196
            if row is None:
197
                cursor.close()
198
                cnx.disconnect()
199
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
200
                                       description='API.PARENT_SPACE_NOT_FOUND')
201
202
        cursor.execute(" SELECT name "
203
                       " FROM tbl_timezones "
204
                       " WHERE id = %s ",
205
                       (new_values['data']['timezone_id'],))
206
        if cursor.fetchone() is None:
207
            cursor.close()
208
            cnx.disconnect()
209
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
210
                                   description='API.TIMEZONE_NOT_FOUND')
211 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...
212
            cursor.execute(" SELECT name "
213
                           " FROM tbl_contacts "
214
                           " WHERE id = %s ",
215
                           (new_values['data']['contact_id'],))
216
            row = cursor.fetchone()
217
            if row is None:
218
                cursor.close()
219
                cnx.disconnect()
220
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
221
                                       description='API.CONTACT_NOT_FOUND')
222
223
        if cost_center_id is not None:
224
            cursor.execute(" SELECT name "
225
                           " FROM tbl_cost_centers "
226
                           " WHERE id = %s ",
227
                           (new_values['data']['cost_center_id'],))
228
            row = cursor.fetchone()
229
            if row is None:
230
                cursor.close()
231
                cnx.disconnect()
232
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
233
                                       description='API.COST_CENTER_NOT_FOUND')
234
235
        add_values = (" INSERT INTO tbl_spaces "
236
                      "    (name, uuid, parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
237
                      "     contact_id, cost_center_id, description) "
238
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
239
        cursor.execute(add_values, (name,
240
                                    str(uuid.uuid4()),
241
                                    parent_space_id,
242
                                    area,
243
                                    timezone_id,
244
                                    is_input_counted,
245
                                    is_output_counted,
246
                                    contact_id,
247
                                    cost_center_id,
248
                                    description))
249
        new_id = cursor.lastrowid
250
        cnx.commit()
251
        cursor.close()
252
        cnx.disconnect()
253
254
        resp.status = falcon.HTTP_201
255
        resp.location = '/spaces/' + str(new_id)
256
257
258
class SpaceItem:
259
    @staticmethod
260
    def __init__():
261
        pass
262
263
    @staticmethod
264
    def on_options(req, resp, id_):
265
        resp.status = falcon.HTTP_200
266
267
    @staticmethod
268
    def on_get(req, resp, id_):
269
        if not id_.isdigit() or int(id_) <= 0:
270
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
271
                                   description='API.INVALID_METER_ID')
272
273
        cnx = mysql.connector.connect(**config.myems_system_db)
274
        cursor = cnx.cursor(dictionary=True)
275
276
        query = (" SELECT id, name, uuid "
277
                 " FROM tbl_spaces ")
278
        cursor.execute(query)
279
        rows_spaces = cursor.fetchall()
280
281
        space_dict = dict()
282
        if rows_spaces is not None and len(rows_spaces) > 0:
283
            for row in rows_spaces:
284
                space_dict[row['id']] = {"id": row['id'],
285
                                         "name": row['name'],
286
                                         "uuid": row['uuid']}
287
288
        query = (" SELECT id, name, utc_offset "
289
                 " FROM tbl_timezones ")
290
        cursor.execute(query)
291
        rows_timezones = cursor.fetchall()
292
293
        timezone_dict = dict()
294
        if rows_timezones is not None and len(rows_timezones) > 0:
295
            for row in rows_timezones:
296
                timezone_dict[row['id']] = {"id": row['id'],
297
                                            "name": row['name'],
298
                                            "utc_offset": row['utc_offset']}
299
300
        query = (" SELECT id, name, uuid "
301
                 " FROM tbl_contacts ")
302
        cursor.execute(query)
303
        rows_contacts = cursor.fetchall()
304
305
        contact_dict = dict()
306
        if rows_contacts is not None and len(rows_contacts) > 0:
307
            for row in rows_contacts:
308
                contact_dict[row['id']] = {"id": row['id'],
309
                                           "name": row['name'],
310
                                           "uuid": row['uuid']}
311
312
        query = (" SELECT id, name, uuid "
313
                 " FROM tbl_cost_centers ")
314
        cursor.execute(query)
315
        rows_cost_centers = cursor.fetchall()
316
317
        cost_center_dict = dict()
318
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
319
            for row in rows_cost_centers:
320
                cost_center_dict[row['id']] = {"id": row['id'],
321
                                               "name": row['name'],
322
                                               "uuid": row['uuid']}
323
324
        query = (" SELECT id, name, uuid, "
325
                 "        parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
326
                 "        contact_id, cost_center_id, description "
327
                 " FROM tbl_spaces "
328
                 " WHERE id = %s ")
329
        cursor.execute(query, (id_,))
330
        row = cursor.fetchone()
331
        cursor.close()
332
        cnx.disconnect()
333
334
        if row is None:
335
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
336
                                   description='API.SPACE_NOT_FOUND')
337
        else:
338
            parent_space = space_dict.get(row['parent_space_id'], None)
339
            timezone = timezone_dict.get(row['timezone_id'], None)
340
            contact = contact_dict.get(row['contact_id'], None)
341
            cost_center = cost_center_dict.get(row['cost_center_id'], None)
342
            meta_result = {"id": row['id'],
343
                           "name": row['name'],
344
                           "uuid": row['uuid'],
345
                           "parent_space_id": parent_space,
346
                           "area": row['area'],
347
                           "timezone": timezone,
348
                           "is_input_counted": bool(row['is_input_counted']),
349
                           "is_output_counted": bool(row['is_output_counted']),
350
                           "contact": contact,
351
                           "cost_center": cost_center,
352
                           "description": row['description']}
353
354
        resp.body = json.dumps(meta_result)
355
356
    @staticmethod
357
    def on_delete(req, resp, id_):
358
        if not id_.isdigit() or int(id_) <= 0:
359
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
360
                                   description='API.INVALID_SPACE_ID')
361
        if int(id_) == 1:
362
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
363
                                   description='API.THIS_SPACE_CAN_NOT_BE_DELETED')
364
365
        cnx = mysql.connector.connect(**config.myems_system_db)
366
        cursor = cnx.cursor()
367
368
        cursor.execute(" SELECT name "
369
                       " FROM tbl_spaces "
370
                       " WHERE id = %s ", (id_,))
371
        if cursor.fetchone() is None:
372
            cursor.close()
373
            cnx.disconnect()
374
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
375
                                   description='API.SPACE_NOT_FOUND')
376
377
        # checkout relation with children spaces
378
        cursor.execute(" SELECT id "
379
                       " FROM tbl_spaces "
380
                       " WHERE parent_space_id = %s ",
381
                       (id_,))
382
        rows_spaces = cursor.fetchall()
383
        if rows_spaces is not None and len(rows_spaces) > 0:
384
            cursor.close()
385
            cnx.disconnect()
386
            raise falcon.HTTPError(falcon.HTTP_400,
387
                                   title='API.BAD_REQUEST',
388
                                   description='API.THERE_IS_RELATION_WITH_CHILDREN_SPACES')
389
390
        # check relation with equipment
391
        cursor.execute(" SELECT equipment_id "
392
                       " FROM tbl_spaces_equipments "
393
                       " WHERE space_id = %s ",
394
                       (id_,))
395
        rows_equipments = cursor.fetchall()
396
        if rows_equipments is not None and len(rows_equipments) > 0:
397
            cursor.close()
398
            cnx.disconnect()
399
            raise falcon.HTTPError(falcon.HTTP_400,
400
                                   title='API.BAD_REQUEST',
401
                                   description='API.THERE_IS_RELATION_WITH_EQUIPMENTS')
402
403
        # check relation with combined equipment
404
        cursor.execute(" SELECT combined_equipment_id "
405
                       " FROM tbl_spaces_combined_equipments "
406
                       " WHERE space_id = %s ",
407
                       (id_,))
408
        rows_combined_equipments = cursor.fetchall()
409
        if rows_combined_equipments is not None and len(rows_combined_equipments) > 0:
410
            cursor.close()
411
            cnx.disconnect()
412
            raise falcon.HTTPError(falcon.HTTP_400,
413
                                   title='API.BAD_REQUEST',
414
                                   description='API.THERE_IS_RELATION_WITH_COMBINED_EQUIPMENTS')
415
416
        # check relation with meter
417
        cursor.execute(" SELECT meter_id "
418
                       " FROM tbl_spaces_meters "
419
                       " WHERE space_id = %s ",
420
                       (id_,))
421
        rows_meters = cursor.fetchall()
422
        if rows_meters is not None and len(rows_meters) > 0:
423
            cursor.close()
424
            cnx.disconnect()
425
            raise falcon.HTTPError(falcon.HTTP_400,
426
                                   title='API.BAD_REQUEST',
427
                                   description='API.THERE_IS_RELATION_WITH_METERS')
428
429
        # check relation with offline meter
430
        cursor.execute(" SELECT offline_meter_id "
431
                       " FROM tbl_spaces_offline_meters "
432
                       " WHERE space_id = %s ",
433
                       (id_,))
434
        rows_offline_meters = cursor.fetchall()
435
        if rows_offline_meters is not None and len(rows_offline_meters) > 0:
436
            cursor.close()
437
            cnx.disconnect()
438
            raise falcon.HTTPError(falcon.HTTP_400,
439
                                   title='API.BAD_REQUEST',
440
                                   description='API.THERE_IS_RELATION_WITH_OFFLINE_METERS')
441
442
        # check relation with points
443
        cursor.execute(" SELECT point_id "
444
                       " FROM tbl_spaces_points "
445
                       " WHERE space_id = %s ", (id_,))
446
        rows_points = cursor.fetchall()
447
        if rows_points is not None and len(rows_points) > 0:
448
            cursor.close()
449
            cnx.disconnect()
450
            raise falcon.HTTPError(falcon.HTTP_400,
451
                                   title='API.BAD_REQUEST',
452
                                   description='API.THERE_IS_RELATION_WITH_POINTS')
453
454
        # check relation with sensor
455
        cursor.execute(" SELECT sensor_id "
456
                       " FROM tbl_spaces_sensors "
457
                       " WHERE space_id = %s ",
458
                       (id_,))
459
        rows_sensors = cursor.fetchall()
460
        if rows_sensors is not None and len(rows_sensors) > 0:
461
            cursor.close()
462
            cnx.disconnect()
463
            raise falcon.HTTPError(falcon.HTTP_400,
464
                                   title='API.BAD_REQUEST',
465
                                   description='API.THERE_IS_RELATION_WITH_SENSORS')
466
467
        # check relation with store
468
        cursor.execute(" SELECT id "
469
                       " FROM tbl_spaces_stores "
470
                       " WHERE space_id = %s ", (id_,))
471
        rows_stores = cursor.fetchall()
472
        if rows_stores is not None and len(rows_stores) > 0:
473
            cursor.close()
474
            cnx.disconnect()
475
            raise falcon.HTTPError(falcon.HTTP_400,
476
                                   title='API.BAD_REQUEST',
477
                                   description='API.THERE_IS_RELATION_WITH_STORES')
478
479
        # check relation with tenant
480
        cursor.execute(" SELECT id "
481
                       " FROM tbl_spaces_tenants "
482
                       " WHERE space_id = %s ", (id_,))
483
        rows_tenants = cursor.fetchall()
484
        if rows_tenants is not None and len(rows_tenants) > 0:
485
            cursor.close()
486
            cnx.disconnect()
487
            raise falcon.HTTPError(falcon.HTTP_400,
488
                                   title='API.BAD_REQUEST',
489
                                   description='API.THERE_IS_RELATION_WITH_TENANTS')
490
491
        # check relation with virtual meter
492
        cursor.execute(" SELECT virtual_meter_id "
493
                       " FROM tbl_spaces_virtual_meters "
494
                       " WHERE space_id = %s ",
495
                       (id_,))
496
        rows_virtual_meters = cursor.fetchall()
497
        if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
498
            cursor.close()
499
            cnx.disconnect()
500
            raise falcon.HTTPError(falcon.HTTP_400,
501
                                   title='API.BAD_REQUEST',
502
                                   description='API.THERE_IS_RELATION_WITH_VIRTUAL_METERS')
503
504
        cursor.execute(" DELETE FROM tbl_spaces WHERE id = %s ", (id_,))
505
        cnx.commit()
506
507
        cursor.close()
508
        cnx.disconnect()
509
510
        resp.status = falcon.HTTP_204
511
512
    @staticmethod
513
    def on_put(req, resp, id_):
514
        """Handles PUT requests"""
515
        try:
516
            raw_json = req.stream.read().decode('utf-8')
517
        except Exception as ex:
518
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
519
520
        if not id_.isdigit() or int(id_) <= 0:
521
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
522
                                   description='API.INVALID_SPACE_ID')
523
524
        new_values = json.loads(raw_json)
525
526
        if 'name' not in new_values['data'].keys() or \
527
                not isinstance(new_values['data']['name'], str) or \
528
                len(str.strip(new_values['data']['name'])) == 0:
529
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
530
                                   description='API.INVALID_SPACE_NAME')
531
        name = str.strip(new_values['data']['name'])
532
533
        if int(id_) == 1:
534
            parent_space_id = None
535
        else:
536
            if 'parent_space_id' not in new_values['data'].keys() or \
537
                    new_values['data']['parent_space_id'] is None or \
538
                    not isinstance(new_values['data']['parent_space_id'], int) or \
539
                    int(new_values['data']['parent_space_id']) <= 0:
540
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
541
                                       description='API.INVALID_TIMEZONE_ID')
542
            parent_space_id = int(new_values['data']['parent_space_id'])
543
544
        if 'area' not in new_values['data'].keys() or \
545
                not (isinstance(new_values['data']['area'], float) or
546
                     isinstance(new_values['data']['area'], int)):
547
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
548
                                   description='API.INVALID_AREA_VALUE')
549
        area = new_values['data']['area']
550
551
        if 'timezone_id' not in new_values['data'].keys() or \
552
                not isinstance(new_values['data']['timezone_id'], int) or \
553
                new_values['data']['timezone_id'] <= 0:
554
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
555
                                   description='API.INVALID_TIMEZONE_ID')
556
        timezone_id = new_values['data']['timezone_id']
557
558
        if 'is_input_counted' not in new_values['data'].keys() or \
559
                not isinstance(new_values['data']['is_input_counted'], bool):
560
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
561
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
562
        is_input_counted = new_values['data']['is_input_counted']
563
564
        if 'is_output_counted' not in new_values['data'].keys() or \
565
                not isinstance(new_values['data']['is_output_counted'], bool):
566
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
567
                                   description='API.INVALID_IS_OUTPUT_COUNTED_VALUE')
568
        is_output_counted = new_values['data']['is_output_counted']
569
570
        if 'contact_id' in new_values['data'].keys():
571
            if new_values['data']['contact_id'] <= 0:
572
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
573
                                       description='API.INVALID_CONTACT_ID')
574
            contact_id = new_values['data']['contact_id']
575
        else:
576
            contact_id = None
577
578
        if 'cost_center_id' in new_values['data'].keys():
579
            if new_values['data']['cost_center_id'] <= 0:
580
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
581
                                       description='API.INVALID_COST_CENTER_ID')
582
            cost_center_id = new_values['data']['cost_center_id']
583
        else:
584
            cost_center_id = None
585
586
        if 'description' in new_values['data'].keys() and \
587
                new_values['data']['description'] is not None and \
588
                len(str(new_values['data']['description'])) > 0:
589
            description = str.strip(new_values['data']['description'])
590
        else:
591
            description = None
592
593
        cnx = mysql.connector.connect(**config.myems_system_db)
594
        cursor = cnx.cursor()
595
596
        cursor.execute(" SELECT name "
597
                       " FROM tbl_spaces "
598
                       " WHERE id = %s ", (id_,))
599
        if cursor.fetchone() is None:
600
            cursor.close()
601
            cnx.disconnect()
602
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
603
                                   description='API.SPACE_NOT_FOUND')
604
605
        cursor.execute(" SELECT name "
606
                       " FROM tbl_spaces "
607
                       " WHERE name = %s AND id != %s ", (name, id_))
608
        if cursor.fetchone() is not None:
609
            cursor.close()
610
            cnx.disconnect()
611
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
612
                                   description='API.SPACE_NAME_IS_ALREADY_IN_USE')
613
614 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...
615
            cursor.execute(" SELECT name "
616
                           " FROM tbl_spaces "
617
                           " WHERE id = %s ",
618
                           (new_values['data']['parent_space_id'],))
619
            row = cursor.fetchone()
620
            if row is None:
621
                cursor.close()
622
                cnx.disconnect()
623
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
624
                                       description='API.PARENT_SPACE_NOT_FOUND')
625
626
        cursor.execute(" SELECT name "
627
                       " FROM tbl_timezones "
628
                       " WHERE id = %s ",
629
                       (new_values['data']['timezone_id'],))
630
        if cursor.fetchone() is None:
631
            cursor.close()
632
            cnx.disconnect()
633
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
634
                                   description='API.TIMEZONE_NOT_FOUND')
635 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...
636
            cursor.execute(" SELECT name "
637
                           " FROM tbl_contacts "
638
                           " WHERE id = %s ",
639
                           (new_values['data']['contact_id'],))
640
            row = cursor.fetchone()
641
            if row is None:
642
                cursor.close()
643
                cnx.disconnect()
644
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
645
                                       description='API.CONTACT_NOT_FOUND')
646
647
        if cost_center_id is not None:
648
            cursor.execute(" SELECT name "
649
                           " FROM tbl_cost_centers "
650
                           " WHERE id = %s ",
651
                           (new_values['data']['cost_center_id'],))
652
            row = cursor.fetchone()
653
            if row is None:
654
                cursor.close()
655
                cnx.disconnect()
656
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
657
                                       description='API.COST_CENTER_NOT_FOUND')
658
659
        update_row = (" UPDATE tbl_spaces "
660
                      " SET name = %s, parent_space_id = %s, area = %s, timezone_id = %s, "
661
                      "     is_input_counted = %s, is_output_counted = %s, contact_id = %s, cost_center_id = %s, "
662
                      "     description = %s "
663
                      " WHERE id = %s ")
664
        cursor.execute(update_row, (name,
665
                                    parent_space_id,
666
                                    area,
667
                                    timezone_id,
668
                                    is_input_counted,
669
                                    is_output_counted,
670
                                    contact_id,
671
                                    cost_center_id,
672
                                    description,
673
                                    id_))
674
        cnx.commit()
675
676
        cursor.close()
677
        cnx.disconnect()
678
679
        resp.status = falcon.HTTP_200
680
681
682
class SpaceChildrenCollection:
683
    @staticmethod
684
    def __init__():
685
        pass
686
687
    @staticmethod
688
    def on_options(req, resp, id_):
689
        resp.status = falcon.HTTP_200
690
691
    @staticmethod
692
    def on_get(req, resp, id_):
693
        if not id_.isdigit() or int(id_) <= 0:
694
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
695
                                   description='API.INVALID_SPACE_ID')
696
697
        cnx = mysql.connector.connect(**config.myems_system_db)
698
        cursor = cnx.cursor(dictionary=True)
699
700
        query = (" SELECT id, name, uuid, "
701
                 "        parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
702
                 "        contact_id, cost_center_id, description "
703
                 " FROM tbl_spaces "
704
                 " WHERE id = %s ")
705
        cursor.execute(query, (id_,))
706
        row_current_space = cursor.fetchone()
707
        if row_current_space is None:
708
            cursor.close()
709
            cnx.disconnect()
710
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
711
                                   description='API.SPACE_NOT_FOUND')
712
        # note: row_current_space will be used at the end
713
714
        query = (" SELECT id, name, uuid "
715
                 " FROM tbl_spaces ")
716
        cursor.execute(query)
717
        rows_spaces = cursor.fetchall()
718
719
        space_dict = dict()
720
        if rows_spaces is not None and len(rows_spaces) > 0:
721
            for row in rows_spaces:
722
                space_dict[row['id']] = {"id": row['id'],
723
                                         "name": row['name'],
724
                                         "uuid": row['uuid']}
725
726
        query = (" SELECT id, name, utc_offset "
727
                 " FROM tbl_timezones ")
728
        cursor.execute(query)
729
        rows_timezones = cursor.fetchall()
730
731
        timezone_dict = dict()
732
        if rows_timezones is not None and len(rows_timezones) > 0:
733
            for row in rows_timezones:
734
                timezone_dict[row['id']] = {"id": row['id'],
735
                                            "name": row['name'],
736
                                            "utc_offset": row['utc_offset']}
737
738
        query = (" SELECT id, name, uuid "
739
                 " FROM tbl_contacts ")
740
        cursor.execute(query)
741
        rows_contacts = cursor.fetchall()
742
743
        contact_dict = dict()
744
        if rows_contacts is not None and len(rows_contacts) > 0:
745
            for row in rows_contacts:
746
                contact_dict[row['id']] = {"id": row['id'],
747
                                           "name": row['name'],
748
                                           "uuid": row['uuid']}
749
750
        query = (" SELECT id, name, uuid "
751
                 " FROM tbl_cost_centers ")
752
        cursor.execute(query)
753
        rows_cost_centers = cursor.fetchall()
754
755
        cost_center_dict = dict()
756
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
757
            for row in rows_cost_centers:
758
                cost_center_dict[row['id']] = {"id": row['id'],
759
                                               "name": row['name'],
760
                                               "uuid": row['uuid']}
761
        result = dict()
762
        result['current'] = dict()
763
        result['current']['id'] = row_current_space['id']
764
        result['current']['name'] = row_current_space['name']
765
        result['current']['uuid'] = row_current_space['uuid']
766
        result['current']['parent_space'] = space_dict.get(row_current_space['parent_space_id'], None)
767
        result['current']['area'] = row_current_space['area']
768
        result['current']['timezone'] = timezone_dict.get(row_current_space['timezone_id'], None)
769
        result['current']['is_input_counted'] = bool(row_current_space['is_input_counted'])
770
        result['current']['is_output_counted'] = bool(row_current_space['is_output_counted'])
771
        result['current']['contact'] = contact_dict.get(row_current_space['contact_id'], None)
772
        result['current']['cost_center'] = cost_center_dict.get(row_current_space['cost_center_id'], None)
773
        result['current']['description'] = row_current_space['description']
774
775
        result['children'] = list()
776
777
        query = (" SELECT id, name, uuid, "
778
                 "        parent_space_id, area, timezone_id, is_input_counted, is_output_counted, "
779
                 "        contact_id, cost_center_id, description "
780
                 " FROM tbl_spaces "
781
                 " WHERE parent_space_id = %s "
782
                 " ORDER BY id ")
783
        cursor.execute(query, (id_, ))
784
        rows_spaces = cursor.fetchall()
785
786 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...
787
            for row in rows_spaces:
788
                timezone = timezone_dict.get(row['timezone_id'], None)
789
                contact = contact_dict.get(row['contact_id'], None)
790
                cost_center = cost_center_dict.get(row['cost_center_id'], None)
791
                parent_space = space_dict.get(row['parent_space_id'], None)
792
                meta_result = {"id": row['id'],
793
                               "name": row['name'],
794
                               "uuid": row['uuid'],
795
                               "parent_space": parent_space,
796
                               "area": row['area'],
797
                               "timezone": timezone,
798
                               "is_input_counted": bool(row['is_input_counted']),
799
                               "is_output_counted": bool(row['is_output_counted']),
800
                               "contact": contact,
801
                               "cost_center": cost_center,
802
                               "description": row['description']}
803
                result['children'].append(meta_result)
804
805
        cursor.close()
806
        cnx.disconnect()
807
        resp.body = json.dumps(result)
808
809
810 View Code Duplication
class SpaceCombinedEquipmentCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
811
    @staticmethod
812
    def __init__():
813
        pass
814
815
    @staticmethod
816
    def on_options(req, resp, id_):
817
        resp.status = falcon.HTTP_200
818
819
    @staticmethod
820
    def on_get(req, resp, id_):
821
        if not id_.isdigit() or int(id_) <= 0:
822
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
823
                                   description='API.INVALID_SPACE_ID')
824
825
        cnx = mysql.connector.connect(**config.myems_system_db)
826
        cursor = cnx.cursor()
827
828
        cursor.execute(" SELECT name "
829
                       " FROM tbl_spaces "
830
                       " WHERE id = %s ", (id_,))
831
        if cursor.fetchone() is None:
832
            cursor.close()
833
            cnx.disconnect()
834
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
835
                                   description='API.SPACE_NOT_FOUND')
836
837
        query = (" SELECT e.id, e.name, e.uuid "
838
                 " FROM tbl_spaces s, tbl_spaces_combined_equipments se, tbl_combined_equipments e "
839
                 " WHERE se.space_id = s.id AND e.id = se.combined_equipment_id AND s.id = %s "
840
                 " ORDER BY e.id ")
841
        cursor.execute(query, (id_,))
842
        rows = cursor.fetchall()
843
844
        result = list()
845
        if rows is not None and len(rows) > 0:
846
            for row in rows:
847
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
848
                result.append(meta_result)
849
850
        resp.body = json.dumps(result)
851
852
    @staticmethod
853
    def on_post(req, resp, id_):
854
        """Handles POST requests"""
855
        try:
856
            raw_json = req.stream.read().decode('utf-8')
857
        except Exception as ex:
858
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
859
860
        if not id_.isdigit() or int(id_) <= 0:
861
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
862
                                   description='API.INVALID_SPACE_ID')
863
864
        new_values = json.loads(raw_json)
865
866
        if 'combined_equipment_id' not in new_values['data'].keys() or \
867
                not isinstance(new_values['data']['combined_equipment_id'], int) or \
868
                new_values['data']['combined_equipment_id'] <= 0:
869
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
870
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
871
        combined_equipment_id = new_values['data']['combined_equipment_id']
872
873
        cnx = mysql.connector.connect(**config.myems_system_db)
874
        cursor = cnx.cursor()
875
876
        cursor.execute(" SELECT name "
877
                       " from tbl_spaces "
878
                       " WHERE id = %s ", (id_,))
879
        if cursor.fetchone() is None:
880
            cursor.close()
881
            cnx.disconnect()
882
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
883
                                   description='API.SPACE_NOT_FOUND')
884
885
        cursor.execute(" SELECT name "
886
                       " FROM tbl_combined_equipments "
887
                       " WHERE id = %s ", (combined_equipment_id,))
888
        if cursor.fetchone() is None:
889
            cursor.close()
890
            cnx.disconnect()
891
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
892
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
893
894
        query = (" SELECT id " 
895
                 " FROM tbl_spaces_combined_equipments "
896
                 " WHERE space_id = %s AND combined_equipment_id = %s")
897
        cursor.execute(query, (id_, combined_equipment_id,))
898
        if cursor.fetchone() is not None:
899
            cursor.close()
900
            cnx.disconnect()
901
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
902
                                   description='API.SPACE_COMBINED_EQUIPMENT_RELATION_EXISTED')
903
904
        add_row = (" INSERT INTO tbl_spaces_combined_equipments (space_id, combined_equipment_id) "
905
                   " VALUES (%s, %s) ")
906
        cursor.execute(add_row, (id_, combined_equipment_id,))
907
        new_id = cursor.lastrowid
908
        cnx.commit()
909
        cursor.close()
910
        cnx.disconnect()
911
912
        resp.status = falcon.HTTP_201
913
        resp.location = '/spaces/' + str(id_) + '/combinedequipments/' + str(combined_equipment_id)
914
915
916 View Code Duplication
class SpaceCombinedEquipmentItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
917
    @staticmethod
918
    def __init__():
919
        pass
920
921
    @staticmethod
922
    def on_options(req, resp, id_, eid):
923
            resp.status = falcon.HTTP_200
924
925
    @staticmethod
926
    def on_delete(req, resp, id_, eid):
927
        if not id_.isdigit() or int(id_) <= 0:
928
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
929
                                   description='API.INVALID_SPACE_ID')
930
931
        if not eid.isdigit() or int(eid) <= 0:
932
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
933
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
934
935
        cnx = mysql.connector.connect(**config.myems_system_db)
936
        cursor = cnx.cursor()
937
938
        cursor.execute(" SELECT name "
939
                       " FROM tbl_spaces "
940
                       " WHERE id = %s ", (id_,))
941
        if cursor.fetchone() is None:
942
            cursor.close()
943
            cnx.disconnect()
944
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
945
                                   description='API.SPACE_NOT_FOUND')
946
947
        cursor.execute(" SELECT name "
948
                       " FROM tbl_combined_equipments "
949
                       " WHERE id = %s ", (eid,))
950
        if cursor.fetchone() is None:
951
            cursor.close()
952
            cnx.disconnect()
953
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
954
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
955
956
        cursor.execute(" SELECT id "
957
                       " FROM tbl_spaces_combined_equipments "
958
                       " WHERE space_id = %s AND combined_equipment_id = %s ", (id_, eid))
959
        if cursor.fetchone() is None:
960
            cursor.close()
961
            cnx.disconnect()
962
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
963
                                   description='API.SPACE_COMBINED_EQUIPMENT_RELATION_NOT_FOUND')
964
965
        cursor.execute(" DELETE FROM tbl_spaces_combined_equipments "
966
                       " WHERE space_id = %s AND combined_equipment_id = %s ", (id_, eid))
967
        cnx.commit()
968
969
        cursor.close()
970
        cnx.disconnect()
971
972
        resp.status = falcon.HTTP_204
973
974
975 View Code Duplication
class SpaceEquipmentCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
976
    @staticmethod
977
    def __init__():
978
        pass
979
980
    @staticmethod
981
    def on_options(req, resp, id_):
982
        resp.status = falcon.HTTP_200
983
984
    @staticmethod
985
    def on_get(req, resp, id_):
986
        if not id_.isdigit() or int(id_) <= 0:
987
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
988
                                   description='API.INVALID_SPACE_ID')
989
990
        cnx = mysql.connector.connect(**config.myems_system_db)
991
        cursor = cnx.cursor()
992
993
        cursor.execute(" SELECT name "
994
                       " FROM tbl_spaces "
995
                       " WHERE id = %s ", (id_,))
996
        if cursor.fetchone() is None:
997
            cursor.close()
998
            cnx.disconnect()
999
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1000
                                   description='API.SPACE_NOT_FOUND')
1001
1002
        query = (" SELECT e.id, e.name, e.uuid "
1003
                 " FROM tbl_spaces s, tbl_spaces_equipments se, tbl_equipments e "
1004
                 " WHERE se.space_id = s.id AND e.id = se.equipment_id AND s.id = %s "
1005
                 " ORDER BY e.id ")
1006
        cursor.execute(query, (id_,))
1007
        rows = cursor.fetchall()
1008
1009
        result = list()
1010
        if rows is not None and len(rows) > 0:
1011
            for row in rows:
1012
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1013
                result.append(meta_result)
1014
1015
        resp.body = json.dumps(result)
1016
1017
    @staticmethod
1018
    def on_post(req, resp, id_):
1019
        """Handles POST requests"""
1020
        try:
1021
            raw_json = req.stream.read().decode('utf-8')
1022
        except Exception as ex:
1023
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1024
1025
        if not id_.isdigit() or int(id_) <= 0:
1026
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1027
                                   description='API.INVALID_SPACE_ID')
1028
1029
        new_values = json.loads(raw_json)
1030
1031
        if 'equipment_id' not in new_values['data'].keys() or \
1032
                not isinstance(new_values['data']['equipment_id'], int) or \
1033
                new_values['data']['equipment_id'] <= 0:
1034
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1035
                                   description='API.INVALID_EQUIPMENT_ID')
1036
        equipment_id = new_values['data']['equipment_id']
1037
1038
        cnx = mysql.connector.connect(**config.myems_system_db)
1039
        cursor = cnx.cursor()
1040
1041
        cursor.execute(" SELECT name "
1042
                       " from tbl_spaces "
1043
                       " WHERE id = %s ", (id_,))
1044
        if cursor.fetchone() is None:
1045
            cursor.close()
1046
            cnx.disconnect()
1047
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1048
                                   description='API.SPACE_NOT_FOUND')
1049
1050
        cursor.execute(" SELECT name "
1051
                       " FROM tbl_equipments "
1052
                       " WHERE id = %s ", (equipment_id,))
1053
        if cursor.fetchone() is None:
1054
            cursor.close()
1055
            cnx.disconnect()
1056
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1057
                                   description='API.EQUIPMENT_NOT_FOUND')
1058
1059
        query = (" SELECT id " 
1060
                 " FROM tbl_spaces_equipments "
1061
                 " WHERE space_id = %s AND equipment_id = %s")
1062
        cursor.execute(query, (id_, equipment_id,))
1063
        if cursor.fetchone() is not None:
1064
            cursor.close()
1065
            cnx.disconnect()
1066
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1067
                                   description='API.SPACE_EQUIPMENT_RELATION_EXISTED')
1068
1069
        add_row = (" INSERT INTO tbl_spaces_equipments (space_id, equipment_id) "
1070
                   " VALUES (%s, %s) ")
1071
        cursor.execute(add_row, (id_, equipment_id,))
1072
        new_id = cursor.lastrowid
1073
        cnx.commit()
1074
        cursor.close()
1075
        cnx.disconnect()
1076
1077
        resp.status = falcon.HTTP_201
1078
        resp.location = '/spaces/' + str(id_) + '/equipments/' + str(equipment_id)
1079
1080
1081 View Code Duplication
class SpaceEquipmentItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1082
    @staticmethod
1083
    def __init__():
1084
        pass
1085
1086
    @staticmethod
1087
    def on_options(req, resp, id_, eid):
1088
            resp.status = falcon.HTTP_200
1089
1090
    @staticmethod
1091
    def on_delete(req, resp, id_, eid):
1092
        if not id_.isdigit() or int(id_) <= 0:
1093
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1094
                                   description='API.INVALID_SPACE_ID')
1095
1096
        if not eid.isdigit() or int(eid) <= 0:
1097
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1098
                                   description='API.INVALID_EQUIPMENT_ID')
1099
1100
        cnx = mysql.connector.connect(**config.myems_system_db)
1101
        cursor = cnx.cursor()
1102
1103
        cursor.execute(" SELECT name "
1104
                       " FROM tbl_spaces "
1105
                       " WHERE id = %s ", (id_,))
1106
        if cursor.fetchone() is None:
1107
            cursor.close()
1108
            cnx.disconnect()
1109
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1110
                                   description='API.SPACE_NOT_FOUND')
1111
1112
        cursor.execute(" SELECT name "
1113
                       " FROM tbl_equipments "
1114
                       " WHERE id = %s ", (eid,))
1115
        if cursor.fetchone() is None:
1116
            cursor.close()
1117
            cnx.disconnect()
1118
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1119
                                   description='API.EQUIPMENT_NOT_FOUND')
1120
1121
        cursor.execute(" SELECT id "
1122
                       " FROM tbl_spaces_equipments "
1123
                       " WHERE space_id = %s AND equipment_id = %s ", (id_, eid))
1124
        if cursor.fetchone() is None:
1125
            cursor.close()
1126
            cnx.disconnect()
1127
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1128
                                   description='API.SPACE_EQUIPMENT_RELATION_NOT_FOUND')
1129
1130
        cursor.execute(" DELETE FROM tbl_spaces_equipments WHERE space_id = %s AND equipment_id = %s ", (id_, eid))
1131
        cnx.commit()
1132
1133
        cursor.close()
1134
        cnx.disconnect()
1135
1136
        resp.status = falcon.HTTP_204
1137
1138
1139 View Code Duplication
class SpaceMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1140
    @staticmethod
1141
    def __init__():
1142
        pass
1143
1144
    @staticmethod
1145
    def on_options(req, resp, id_):
1146
        resp.status = falcon.HTTP_200
1147
1148
    @staticmethod
1149
    def on_get(req, resp, id_):
1150
        if not id_.isdigit() or int(id_) <= 0:
1151
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1152
                                   description='API.INVALID_SPACE_ID')
1153
1154
        cnx = mysql.connector.connect(**config.myems_system_db)
1155
        cursor = cnx.cursor(dictionary=True)
1156
1157
        cursor.execute(" SELECT name "
1158
                       " FROM tbl_spaces "
1159
                       " WHERE id = %s ", (id_,))
1160
        if cursor.fetchone() is None:
1161
            cursor.close()
1162
            cnx.disconnect()
1163
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1164
                                   description='API.SPACE_NOT_FOUND')
1165
1166
        query = (" SELECT id, name, uuid "
1167
                 " FROM tbl_energy_categories ")
1168
        cursor.execute(query)
1169
        rows_energy_categories = cursor.fetchall()
1170
1171
        energy_category_dict = dict()
1172
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1173
            for row in rows_energy_categories:
1174
                energy_category_dict[row['id']] = {"id": row['id'],
1175
                                                   "name": row['name'],
1176
                                                   "uuid": row['uuid']}
1177
1178
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1179
                 " FROM tbl_spaces s, tbl_spaces_meters sm, tbl_meters m "
1180
                 " WHERE sm.space_id = s.id AND m.id = sm.meter_id AND s.id = %s "
1181
                 " ORDER BY m.id ")
1182
        cursor.execute(query, (id_,))
1183
        rows = cursor.fetchall()
1184
1185
        result = list()
1186
        if rows is not None and len(rows) > 0:
1187
            for row in rows:
1188
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1189
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1190
                               "energy_category": energy_category}
1191
                result.append(meta_result)
1192
1193
        resp.body = json.dumps(result)
1194
1195
    @staticmethod
1196
    def on_post(req, resp, id_):
1197
        """Handles POST requests"""
1198
        try:
1199
            raw_json = req.stream.read().decode('utf-8')
1200
        except Exception as ex:
1201
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1202
1203
        if not id_.isdigit() or int(id_) <= 0:
1204
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1205
                                   description='API.INVALID_SPACE_ID')
1206
1207
        new_values = json.loads(raw_json)
1208
1209
        if 'meter_id' not in new_values['data'].keys() or \
1210
                not isinstance(new_values['data']['meter_id'], int) or \
1211
                new_values['data']['meter_id'] <= 0:
1212
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1213
                                   description='API.INVALID_METER_ID')
1214
        meter_id = new_values['data']['meter_id']
1215
1216
        cnx = mysql.connector.connect(**config.myems_system_db)
1217
        cursor = cnx.cursor()
1218
1219
        cursor.execute(" SELECT name "
1220
                       " from tbl_spaces "
1221
                       " WHERE id = %s ", (id_,))
1222
        if cursor.fetchone() is None:
1223
            cursor.close()
1224
            cnx.disconnect()
1225
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1226
                                   description='API.SPACE_NOT_FOUND')
1227
1228
        cursor.execute(" SELECT name "
1229
                       " FROM tbl_meters "
1230
                       " WHERE id = %s ", (meter_id,))
1231
        if cursor.fetchone() is None:
1232
            cursor.close()
1233
            cnx.disconnect()
1234
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1235
                                   description='API.METER_NOT_FOUND')
1236
1237
        query = (" SELECT id " 
1238
                 " FROM tbl_spaces_meters "
1239
                 " WHERE space_id = %s AND meter_id = %s")
1240
        cursor.execute(query, (id_, meter_id,))
1241
        if cursor.fetchone() is not None:
1242
            cursor.close()
1243
            cnx.disconnect()
1244
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1245
                                   description='API.SPACE_METER_RELATION_EXISTED')
1246
1247
        add_row = (" INSERT INTO tbl_spaces_meters (space_id, meter_id) "
1248
                   " VALUES (%s, %s) ")
1249
        cursor.execute(add_row, (id_, meter_id,))
1250
        new_id = cursor.lastrowid
1251
        cnx.commit()
1252
        cursor.close()
1253
        cnx.disconnect()
1254
1255
        resp.status = falcon.HTTP_201
1256
        resp.location = '/spaces/' + str(id_) + '/meters/' + str(meter_id)
1257
1258
1259 View Code Duplication
class SpaceMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1260
    @staticmethod
1261
    def __init__():
1262
        pass
1263
1264
    @staticmethod
1265
    def on_options(req, resp, id_, mid):
1266
            resp.status = falcon.HTTP_200
1267
1268
    @staticmethod
1269
    def on_delete(req, resp, id_, mid):
1270
        if not id_.isdigit() or int(id_) <= 0:
1271
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1272
                                   description='API.INVALID_SPACE_ID')
1273
1274
        if not mid.isdigit() or int(mid) <= 0:
1275
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1276
                                   description='API.INVALID_METER_ID')
1277
1278
        cnx = mysql.connector.connect(**config.myems_system_db)
1279
        cursor = cnx.cursor()
1280
1281
        cursor.execute(" SELECT name "
1282
                       " FROM tbl_spaces "
1283
                       " WHERE id = %s ", (id_,))
1284
        if cursor.fetchone() is None:
1285
            cursor.close()
1286
            cnx.disconnect()
1287
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1288
                                   description='API.SPACE_NOT_FOUND')
1289
1290
        cursor.execute(" SELECT name "
1291
                       " FROM tbl_meters "
1292
                       " WHERE id = %s ", (mid,))
1293
        if cursor.fetchone() is None:
1294
            cursor.close()
1295
            cnx.disconnect()
1296
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1297
                                   description='API.METER_NOT_FOUND')
1298
1299
        cursor.execute(" SELECT id "
1300
                       " FROM tbl_spaces_meters "
1301
                       " WHERE space_id = %s AND meter_id = %s ", (id_, mid))
1302
        if cursor.fetchone() is None:
1303
            cursor.close()
1304
            cnx.disconnect()
1305
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1306
                                   description='API.SPACE_METER_RELATION_NOT_FOUND')
1307
1308
        cursor.execute(" DELETE FROM tbl_spaces_meters WHERE space_id = %s AND meter_id = %s ", (id_, mid))
1309
        cnx.commit()
1310
1311
        cursor.close()
1312
        cnx.disconnect()
1313
1314
        resp.status = falcon.HTTP_204
1315
1316
1317 View Code Duplication
class SpaceOfflineMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1318
    @staticmethod
1319
    def __init__():
1320
        pass
1321
1322
    @staticmethod
1323
    def on_options(req, resp, id_):
1324
        resp.status = falcon.HTTP_200
1325
1326
    @staticmethod
1327
    def on_get(req, resp, id_):
1328
        if not id_.isdigit() or int(id_) <= 0:
1329
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1330
                                   description='API.INVALID_SPACE_ID')
1331
1332
        cnx = mysql.connector.connect(**config.myems_system_db)
1333
        cursor = cnx.cursor(dictionary=True)
1334
1335
        cursor.execute(" SELECT name "
1336
                       " FROM tbl_spaces "
1337
                       " WHERE id = %s ", (id_,))
1338
        if cursor.fetchone() is None:
1339
            cursor.close()
1340
            cnx.disconnect()
1341
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1342
                                   description='API.SPACE_NOT_FOUND')
1343
1344
        query = (" SELECT id, name, uuid "
1345
                 " FROM tbl_energy_categories ")
1346
        cursor.execute(query)
1347
        rows_energy_categories = cursor.fetchall()
1348
1349
        energy_category_dict = dict()
1350
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1351
            for row in rows_energy_categories:
1352
                energy_category_dict[row['id']] = {"id": row['id'],
1353
                                                   "name": row['name'],
1354
                                                   "uuid": row['uuid']}
1355
1356
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1357
                 " FROM tbl_spaces s, tbl_spaces_offline_meters sm, tbl_offline_meters m "
1358
                 " WHERE sm.space_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
1359
                 " ORDER BY m.id ")
1360
        cursor.execute(query, (id_,))
1361
        rows = cursor.fetchall()
1362
1363
        result = list()
1364
        if rows is not None and len(rows) > 0:
1365
            for row in rows:
1366
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1367
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1368
                               "energy_category": energy_category}
1369
                result.append(meta_result)
1370
1371
        resp.body = json.dumps(result)
1372
1373
    @staticmethod
1374
    def on_post(req, resp, id_):
1375
        """Handles POST requests"""
1376
        try:
1377
            raw_json = req.stream.read().decode('utf-8')
1378
        except Exception as ex:
1379
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1380
1381
        if not id_.isdigit() or int(id_) <= 0:
1382
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1383
                                   description='API.INVALID_SPACE_ID')
1384
1385
        new_values = json.loads(raw_json)
1386
1387
        if 'offline_meter_id' not in new_values['data'].keys() or \
1388
                not isinstance(new_values['data']['offline_meter_id'], int) or \
1389
                new_values['data']['offline_meter_id'] <= 0:
1390
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1391
                                   description='API.INVALID_OFFLINE_METER_ID')
1392
        offline_meter_id = new_values['data']['offline_meter_id']
1393
1394
        cnx = mysql.connector.connect(**config.myems_system_db)
1395
        cursor = cnx.cursor()
1396
1397
        cursor.execute(" SELECT name "
1398
                       " from tbl_spaces "
1399
                       " WHERE id = %s ", (id_,))
1400
        if cursor.fetchone() is None:
1401
            cursor.close()
1402
            cnx.disconnect()
1403
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1404
                                   description='API.SPACE_NOT_FOUND')
1405
1406
        cursor.execute(" SELECT name "
1407
                       " FROM tbl_offline_meters "
1408
                       " WHERE id = %s ", (offline_meter_id,))
1409
        if cursor.fetchone() is None:
1410
            cursor.close()
1411
            cnx.disconnect()
1412
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1413
                                   description='API.OFFLINE_METER_NOT_FOUND')
1414
1415
        query = (" SELECT id " 
1416
                 " FROM tbl_spaces_offline_meters "
1417
                 " WHERE space_id = %s AND offline_meter_id = %s")
1418
        cursor.execute(query, (id_, offline_meter_id,))
1419
        if cursor.fetchone() is not None:
1420
            cursor.close()
1421
            cnx.disconnect()
1422
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1423
                                   description='API.SPACE_OFFLINE_METER_RELATION_EXISTED')
1424
1425
        add_row = (" INSERT INTO tbl_spaces_offline_meters (space_id, offline_meter_id) "
1426
                   " VALUES (%s, %s) ")
1427
        cursor.execute(add_row, (id_, offline_meter_id,))
1428
        new_id = cursor.lastrowid
1429
        cnx.commit()
1430
        cursor.close()
1431
        cnx.disconnect()
1432
1433
        resp.status = falcon.HTTP_201
1434
        resp.location = '/spaces/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
1435
1436
1437 View Code Duplication
class SpaceOfflineMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1438
    @staticmethod
1439
    def __init__():
1440
        pass
1441
1442
    @staticmethod
1443
    def on_options(req, resp, id_, mid):
1444
            resp.status = falcon.HTTP_200
1445
1446
    @staticmethod
1447
    def on_delete(req, resp, id_, mid):
1448
        if not id_.isdigit() or int(id_) <= 0:
1449
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1450
                                   description='API.INVALID_SPACE_ID')
1451
1452
        if not mid.isdigit() or int(mid) <= 0:
1453
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1454
                                   description='API.INVALID_OFFLINE_METER_ID')
1455
1456
        cnx = mysql.connector.connect(**config.myems_system_db)
1457
        cursor = cnx.cursor()
1458
1459
        cursor.execute(" SELECT name "
1460
                       " FROM tbl_spaces "
1461
                       " WHERE id = %s ", (id_,))
1462
        if cursor.fetchone() is None:
1463
            cursor.close()
1464
            cnx.disconnect()
1465
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1466
                                   description='API.SPACE_NOT_FOUND')
1467
1468
        cursor.execute(" SELECT name "
1469
                       " FROM tbl_offline_meters "
1470
                       " WHERE id = %s ", (mid,))
1471
        if cursor.fetchone() is None:
1472
            cursor.close()
1473
            cnx.disconnect()
1474
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1475
                                   description='API.OFFLINE_METER_NOT_FOUND')
1476
1477
        cursor.execute(" SELECT id "
1478
                       " FROM tbl_spaces_offline_meters "
1479
                       " WHERE space_id = %s AND offline_meter_id = %s ", (id_, mid))
1480
        if cursor.fetchone() is None:
1481
            cursor.close()
1482
            cnx.disconnect()
1483
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1484
                                   description='API.SPACE_OFFLINE_METER_RELATION_NOT_FOUND')
1485
1486
        cursor.execute(" DELETE FROM tbl_spaces_offline_meters "
1487
                       " WHERE space_id = %s AND offline_meter_id = %s ", (id_, mid))
1488
        cnx.commit()
1489
1490
        cursor.close()
1491
        cnx.disconnect()
1492
1493
        resp.status = falcon.HTTP_204
1494
1495
1496 View Code Duplication
class SpacePointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1497
    @staticmethod
1498
    def __init__():
1499
        pass
1500
1501
    @staticmethod
1502
    def on_options(req, resp, id_):
1503
        resp.status = falcon.HTTP_200
1504
1505
    @staticmethod
1506
    def on_get(req, resp, id_):
1507
        if not id_.isdigit() or int(id_) <= 0:
1508
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1509
                                   description='API.INVALID_SPACE_ID')
1510
1511
        cnx = mysql.connector.connect(**config.myems_system_db)
1512
        cursor = cnx.cursor(dictionary=True)
1513
1514
        cursor.execute(" SELECT name "
1515
                       " FROM tbl_spaces "
1516
                       " WHERE id = %s ", (id_,))
1517
        if cursor.fetchone() is None:
1518
            cursor.close()
1519
            cnx.disconnect()
1520
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1521
                                   description='API.SPACE_NOT_FOUND')
1522
1523
        query = (" SELECT id, name, uuid "
1524
                 " FROM tbl_data_sources ")
1525
        cursor.execute(query)
1526
        rows_data_sources = cursor.fetchall()
1527
1528
        data_source_dict = dict()
1529
        if rows_data_sources is not None and len(rows_data_sources) > 0:
1530
            for row in rows_data_sources:
1531
                data_source_dict[row['id']] = {"id": row['id'],
1532
                                               "name": row['name'],
1533
                                               "uuid": row['uuid']}
1534
1535
        query = (" SELECT p.id, p.name, p.data_source_id "
1536
                 " FROM tbl_spaces s, tbl_spaces_points sp, tbl_points p "
1537
                 " WHERE sp.space_id = s.id AND p.id = sp.point_id AND s.id = %s "
1538
                 " ORDER BY p.id ")
1539
        cursor.execute(query, (id_,))
1540
        rows = cursor.fetchall()
1541
1542
        result = list()
1543
        if rows is not None and len(rows) > 0:
1544
            for row in rows:
1545
                data_source = data_source_dict.get(row['data_source_id'], None)
1546
                meta_result = {"id": row['id'], "name": row['name'], "data_source": data_source}
1547
                result.append(meta_result)
1548
1549
        resp.body = json.dumps(result)
1550
1551
    @staticmethod
1552
    def on_post(req, resp, id_):
1553
        """Handles POST requests"""
1554
        try:
1555
            raw_json = req.stream.read().decode('utf-8')
1556
        except Exception as ex:
1557
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1558
1559
        if not id_.isdigit() or int(id_) <= 0:
1560
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1561
                                   description='API.INVALID_SPACE_ID')
1562
1563
        new_values = json.loads(raw_json)
1564
1565
        if 'point_id' not in new_values['data'].keys() or \
1566
                not isinstance(new_values['data']['point_id'], int) or \
1567
                new_values['data']['point_id'] <= 0:
1568
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1569
                                   description='API.INVALID_POINT_ID')
1570
        point_id = new_values['data']['point_id']
1571
1572
        cnx = mysql.connector.connect(**config.myems_system_db)
1573
        cursor = cnx.cursor()
1574
1575
        cursor.execute(" SELECT name "
1576
                       " from tbl_spaces "
1577
                       " WHERE id = %s ", (id_,))
1578
        if cursor.fetchone() is None:
1579
            cursor.close()
1580
            cnx.disconnect()
1581
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1582
                                   description='API.SPACE_NOT_FOUND')
1583
1584
        cursor.execute(" SELECT name "
1585
                       " FROM tbl_points "
1586
                       " WHERE id = %s ", (point_id,))
1587
        if cursor.fetchone() is None:
1588
            cursor.close()
1589
            cnx.disconnect()
1590
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1591
                                   description='API.POINT_NOT_FOUND')
1592
1593
        query = (" SELECT id " 
1594
                 " FROM tbl_spaces_points "
1595
                 " WHERE space_id = %s AND point_id = %s")
1596
        cursor.execute(query, (id_, point_id,))
1597
        if cursor.fetchone() is not None:
1598
            cursor.close()
1599
            cnx.disconnect()
1600
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1601
                                   description='API.SPACE_POINT_RELATION_EXISTED')
1602
1603
        add_row = (" INSERT INTO tbl_spaces_points (space_id, point_id) "
1604
                   " VALUES (%s, %s) ")
1605
        cursor.execute(add_row, (id_, point_id,))
1606
        new_id = cursor.lastrowid
1607
        cnx.commit()
1608
        cursor.close()
1609
        cnx.disconnect()
1610
1611
        resp.status = falcon.HTTP_201
1612
        resp.location = '/spaces/' + str(id_) + '/points/' + str(point_id)
1613
1614
1615 View Code Duplication
class SpacePointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1616
    @staticmethod
1617
    def __init__():
1618
        pass
1619
1620
    @staticmethod
1621
    def on_options(req, resp, id_, pid):
1622
            resp.status = falcon.HTTP_200
1623
1624
    @staticmethod
1625
    def on_delete(req, resp, id_, pid):
1626
        if not id_.isdigit() or int(id_) <= 0:
1627
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1628
                                   description='API.INVALID_SPACE_ID')
1629
1630
        if not pid.isdigit() or int(pid) <= 0:
1631
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1632
                                   description='API.INVALID_POINT_ID')
1633
1634
        cnx = mysql.connector.connect(**config.myems_system_db)
1635
        cursor = cnx.cursor()
1636
1637
        cursor.execute(" SELECT name "
1638
                       " FROM tbl_spaces "
1639
                       " WHERE id = %s ", (id_,))
1640
        if cursor.fetchone() is None:
1641
            cursor.close()
1642
            cnx.disconnect()
1643
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1644
                                   description='API.SPACE_NOT_FOUND')
1645
1646
        cursor.execute(" SELECT name "
1647
                       " FROM tbl_points "
1648
                       " WHERE id = %s ", (pid,))
1649
        if cursor.fetchone() is None:
1650
            cursor.close()
1651
            cnx.disconnect()
1652
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1653
                                   description='API.POINT_NOT_FOUND')
1654
1655
        cursor.execute(" SELECT id "
1656
                       " FROM tbl_spaces_points "
1657
                       " WHERE space_id = %s AND point_id = %s ", (id_, pid))
1658
        if cursor.fetchone() is None:
1659
            cursor.close()
1660
            cnx.disconnect()
1661
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1662
                                   description='API.SPACE_POINT_RELATION_NOT_FOUND')
1663
1664
        cursor.execute(" DELETE FROM tbl_spaces_points "
1665
                       " WHERE space_id = %s AND point_id = %s ", (id_, pid))
1666
        cnx.commit()
1667
1668
        cursor.close()
1669
        cnx.disconnect()
1670
1671
        resp.status = falcon.HTTP_204
1672
1673
1674 View Code Duplication
class SpaceSensorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1675
    @staticmethod
1676
    def __init__():
1677
        pass
1678
1679
    @staticmethod
1680
    def on_options(req, resp, id_):
1681
        resp.status = falcon.HTTP_200
1682
1683
    @staticmethod
1684
    def on_get(req, resp, id_):
1685
        if not id_.isdigit() or int(id_) <= 0:
1686
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1687
                                   description='API.INVALID_SPACE_ID')
1688
1689
        cnx = mysql.connector.connect(**config.myems_system_db)
1690
        cursor = cnx.cursor()
1691
1692
        cursor.execute(" SELECT name "
1693
                       " FROM tbl_spaces "
1694
                       " WHERE id = %s ", (id_,))
1695
        if cursor.fetchone() is None:
1696
            cursor.close()
1697
            cnx.disconnect()
1698
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1699
                                   description='API.SPACE_NOT_FOUND')
1700
1701
        query = (" SELECT se.id, se.name, se.uuid "
1702
                 " FROM tbl_spaces sp, tbl_spaces_sensors ss, tbl_sensors se "
1703
                 " WHERE ss.space_id = sp.id AND se.id = ss.sensor_id AND sp.id = %s "
1704
                 " ORDER BY se.id ")
1705
        cursor.execute(query, (id_,))
1706
        rows = cursor.fetchall()
1707
1708
        result = list()
1709
        if rows is not None and len(rows) > 0:
1710
            for row in rows:
1711
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1712
                result.append(meta_result)
1713
1714
        resp.body = json.dumps(result)
1715
1716
    @staticmethod
1717
    def on_post(req, resp, id_):
1718
        """Handles POST requests"""
1719
        try:
1720
            raw_json = req.stream.read().decode('utf-8')
1721
        except Exception as ex:
1722
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1723
1724
        if not id_.isdigit() or int(id_) <= 0:
1725
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1726
                                   description='API.INVALID_SPACE_ID')
1727
1728
        new_values = json.loads(raw_json)
1729
1730
        if 'sensor_id' not in new_values['data'].keys() or \
1731
                not isinstance(new_values['data']['sensor_id'], int) or \
1732
                new_values['data']['sensor_id'] <= 0:
1733
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1734
                                   description='API.INVALID_SENSOR_ID')
1735
        sensor_id = new_values['data']['sensor_id']
1736
1737
        cnx = mysql.connector.connect(**config.myems_system_db)
1738
        cursor = cnx.cursor()
1739
1740
        cursor.execute(" SELECT name "
1741
                       " from tbl_spaces "
1742
                       " WHERE id = %s ", (id_,))
1743
        if cursor.fetchone() is None:
1744
            cursor.close()
1745
            cnx.disconnect()
1746
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1747
                                   description='API.SPACE_NOT_FOUND')
1748
1749
        cursor.execute(" SELECT name "
1750
                       " FROM tbl_sensors "
1751
                       " WHERE id = %s ", (sensor_id,))
1752
        if cursor.fetchone() is None:
1753
            cursor.close()
1754
            cnx.disconnect()
1755
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1756
                                   description='API.SENSOR_NOT_FOUND')
1757
1758
        query = (" SELECT id " 
1759
                 " FROM tbl_spaces_sensors "
1760
                 " WHERE space_id = %s AND sensor_id = %s")
1761
        cursor.execute(query, (id_, sensor_id,))
1762
        if cursor.fetchone() is not None:
1763
            cursor.close()
1764
            cnx.disconnect()
1765
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1766
                                   description='API.SPACE_SENSOR_RELATION_EXISTED')
1767
1768
        add_row = (" INSERT INTO tbl_spaces_sensors (space_id, sensor_id) "
1769
                   " VALUES (%s, %s) ")
1770
        cursor.execute(add_row, (id_, sensor_id,))
1771
        new_id = cursor.lastrowid
1772
        cnx.commit()
1773
        cursor.close()
1774
        cnx.disconnect()
1775
1776
        resp.status = falcon.HTTP_201
1777
        resp.location = '/spaces/' + str(id_) + '/sensors/' + str(sensor_id)
1778
1779
1780 View Code Duplication
class SpaceSensorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1781
    @staticmethod
1782
    def __init__():
1783
        pass
1784
1785
    @staticmethod
1786
    def on_options(req, resp, id_, sid):
1787
            resp.status = falcon.HTTP_200
1788
1789
    @staticmethod
1790
    def on_delete(req, resp, id_, sid):
1791
        if not id_.isdigit() or int(id_) <= 0:
1792
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1793
                                   description='API.INVALID_SPACE_ID')
1794
1795
        if not sid.isdigit() or int(sid) <= 0:
1796
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1797
                                   description='API.INVALID_SENSOR_ID')
1798
1799
        cnx = mysql.connector.connect(**config.myems_system_db)
1800
        cursor = cnx.cursor()
1801
1802
        cursor.execute(" SELECT name "
1803
                       " FROM tbl_spaces "
1804
                       " WHERE id = %s ", (id_,))
1805
        if cursor.fetchone() is None:
1806
            cursor.close()
1807
            cnx.disconnect()
1808
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1809
                                   description='API.SPACE_NOT_FOUND')
1810
1811
        cursor.execute(" SELECT name "
1812
                       " FROM tbl_sensors "
1813
                       " WHERE id = %s ", (sid,))
1814
        if cursor.fetchone() is None:
1815
            cursor.close()
1816
            cnx.disconnect()
1817
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1818
                                   description='API.SENSOR_NOT_FOUND')
1819
1820
        cursor.execute(" SELECT id "
1821
                       " FROM tbl_spaces_sensors "
1822
                       " WHERE space_id = %s AND sensor_id = %s ", (id_, sid))
1823
        if cursor.fetchone() is None:
1824
            cursor.close()
1825
            cnx.disconnect()
1826
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1827
                                   description='API.SPACE_SENSOR_RELATION_NOT_FOUND')
1828
1829
        cursor.execute(" DELETE FROM tbl_spaces_sensors WHERE space_id = %s AND sensor_id = %s ", (id_, sid))
1830
        cnx.commit()
1831
1832
        cursor.close()
1833
        cnx.disconnect()
1834
1835
        resp.status = falcon.HTTP_204
1836
1837
1838 View Code Duplication
class SpaceShopfloorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1839
    @staticmethod
1840
    def __init__():
1841
        pass
1842
1843
    @staticmethod
1844
    def on_options(req, resp, id_):
1845
        resp.status = falcon.HTTP_200
1846
1847
    @staticmethod
1848
    def on_get(req, resp, id_):
1849
        if not id_.isdigit() or int(id_) <= 0:
1850
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1851
                                   description='API.INVALID_SPACE_ID')
1852
1853
        cnx = mysql.connector.connect(**config.myems_system_db)
1854
        cursor = cnx.cursor()
1855
1856
        cursor.execute(" SELECT name "
1857
                       " FROM tbl_spaces "
1858
                       " WHERE id = %s ", (id_,))
1859
        if cursor.fetchone() is None:
1860
            cursor.close()
1861
            cnx.disconnect()
1862
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1863
                                   description='API.SPACE_NOT_FOUND')
1864
1865
        query = (" SELECT sf.id, sf.name, sf.uuid "
1866
                 " FROM tbl_spaces sp, tbl_spaces_shopfloors ss, tbl_shopfloors sf "
1867
                 " WHERE ss.space_id = sp.id AND sf.id = ss.shopfloor_id AND sp.id = %s "
1868
                 " ORDER BY sf.id ")
1869
        cursor.execute(query, (id_,))
1870
        rows = cursor.fetchall()
1871
1872
        result = list()
1873
        if rows is not None and len(rows) > 0:
1874
            for row in rows:
1875
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1876
                result.append(meta_result)
1877
1878
        resp.body = json.dumps(result)
1879
1880
    @staticmethod
1881
    def on_post(req, resp, id_):
1882
        """Handles POST requests"""
1883
        try:
1884
            raw_json = req.stream.read().decode('utf-8')
1885
        except Exception as ex:
1886
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1887
1888
        if not id_.isdigit() or int(id_) <= 0:
1889
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1890
                                   description='API.INVALID_SPACE_ID')
1891
1892
        new_values = json.loads(raw_json)
1893
1894
        if 'shopfloor_id' not in new_values['data'].keys() or \
1895
                not isinstance(new_values['data']['shopfloor_id'], int) or \
1896
                new_values['data']['shopfloor_id'] <= 0:
1897
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1898
                                   description='API.INVALID_SHOPFLOOR_ID')
1899
        shopfloor_id = new_values['data']['shopfloor_id']
1900
1901
        cnx = mysql.connector.connect(**config.myems_system_db)
1902
        cursor = cnx.cursor()
1903
1904
        cursor.execute(" SELECT name "
1905
                       " from tbl_spaces "
1906
                       " WHERE id = %s ", (id_,))
1907
        if cursor.fetchone() is None:
1908
            cursor.close()
1909
            cnx.disconnect()
1910
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1911
                                   description='API.SPACE_NOT_FOUND')
1912
1913
        cursor.execute(" SELECT name "
1914
                       " FROM tbl_shopfloors "
1915
                       " WHERE id = %s ", (shopfloor_id,))
1916
        if cursor.fetchone() is None:
1917
            cursor.close()
1918
            cnx.disconnect()
1919
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1920
                                   description='API.SHOPFLOOR_NOT_FOUND')
1921
1922
        query = (" SELECT id " 
1923
                 " FROM tbl_spaces_shopfloors "
1924
                 " WHERE space_id = %s AND shopfloor_id = %s")
1925
        cursor.execute(query, (id_, shopfloor_id,))
1926
        if cursor.fetchone() is not None:
1927
            cursor.close()
1928
            cnx.disconnect()
1929
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1930
                                   description='API.SPACE_SHOPFLOOR_RELATION_EXISTED')
1931
1932
        add_row = (" INSERT INTO tbl_spaces_shopfloors (space_id, shopfloor_id) "
1933
                   " VALUES (%s, %s) ")
1934
        cursor.execute(add_row, (id_, shopfloor_id,))
1935
        new_id = cursor.lastrowid
1936
        cnx.commit()
1937
        cursor.close()
1938
        cnx.disconnect()
1939
1940
        resp.status = falcon.HTTP_201
1941
        resp.location = '/spaces/' + str(id_) + '/shopfloors/' + str(shopfloor_id)
1942
1943
1944 View Code Duplication
class SpaceShopfloorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1945
    @staticmethod
1946
    def __init__():
1947
        pass
1948
1949
    @staticmethod
1950
    def on_options(req, resp, id_, sid):
1951
            resp.status = falcon.HTTP_200
1952
1953
    @staticmethod
1954
    def on_delete(req, resp, id_, sid):
1955
        if not id_.isdigit() or int(id_) <= 0:
1956
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1957
                                   description='API.INVALID_SPACE_ID')
1958
1959
        if not sid.isdigit() or int(sid) <= 0:
1960
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1961
                                   description='API.INVALID_SHOPFLOOR_ID')
1962
1963
        cnx = mysql.connector.connect(**config.myems_system_db)
1964
        cursor = cnx.cursor()
1965
1966
        cursor.execute(" SELECT name "
1967
                       " FROM tbl_spaces "
1968
                       " WHERE id = %s ", (id_,))
1969
        if cursor.fetchone() is None:
1970
            cursor.close()
1971
            cnx.disconnect()
1972
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1973
                                   description='API.SPACE_NOT_FOUND')
1974
1975
        cursor.execute(" SELECT name "
1976
                       " FROM tbl_shopfloors "
1977
                       " WHERE id = %s ", (sid,))
1978
        if cursor.fetchone() is None:
1979
            cursor.close()
1980
            cnx.disconnect()
1981
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1982
                                   description='API.SHOPFLOOR_NOT_FOUND')
1983
1984
        cursor.execute(" SELECT id "
1985
                       " FROM tbl_spaces_shopfloors "
1986
                       " WHERE space_id = %s AND shopfloor_id = %s ", (id_, sid))
1987
        if cursor.fetchone() is None:
1988
            cursor.close()
1989
            cnx.disconnect()
1990
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1991
                                   description='API.SPACE_SHOPFLOOR_RELATION_NOT_FOUND')
1992
1993
        cursor.execute(" DELETE FROM tbl_spaces_shopfloors WHERE space_id = %s AND shopfloor_id = %s ", (id_, sid))
1994
        cnx.commit()
1995
1996
        cursor.close()
1997
        cnx.disconnect()
1998
1999
        resp.status = falcon.HTTP_204
2000
2001
2002 View Code Duplication
class SpaceStoreCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2003
    @staticmethod
2004
    def __init__():
2005
        pass
2006
2007
    @staticmethod
2008
    def on_options(req, resp, id_):
2009
        resp.status = falcon.HTTP_200
2010
2011
    @staticmethod
2012
    def on_get(req, resp, id_):
2013
        if not id_.isdigit() or int(id_) <= 0:
2014
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2015
                                   description='API.INVALID_SPACE_ID')
2016
2017
        cnx = mysql.connector.connect(**config.myems_system_db)
2018
        cursor = cnx.cursor()
2019
2020
        cursor.execute(" SELECT name "
2021
                       " FROM tbl_spaces "
2022
                       " WHERE id = %s ", (id_,))
2023
        if cursor.fetchone() is None:
2024
            cursor.close()
2025
            cnx.disconnect()
2026
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2027
                                   description='API.SPACE_NOT_FOUND')
2028
2029
        query = (" SELECT t.id, t.name, t.uuid "
2030
                 " FROM tbl_spaces s, tbl_spaces_stores st, tbl_stores t "
2031
                 " WHERE st.space_id = s.id AND t.id = st.store_id AND s.id = %s "
2032
                 " ORDER BY t.id ")
2033
        cursor.execute(query, (id_,))
2034
        rows = cursor.fetchall()
2035
2036
        result = list()
2037
        if rows is not None and len(rows) > 0:
2038
            for row in rows:
2039
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2040
                result.append(meta_result)
2041
2042
        resp.body = json.dumps(result)
2043
2044
    @staticmethod
2045
    def on_post(req, resp, id_):
2046
        """Handles POST requests"""
2047
        try:
2048
            raw_json = req.stream.read().decode('utf-8')
2049
        except Exception as ex:
2050
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
2051
2052
        if not id_.isdigit() or int(id_) <= 0:
2053
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2054
                                   description='API.INVALID_SPACE_ID')
2055
2056
        new_values = json.loads(raw_json)
2057
2058
        if 'store_id' not in new_values['data'].keys() or \
2059
                not isinstance(new_values['data']['store_id'], int) or \
2060
                new_values['data']['store_id'] <= 0:
2061
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2062
                                   description='API.INVALID_STORE_ID')
2063
        store_id = new_values['data']['store_id']
2064
2065
        cnx = mysql.connector.connect(**config.myems_system_db)
2066
        cursor = cnx.cursor()
2067
2068
        cursor.execute(" SELECT name "
2069
                       " from tbl_spaces "
2070
                       " WHERE id = %s ", (id_,))
2071
        if cursor.fetchone() is None:
2072
            cursor.close()
2073
            cnx.disconnect()
2074
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2075
                                   description='API.SPACE_NOT_FOUND')
2076
2077
        cursor.execute(" SELECT name "
2078
                       " FROM tbl_stores "
2079
                       " WHERE id = %s ", (store_id,))
2080
        if cursor.fetchone() is None:
2081
            cursor.close()
2082
            cnx.disconnect()
2083
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2084
                                   description='API.STORE_NOT_FOUND')
2085
2086
        query = (" SELECT id " 
2087
                 " FROM tbl_spaces_stores "
2088
                 " WHERE space_id = %s AND store_id = %s")
2089
        cursor.execute(query, (id_, store_id,))
2090
        if cursor.fetchone() is not None:
2091
            cursor.close()
2092
            cnx.disconnect()
2093
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
2094
                                   description='API.SPACE_STORE_RELATION_EXISTED')
2095
2096
        add_row = (" INSERT INTO tbl_spaces_stores (space_id, store_id) "
2097
                   " VALUES (%s, %s) ")
2098
        cursor.execute(add_row, (id_, store_id,))
2099
        new_id = cursor.lastrowid
2100
        cnx.commit()
2101
        cursor.close()
2102
        cnx.disconnect()
2103
2104
        resp.status = falcon.HTTP_201
2105
        resp.location = '/spaces/' + str(id_) + '/stores/' + str(store_id)
2106
2107
2108 View Code Duplication
class SpaceStoreItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2109
    @staticmethod
2110
    def __init__():
2111
        pass
2112
2113
    @staticmethod
2114
    def on_options(req, resp, id_, tid):
2115
            resp.status = falcon.HTTP_200
2116
2117
    @staticmethod
2118
    def on_delete(req, resp, id_, tid):
2119
        if not id_.isdigit() or int(id_) <= 0:
2120
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2121
                                   description='API.INVALID_SPACE_ID')
2122
2123
        if not tid.isdigit() or int(tid) <= 0:
2124
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2125
                                   description='API.INVALID_STORE_ID')
2126
2127
        cnx = mysql.connector.connect(**config.myems_system_db)
2128
        cursor = cnx.cursor()
2129
2130
        cursor.execute(" SELECT name "
2131
                       " FROM tbl_spaces "
2132
                       " WHERE id = %s ", (id_,))
2133
        if cursor.fetchone() is None:
2134
            cursor.close()
2135
            cnx.disconnect()
2136
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2137
                                   description='API.SPACE_NOT_FOUND')
2138
2139
        cursor.execute(" SELECT name "
2140
                       " FROM tbl_stores "
2141
                       " WHERE id = %s ", (tid,))
2142
        if cursor.fetchone() is None:
2143
            cursor.close()
2144
            cnx.disconnect()
2145
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2146
                                   description='API.STORE_NOT_FOUND')
2147
2148
        cursor.execute(" SELECT id "
2149
                       " FROM tbl_spaces_stores "
2150
                       " WHERE space_id = %s AND store_id = %s ", (id_, tid))
2151
        if cursor.fetchone() is None:
2152
            cursor.close()
2153
            cnx.disconnect()
2154
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2155
                                   description='API.SPACE_STORE_RELATION_NOT_FOUND')
2156
2157
        cursor.execute(" DELETE FROM tbl_spaces_stores WHERE space_id = %s AND store_id = %s ", (id_, tid))
2158
        cnx.commit()
2159
2160
        cursor.close()
2161
        cnx.disconnect()
2162
2163
        resp.status = falcon.HTTP_204
2164
2165
2166 View Code Duplication
class SpaceTenantCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2167
    @staticmethod
2168
    def __init__():
2169
        pass
2170
2171
    @staticmethod
2172
    def on_options(req, resp, id_):
2173
        resp.status = falcon.HTTP_200
2174
2175
    @staticmethod
2176
    def on_get(req, resp, id_):
2177
        if not id_.isdigit() or int(id_) <= 0:
2178
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2179
                                   description='API.INVALID_SPACE_ID')
2180
2181
        cnx = mysql.connector.connect(**config.myems_system_db)
2182
        cursor = cnx.cursor()
2183
2184
        cursor.execute(" SELECT name "
2185
                       " FROM tbl_spaces "
2186
                       " WHERE id = %s ", (id_,))
2187
        if cursor.fetchone() is None:
2188
            cursor.close()
2189
            cnx.disconnect()
2190
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2191
                                   description='API.SPACE_NOT_FOUND')
2192
2193
        query = (" SELECT t.id, t.name, t.uuid "
2194
                 " FROM tbl_spaces s, tbl_spaces_tenants st, tbl_tenants t "
2195
                 " WHERE st.space_id = s.id AND t.id = st.tenant_id AND s.id = %s "
2196
                 " ORDER BY t.id ")
2197
        cursor.execute(query, (id_,))
2198
        rows = cursor.fetchall()
2199
2200
        result = list()
2201
        if rows is not None and len(rows) > 0:
2202
            for row in rows:
2203
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2204
                result.append(meta_result)
2205
2206
        resp.body = json.dumps(result)
2207
2208
    @staticmethod
2209
    def on_post(req, resp, id_):
2210
        """Handles POST requests"""
2211
        try:
2212
            raw_json = req.stream.read().decode('utf-8')
2213
        except Exception as ex:
2214
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
2215
2216
        if not id_.isdigit() or int(id_) <= 0:
2217
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2218
                                   description='API.INVALID_SPACE_ID')
2219
2220
        new_values = json.loads(raw_json)
2221
2222
        if 'tenant_id' not in new_values['data'].keys() or \
2223
                not isinstance(new_values['data']['tenant_id'], int) or \
2224
                new_values['data']['tenant_id'] <= 0:
2225
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2226
                                   description='API.INVALID_TENANT_ID')
2227
        tenant_id = new_values['data']['tenant_id']
2228
2229
        cnx = mysql.connector.connect(**config.myems_system_db)
2230
        cursor = cnx.cursor()
2231
2232
        cursor.execute(" SELECT name "
2233
                       " from tbl_spaces "
2234
                       " WHERE id = %s ", (id_,))
2235
        if cursor.fetchone() is None:
2236
            cursor.close()
2237
            cnx.disconnect()
2238
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2239
                                   description='API.SPACE_NOT_FOUND')
2240
2241
        cursor.execute(" SELECT name "
2242
                       " FROM tbl_tenants "
2243
                       " WHERE id = %s ", (tenant_id,))
2244
        if cursor.fetchone() is None:
2245
            cursor.close()
2246
            cnx.disconnect()
2247
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2248
                                   description='API.TENANT_NOT_FOUND')
2249
2250
        query = (" SELECT id " 
2251
                 " FROM tbl_spaces_tenants "
2252
                 " WHERE space_id = %s AND tenant_id = %s")
2253
        cursor.execute(query, (id_, tenant_id,))
2254
        if cursor.fetchone() is not None:
2255
            cursor.close()
2256
            cnx.disconnect()
2257
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
2258
                                   description='API.SPACE_TENANT_RELATION_EXISTED')
2259
2260
        add_row = (" INSERT INTO tbl_spaces_tenants (space_id, tenant_id) "
2261
                   " VALUES (%s, %s) ")
2262
        cursor.execute(add_row, (id_, tenant_id,))
2263
        new_id = cursor.lastrowid
2264
        cnx.commit()
2265
        cursor.close()
2266
        cnx.disconnect()
2267
2268
        resp.status = falcon.HTTP_201
2269
        resp.location = '/spaces/' + str(id_) + '/tenants/' + str(tenant_id)
2270
2271
2272 View Code Duplication
class SpaceTenantItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2273
    @staticmethod
2274
    def __init__():
2275
        pass
2276
2277
    @staticmethod
2278
    def on_options(req, resp, id_, tid):
2279
            resp.status = falcon.HTTP_200
2280
2281
    @staticmethod
2282
    def on_delete(req, resp, id_, tid):
2283
        if not id_.isdigit() or int(id_) <= 0:
2284
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2285
                                   description='API.INVALID_SPACE_ID')
2286
2287
        if not tid.isdigit() or int(tid) <= 0:
2288
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2289
                                   description='API.INVALID_TENANT_ID')
2290
2291
        cnx = mysql.connector.connect(**config.myems_system_db)
2292
        cursor = cnx.cursor()
2293
2294
        cursor.execute(" SELECT name "
2295
                       " FROM tbl_spaces "
2296
                       " WHERE id = %s ", (id_,))
2297
        if cursor.fetchone() is None:
2298
            cursor.close()
2299
            cnx.disconnect()
2300
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2301
                                   description='API.SPACE_NOT_FOUND')
2302
2303
        cursor.execute(" SELECT name "
2304
                       " FROM tbl_tenants "
2305
                       " WHERE id = %s ", (tid,))
2306
        if cursor.fetchone() is None:
2307
            cursor.close()
2308
            cnx.disconnect()
2309
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2310
                                   description='API.TENANT_NOT_FOUND')
2311
2312
        cursor.execute(" SELECT id "
2313
                       " FROM tbl_spaces_tenants "
2314
                       " WHERE space_id = %s AND tenant_id = %s ", (id_, tid))
2315
        if cursor.fetchone() is None:
2316
            cursor.close()
2317
            cnx.disconnect()
2318
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2319
                                   description='API.SPACE_TENANT_RELATION_NOT_FOUND')
2320
2321
        cursor.execute(" DELETE FROM tbl_spaces_tenants WHERE space_id = %s AND tenant_id = %s ", (id_, tid))
2322
        cnx.commit()
2323
2324
        cursor.close()
2325
        cnx.disconnect()
2326
2327
        resp.status = falcon.HTTP_204
2328
2329
2330 View Code Duplication
class SpaceVirtualMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2331
    @staticmethod
2332
    def __init__():
2333
        pass
2334
2335
    @staticmethod
2336
    def on_options(req, resp, id_):
2337
        resp.status = falcon.HTTP_200
2338
2339
    @staticmethod
2340
    def on_get(req, resp, id_):
2341
        if not id_.isdigit() or int(id_) <= 0:
2342
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2343
                                   description='API.INVALID_SPACE_ID')
2344
2345
        cnx = mysql.connector.connect(**config.myems_system_db)
2346
        cursor = cnx.cursor(dictionary=True)
2347
2348
        cursor.execute(" SELECT name "
2349
                       " FROM tbl_spaces "
2350
                       " WHERE id = %s ", (id_,))
2351
        if cursor.fetchone() is None:
2352
            cursor.close()
2353
            cnx.disconnect()
2354
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2355
                                   description='API.SPACE_NOT_FOUND')
2356
2357
        query = (" SELECT id, name, uuid "
2358
                 " FROM tbl_energy_categories ")
2359
        cursor.execute(query)
2360
        rows_energy_categories = cursor.fetchall()
2361
2362
        energy_category_dict = dict()
2363
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
2364
            for row in rows_energy_categories:
2365
                energy_category_dict[row['id']] = {"id": row['id'],
2366
                                                   "name": row['name'],
2367
                                                   "uuid": row['uuid']}
2368
2369
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
2370
                 " FROM tbl_spaces s, tbl_spaces_virtual_meters sm, tbl_virtual_meters m "
2371
                 " WHERE sm.space_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
2372
                 " ORDER BY m.id ")
2373
        cursor.execute(query, (id_,))
2374
        rows = cursor.fetchall()
2375
2376
        result = list()
2377
        if rows is not None and len(rows) > 0:
2378
            for row in rows:
2379
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
2380
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
2381
                               "energy_category": energy_category}
2382
                result.append(meta_result)
2383
2384
        resp.body = json.dumps(result)
2385
2386
    @staticmethod
2387
    def on_post(req, resp, id_):
2388
        """Handles POST requests"""
2389
        try:
2390
            raw_json = req.stream.read().decode('utf-8')
2391
        except Exception as ex:
2392
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
2393
2394
        if not id_.isdigit() or int(id_) <= 0:
2395
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2396
                                   description='API.INVALID_SPACE_ID')
2397
2398
        new_values = json.loads(raw_json)
2399
2400
        if 'virtual_meter_id' not in new_values['data'].keys() or \
2401
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
2402
                new_values['data']['virtual_meter_id'] <= 0:
2403
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2404
                                   description='API.INVALID_VIRTUAL_METER_ID')
2405
        virtual_meter_id = new_values['data']['virtual_meter_id']
2406
2407
        cnx = mysql.connector.connect(**config.myems_system_db)
2408
        cursor = cnx.cursor()
2409
2410
        cursor.execute(" SELECT name "
2411
                       " from tbl_spaces "
2412
                       " WHERE id = %s ", (id_,))
2413
        if cursor.fetchone() is None:
2414
            cursor.close()
2415
            cnx.disconnect()
2416
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2417
                                   description='API.SPACE_NOT_FOUND')
2418
2419
        cursor.execute(" SELECT name "
2420
                       " FROM tbl_virtual_meters "
2421
                       " WHERE id = %s ", (virtual_meter_id,))
2422
        if cursor.fetchone() is None:
2423
            cursor.close()
2424
            cnx.disconnect()
2425
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2426
                                   description='API.VIRTUAL_METER_NOT_FOUND')
2427
2428
        query = (" SELECT id " 
2429
                 " FROM tbl_spaces_virtual_meters "
2430
                 " WHERE space_id = %s AND virtual_meter_id = %s")
2431
        cursor.execute(query, (id_, virtual_meter_id,))
2432
        if cursor.fetchone() is not None:
2433
            cursor.close()
2434
            cnx.disconnect()
2435
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
2436
                                   description='API.SPACE_VIRTUAL_METER_RELATION_EXISTED')
2437
2438
        add_row = (" INSERT INTO tbl_spaces_virtual_meters (space_id, virtual_meter_id) "
2439
                   " VALUES (%s, %s) ")
2440
        cursor.execute(add_row, (id_, virtual_meter_id,))
2441
        new_id = cursor.lastrowid
2442
        cnx.commit()
2443
        cursor.close()
2444
        cnx.disconnect()
2445
2446
        resp.status = falcon.HTTP_201
2447
        resp.location = '/spaces/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
2448
2449
2450 View Code Duplication
class SpaceVirtualMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2451
    @staticmethod
2452
    def __init__():
2453
        pass
2454
2455
    @staticmethod
2456
    def on_options(req, resp, id_, mid):
2457
            resp.status = falcon.HTTP_200
2458
2459
    @staticmethod
2460
    def on_delete(req, resp, id_, mid):
2461
        if not id_.isdigit() or int(id_) <= 0:
2462
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2463
                                   description='API.INVALID_SPACE_ID')
2464
2465
        if not mid.isdigit() or int(mid) <= 0:
2466
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2467
                                   description='API.INVALID_VIRTUAL_METER_ID')
2468
2469
        cnx = mysql.connector.connect(**config.myems_system_db)
2470
        cursor = cnx.cursor()
2471
2472
        cursor.execute(" SELECT name "
2473
                       " FROM tbl_spaces "
2474
                       " WHERE id = %s ", (id_,))
2475
        if cursor.fetchone() is None:
2476
            cursor.close()
2477
            cnx.disconnect()
2478
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2479
                                   description='API.SPACE_NOT_FOUND')
2480
2481
        cursor.execute(" SELECT name "
2482
                       " FROM tbl_virtual_meters "
2483
                       " WHERE id = %s ", (mid,))
2484
        if cursor.fetchone() is None:
2485
            cursor.close()
2486
            cnx.disconnect()
2487
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2488
                                   description='API.VIRTUAL_METER_NOT_FOUND')
2489
2490
        cursor.execute(" SELECT id "
2491
                       " FROM tbl_spaces_virtual_meters "
2492
                       " WHERE space_id = %s AND virtual_meter_id = %s ", (id_, mid))
2493
        if cursor.fetchone() is None:
2494
            cursor.close()
2495
            cnx.disconnect()
2496
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2497
                                   description='API.SPACE_VIRTUAL_METER_RELATION_NOT_FOUND')
2498
2499
        cursor.execute(" DELETE FROM tbl_spaces_virtual_meters "
2500
                       " WHERE space_id = %s AND virtual_meter_id = %s ", (id_, mid))
2501
        cnx.commit()
2502
2503
        cursor.close()
2504
        cnx.disconnect()
2505
2506
        resp.status = falcon.HTTP_204
2507
2508
2509
class SpaceTreeCollection:
2510
    @staticmethod
2511
    def __init__():
2512
        pass
2513
2514
    @staticmethod
2515
    def on_options(req, resp):
2516
        resp.status = falcon.HTTP_200
2517
2518
    @staticmethod
2519
    def on_get(req, resp):
2520
        if 'USER-UUID' not in req.headers or \
2521
                not isinstance(req.headers['USER-UUID'], str) or \
2522
                len(str.strip(req.headers['USER-UUID'])) == 0:
2523
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2524
                                   description='API.INVALID_USER_UUID')
2525
        user_uuid = str.strip(req.headers['USER-UUID'])
2526
2527
        if 'TOKEN' not in req.headers or \
2528
                not isinstance(req.headers['TOKEN'], str) or \
2529
                len(str.strip(req.headers['TOKEN'])) == 0:
2530
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2531
                                   description='API.INVALID_TOKEN')
2532
        token = str.strip(req.headers['TOKEN'])
2533
2534
        # Verify User Session
2535
        cnx = mysql.connector.connect(**config.myems_user_db)
2536
        cursor = cnx.cursor()
2537
        query = (" SELECT utc_expires "
2538
                 " FROM tbl_sessions "
2539
                 " WHERE user_uuid = %s AND token = %s")
2540
        cursor.execute(query, (user_uuid, token,))
2541
        row = cursor.fetchone()
2542
2543 View Code Duplication
        if row is None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2544
            cursor.close()
2545
            cnx.disconnect()
2546
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2547
                                   description='API.USER_SESSION_NOT_FOUND')
2548
        else:
2549
            utc_expires = row[0]
2550
            if datetime.utcnow() > utc_expires:
2551
                cursor.close()
2552
                cnx.disconnect()
2553
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2554
                                       description='API.USER_SESSION_TIMEOUT')
2555
        # get privilege
2556
        query = (" SELECT is_admin, privilege_id "
2557
                 " FROM tbl_users "
2558
                 " WHERE uuid = %s ")
2559
        cursor.execute(query, (user_uuid,))
2560
        row = cursor.fetchone()
2561
        if row is None:
2562
            cursor.close()
2563
            cnx.disconnect()
2564
            raise falcon.HTTPError(falcon.HTTP_404, 'API.NOT_FOUND', 'API.USER_NOT_FOUND')
2565
        else:
2566
            is_admin = bool(row[0])
2567
            privilege_id = row[1]
2568
2569
        # get space_id in privilege
2570
        if is_admin:
2571
            space_id = 1
2572
        elif privilege_id is None:
2573
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2574
                                   description='API.PRIVILEGE_NOT_FOUND')
2575
        else:
2576
            query = (" SELECT data "
2577
                     " FROM tbl_privileges "
2578
                     " WHERE id =%s ")
2579
            cursor.execute(query, (privilege_id,))
2580
            row = cursor.fetchone()
2581
            cursor.close()
2582
            cnx.disconnect()
2583
2584
            if row is None:
2585
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2586
                                       description='API.PRIVILEGE_NOT_FOUND')
2587
            try:
2588
                data = json.loads(row[0])
2589
            except Exception as ex:
2590
                raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex)
2591
2592
            if 'spaces' not in data or len(data['spaces']) == 0:
2593
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2594
                                       description='API.SPACE_NOT_FOUND_IN_PRIVILEGE')
2595
2596
            space_id = data['spaces'][0]
2597
            if space_id is None:
2598
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2599
                                       description='API.PRIVILEGE_NOT_FOUND')
2600
        # get all spaces
2601
        cnx = mysql.connector.connect(**config.myems_system_db)
2602
        cursor = cnx.cursor(dictionary=True)
2603
2604
        query = (" SELECT id, name, parent_space_id "
2605
                 " FROM tbl_spaces "
2606
                 " ORDER BY id ")
2607
        cursor.execute(query)
2608
        rows_spaces = cursor.fetchall()
2609
        node_dict = dict()
2610
        if rows_spaces is not None and len(rows_spaces) > 0:
2611
            for row in rows_spaces:
2612
                parent_node = node_dict[row['parent_space_id']] if row['parent_space_id'] is not None else None
2613
                node_dict[row['id']] = AnyNode(id=row['id'], parent=parent_node, name=row['name'])
2614
2615
        cursor.close()
2616
        cnx.disconnect()
2617
        resp.body = JsonExporter(sort_keys=True).export(node_dict[space_id], )
2618