Passed
Push — master ( e3d886...c0116c )
by Guangyu
08:32 queued 12s
created

core.shopfloor.ShopfloorItem.on_get()   C

Complexity

Conditions 10

Size

Total Lines 59
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 45
dl 0
loc 59
rs 5.9999
c 0
b 0
f 0
cc 10
nop 3

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

Complexity

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

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

1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
import uuid
6
from core.useractivity import user_logger, access_control
7
8
9
class ShopfloorCollection:
10
    @staticmethod
11
    def __init__():
12
        """Initializes ShopfloorCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    @staticmethod
20
    def on_get(req, resp):
21
        cnx = mysql.connector.connect(**config.myems_system_db)
22
        cursor = cnx.cursor(dictionary=True)
23
24
        query = (" SELECT id, name, uuid "
25
                 " FROM tbl_contacts ")
26
        cursor.execute(query)
27
        rows_contacts = cursor.fetchall()
28
29
        contact_dict = dict()
30
        if rows_contacts is not None and len(rows_contacts) > 0:
31
            for row in rows_contacts:
32
                contact_dict[row['id']] = {"id": row['id'],
33
                                           "name": row['name'],
34
                                           "uuid": row['uuid']}
35
36
        query = (" SELECT id, name, uuid "
37
                 " FROM tbl_cost_centers ")
38
        cursor.execute(query)
39
        rows_cost_centers = cursor.fetchall()
40
41
        cost_center_dict = dict()
42
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
43
            for row in rows_cost_centers:
44
                cost_center_dict[row['id']] = {"id": row['id'],
45
                                               "name": row['name'],
46
                                               "uuid": row['uuid']}
47
48
        query = (" SELECT id, name, uuid, "
49
                 "        area, is_input_counted, "
50
                 "        contact_id, cost_center_id, description "
51
                 " FROM tbl_shopfloors "
52
                 " ORDER BY id ")
53
        cursor.execute(query)
54
        rows_shopfloors = cursor.fetchall()
55
56
        result = list()
57
        if rows_shopfloors is not None and len(rows_shopfloors) > 0:
58
            for row in rows_shopfloors:
59
                contact = contact_dict.get(row['contact_id'], None)
60
                cost_center = cost_center_dict.get(row['cost_center_id'], None)
61
                meta_result = {"id": row['id'],
62
                               "name": row['name'],
63
                               "uuid": row['uuid'],
64
                               "area": row['area'],
65
                               "is_input_counted": bool(row['is_input_counted']),
66
                               "contact": contact,
67
                               "cost_center": cost_center,
68
                               "description": row['description'],
69
                               "qrcode": "shopfloor:" + row['uuid']}
70
                result.append(meta_result)
71
72
        cursor.close()
73
        cnx.disconnect()
74
        resp.text = json.dumps(result)
75
76
    @staticmethod
77
    @user_logger
78
    def on_post(req, resp):
79
        """Handles POST requests"""
80
        access_control(req)
81
        try:
82
            raw_json = req.stream.read().decode('utf-8')
83
        except Exception as ex:
84
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex)
85
86
        new_values = json.loads(raw_json)
87
88
        if 'name' not in new_values['data'].keys() or \
89
                not isinstance(new_values['data']['name'], str) or \
90
                len(str.strip(new_values['data']['name'])) == 0:
91
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
92
                                   description='API.INVALID_SHOPFLOOR_NAME')
93
        name = str.strip(new_values['data']['name'])
94
95
        if 'area' not in new_values['data'].keys() or \
96
                not (isinstance(new_values['data']['area'], float) or
97
                     isinstance(new_values['data']['area'], int)) or \
98
                new_values['data']['area'] <= 0.0:
99
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
100
                                   description='API.INVALID_AREA_VALUE')
101
        area = new_values['data']['area']
102
103
        if 'is_input_counted' not in new_values['data'].keys() or \
104
                not isinstance(new_values['data']['is_input_counted'], bool):
105
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
106
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
107
        is_input_counted = new_values['data']['is_input_counted']
108
109
        if 'contact_id' in new_values['data'].keys():
110
            if new_values['data']['contact_id'] <= 0:
111
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
112
                                       description='API.INVALID_CONTACT_ID')
113
            contact_id = new_values['data']['contact_id']
114
        else:
115
            contact_id = None
116
117
        if 'cost_center_id' in new_values['data'].keys():
118
            if new_values['data']['cost_center_id'] <= 0:
119
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
120
                                       description='API.INVALID_COST_CENTER_ID')
121
            cost_center_id = new_values['data']['cost_center_id']
122
        else:
123
            cost_center_id = None
124
125
        if 'description' in new_values['data'].keys() and \
126
                new_values['data']['description'] is not None and \
127
                len(str(new_values['data']['description'])) > 0:
128
            description = str.strip(new_values['data']['description'])
129
        else:
130
            description = None
131
132
        cnx = mysql.connector.connect(**config.myems_system_db)
133
        cursor = cnx.cursor()
134
135
        cursor.execute(" SELECT name "
136
                       " FROM tbl_shopfloors "
137
                       " WHERE name = %s ", (name,))
138
        if cursor.fetchone() is not None:
139
            cursor.close()
140
            cnx.disconnect()
141
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
142
                                   description='API.SHOPFLOOR_NAME_IS_ALREADY_IN_USE')
143
144 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...
145
            cursor.execute(" SELECT name "
146
                           " FROM tbl_contacts "
147
                           " WHERE id = %s ",
148
                           (new_values['data']['contact_id'],))
149
            row = cursor.fetchone()
150
            if row is None:
151
                cursor.close()
152
                cnx.disconnect()
153
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
154
                                       description='API.CONTACT_NOT_FOUND')
155
156
        if cost_center_id is not None:
157
            cursor.execute(" SELECT name "
158
                           " FROM tbl_cost_centers "
159
                           " WHERE id = %s ",
160
                           (new_values['data']['cost_center_id'],))
161
            row = cursor.fetchone()
162
            if row is None:
163
                cursor.close()
164
                cnx.disconnect()
165
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
166
                                       description='API.COST_CENTER_NOT_FOUND')
167
168
        add_values = (" INSERT INTO tbl_shopfloors "
169
                      "    (name, uuid, area, is_input_counted, "
170
                      "     contact_id, cost_center_id, description) "
171
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
172
        cursor.execute(add_values, (name,
173
                                    str(uuid.uuid4()),
174
                                    area,
175
                                    is_input_counted,
176
                                    contact_id,
177
                                    cost_center_id,
178
                                    description))
179
        new_id = cursor.lastrowid
180
        cnx.commit()
181
        cursor.close()
182
        cnx.disconnect()
183
184
        resp.status = falcon.HTTP_201
185
        resp.location = '/shopfloors/' + str(new_id)
186
187
188
class ShopfloorItem:
189
    @staticmethod
190
    def __init__():
191
        """Initializes ShopfloorItem"""
192
        pass
193
194
    @staticmethod
195
    def on_options(req, resp, id_):
196
        resp.status = falcon.HTTP_200
197
198
    @staticmethod
199
    def on_get(req, resp, id_):
200
        if not id_.isdigit() or int(id_) <= 0:
201
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
202
                                   description='API.INVALID_SHOPFLOOR_ID')
203
204
        cnx = mysql.connector.connect(**config.myems_system_db)
205
        cursor = cnx.cursor(dictionary=True)
206
207
        query = (" SELECT id, name, uuid "
208
                 " FROM tbl_contacts ")
209
        cursor.execute(query)
210
        rows_contacts = cursor.fetchall()
211
212
        contact_dict = dict()
213
        if rows_contacts is not None and len(rows_contacts) > 0:
214
            for row in rows_contacts:
215
                contact_dict[row['id']] = {"id": row['id'],
216
                                           "name": row['name'],
217
                                           "uuid": row['uuid']}
218
219
        query = (" SELECT id, name, uuid "
220
                 " FROM tbl_cost_centers ")
221
        cursor.execute(query)
222
        rows_cost_centers = cursor.fetchall()
223
224
        cost_center_dict = dict()
225
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
226
            for row in rows_cost_centers:
227
                cost_center_dict[row['id']] = {"id": row['id'],
228
                                               "name": row['name'],
229
                                               "uuid": row['uuid']}
230
231
        query = (" SELECT id, name, uuid, "
232
                 "        area, is_input_counted, contact_id, cost_center_id, description "
233
                 " FROM tbl_shopfloors "
234
                 " WHERE id = %s ")
235
        cursor.execute(query, (id_,))
236
        row = cursor.fetchone()
237
        cursor.close()
238
        cnx.disconnect()
239
240
        if row is None:
241
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
242
                                   description='API.SHOPFLOOR_NOT_FOUND')
243
        else:
244
            contact = contact_dict.get(row['contact_id'], None)
245
            cost_center = cost_center_dict.get(row['cost_center_id'], None)
246
            meta_result = {"id": row['id'],
247
                           "name": row['name'],
248
                           "uuid": row['uuid'],
249
                           "area": row['area'],
250
                           "is_input_counted": bool(row['is_input_counted']),
251
                           "contact": contact,
252
                           "cost_center": cost_center,
253
                           "description": row['description'],
254
                           "qrcode": "shopfloor:" + row['uuid']}
255
256
        resp.text = json.dumps(meta_result)
257
258
    @staticmethod
259
    @user_logger
260
    def on_delete(req, resp, id_):
261
        access_control(req)
262
        if not id_.isdigit() or int(id_) <= 0:
263
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
264
                                   description='API.INVALID_SHOPFLOOR_ID')
265
        if int(id_) == 1:
266
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
267
                                   description='API.THIS_SHOPFLOOR_CANNOT_BE_DELETED')
268
269
        cnx = mysql.connector.connect(**config.myems_system_db)
270
        cursor = cnx.cursor()
271
272
        cursor.execute(" SELECT name "
273
                       " FROM tbl_shopfloors "
274
                       " WHERE id = %s ", (id_,))
275
        if cursor.fetchone() is None:
276
            cursor.close()
277
            cnx.disconnect()
278
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
279
                                   description='API.SHOPFLOOR_NOT_FOUND')
280
281
        # check relation with spaces
282
        cursor.execute(" SELECT space_id "
283
                       " FROM tbl_spaces_shopfloors "
284
                       " WHERE shopfloor_id = %s ",
285
                       (id_,))
286
        rows_spaces = cursor.fetchall()
287
        if rows_spaces is not None and len(rows_spaces) > 0:
288
            cursor.close()
289
            cnx.disconnect()
290
            raise falcon.HTTPError(falcon.HTTP_400,
291
                                   title='API.BAD_REQUEST',
292
                                   description='API.THERE_IS_RELATION_WITH_SPACES')
293
294
        # check relation with equipments
295
        cursor.execute(" SELECT equipment_id "
296
                       " FROM tbl_shopfloors_equipments "
297
                       " WHERE shopfloor_id = %s ",
298
                       (id_,))
299
        rows_equipments = cursor.fetchall()
300
        if rows_equipments is not None and len(rows_equipments) > 0:
301
            cursor.close()
302
            cnx.disconnect()
303
            raise falcon.HTTPError(falcon.HTTP_400,
304
                                   title='API.BAD_REQUEST',
305
                                   description='API.THERE_IS_RELATION_WITH_EQUIPMENTS')
306
307
        # check relation with meters
308
        cursor.execute(" SELECT meter_id "
309
                       " FROM tbl_shopfloors_meters "
310
                       " WHERE shopfloor_id = %s ",
311
                       (id_,))
312
        rows_meters = cursor.fetchall()
313
        if rows_meters is not None and len(rows_meters) > 0:
314
            cursor.close()
315
            cnx.disconnect()
316
            raise falcon.HTTPError(falcon.HTTP_400,
317
                                   title='API.BAD_REQUEST',
318
                                   description='API.THERE_IS_RELATION_WITH_METERS')
319
320
        # check relation with offline meters
321
        cursor.execute(" SELECT offline_meter_id "
322
                       " FROM tbl_shopfloors_offline_meters "
323
                       " WHERE shopfloor_id = %s ",
324
                       (id_,))
325
        rows_offline_meters = cursor.fetchall()
326
        if rows_offline_meters is not None and len(rows_offline_meters) > 0:
327
            cursor.close()
328
            cnx.disconnect()
329
            raise falcon.HTTPError(falcon.HTTP_400,
330
                                   title='API.BAD_REQUEST',
331
                                   description='API.THERE_IS_RELATION_WITH_OFFLINE_METERS')
332
333
        # check relation with points
334
        cursor.execute(" SELECT point_id "
335
                       " FROM tbl_shopfloors_points "
336
                       " WHERE shopfloor_id = %s ", (id_,))
337
        rows_points = cursor.fetchall()
338
        if rows_points is not None and len(rows_points) > 0:
339
            cursor.close()
340
            cnx.disconnect()
341
            raise falcon.HTTPError(falcon.HTTP_400,
342
                                   title='API.BAD_REQUEST',
343
                                   description='API.THERE_IS_RELATION_WITH_POINTS')
344
345
        # check relation with sensor
346
        cursor.execute(" SELECT sensor_id "
347
                       " FROM tbl_shopfloors_sensors "
348
                       " WHERE shopfloor_id = %s ",
349
                       (id_,))
350
        rows_sensors = cursor.fetchall()
351
        if rows_sensors is not None and len(rows_sensors) > 0:
352
            cursor.close()
353
            cnx.disconnect()
354
            raise falcon.HTTPError(falcon.HTTP_400,
355
                                   title='API.BAD_REQUEST',
356
                                   description='API.THERE_IS_RELATION_WITH_SENSORS')
357
358
        # check relation with virtual meter
359
        cursor.execute(" SELECT virtual_meter_id "
360
                       " FROM tbl_shopfloors_virtual_meters "
361
                       " WHERE shopfloor_id = %s ",
362
                       (id_,))
363
        rows_virtual_meters = cursor.fetchall()
364
        if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
365
            cursor.close()
366
            cnx.disconnect()
367
            raise falcon.HTTPError(falcon.HTTP_400,
368
                                   title='API.BAD_REQUEST',
369
                                   description='API.THERE_IS_RELATION_WITH_VIRTUAL_METERS')
370
371
        cursor.execute(" DELETE FROM tbl_shopfloors WHERE id = %s ", (id_,))
372
        cnx.commit()
373
374
        cursor.close()
375
        cnx.disconnect()
376
377
        resp.status = falcon.HTTP_204
378
379
    @staticmethod
380
    @user_logger
381
    def on_put(req, resp, id_):
382
        """Handles PUT requests"""
383
        access_control(req)
384
        try:
385
            raw_json = req.stream.read().decode('utf-8')
386
        except Exception as ex:
387
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
388
389
        if not id_.isdigit() or int(id_) <= 0:
390
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
391
                                   description='API.INVALID_SHOPFLOOR_ID')
392
393
        new_values = json.loads(raw_json)
394
395
        if 'name' not in new_values['data'].keys() or \
396
                not isinstance(new_values['data']['name'], str) or \
397
                len(str.strip(new_values['data']['name'])) == 0:
398
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
399
                                   description='API.INVALID_SHOPFLOOR_NAME')
400
        name = str.strip(new_values['data']['name'])
401
402
        if 'area' not in new_values['data'].keys() or \
403
                not (isinstance(new_values['data']['area'], float) or
404
                     isinstance(new_values['data']['area'], int)) or \
405
                new_values['data']['area'] <= 0.0:
406
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
407
                                   description='API.INVALID_AREA_VALUE')
408
        area = new_values['data']['area']
409
410
        if 'is_input_counted' not in new_values['data'].keys() or \
411
                not isinstance(new_values['data']['is_input_counted'], bool):
412
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
413
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
414
        is_input_counted = new_values['data']['is_input_counted']
415
416
        if 'contact_id' in new_values['data'].keys():
417
            if new_values['data']['contact_id'] <= 0:
418
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
419
                                       description='API.INVALID_CONTACT_ID')
420
            contact_id = new_values['data']['contact_id']
421
        else:
422
            contact_id = None
423
424
        if 'cost_center_id' in new_values['data'].keys():
425
            if new_values['data']['cost_center_id'] <= 0:
426
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
427
                                       description='API.INVALID_COST_CENTER_ID')
428
            cost_center_id = new_values['data']['cost_center_id']
429
        else:
430
            cost_center_id = None
431
432
        if 'description' in new_values['data'].keys() and \
433
                new_values['data']['description'] is not None and \
434
                len(str(new_values['data']['description'])) > 0:
435
            description = str.strip(new_values['data']['description'])
436
        else:
437
            description = None
438
439
        cnx = mysql.connector.connect(**config.myems_system_db)
440
        cursor = cnx.cursor()
441
442
        cursor.execute(" SELECT name "
443
                       " FROM tbl_shopfloors "
444
                       " WHERE id = %s ", (id_,))
445
        if cursor.fetchone() is None:
446
            cursor.close()
447
            cnx.disconnect()
448
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
449
                                   description='API.SHOPFLOOR_NOT_FOUND')
450
451
        cursor.execute(" SELECT name "
452
                       " FROM tbl_shopfloors "
453
                       " WHERE name = %s AND id != %s ", (name, id_))
454
        if cursor.fetchone() is not None:
455
            cursor.close()
456
            cnx.disconnect()
457
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
458
                                   description='API.SHOPFLOOR_NAME_IS_ALREADY_IN_USE')
459
460 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...
461
            cursor.execute(" SELECT name "
462
                           " FROM tbl_contacts "
463
                           " WHERE id = %s ",
464
                           (new_values['data']['contact_id'],))
465
            row = cursor.fetchone()
466
            if row is None:
467
                cursor.close()
468
                cnx.disconnect()
469
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
470
                                       description='API.CONTACT_NOT_FOUND')
471
472
        if cost_center_id is not None:
473
            cursor.execute(" SELECT name "
474
                           " FROM tbl_cost_centers "
475
                           " WHERE id = %s ",
476
                           (new_values['data']['cost_center_id'],))
477
            row = cursor.fetchone()
478
            if row is None:
479
                cursor.close()
480
                cnx.disconnect()
481
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
482
                                       description='API.COST_CENTER_NOT_FOUND')
483
484
        update_row = (" UPDATE tbl_shopfloors "
485
                      " SET name = %s, area = %s, is_input_counted = %s, contact_id = %s, cost_center_id = %s, "
486
                      "     description = %s "
487
                      " WHERE id = %s ")
488
        cursor.execute(update_row, (name,
489
                                    area,
490
                                    is_input_counted,
491
                                    contact_id,
492
                                    cost_center_id,
493
                                    description,
494
                                    id_))
495
        cnx.commit()
496
497
        cursor.close()
498
        cnx.disconnect()
499
500
        resp.status = falcon.HTTP_200
501
502
503 View Code Duplication
class ShopfloorEquipmentCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
504
    @staticmethod
505
    def __init__():
506
        """Initializes ShopfloorEquipmentCollection"""
507
        pass
508
509
    @staticmethod
510
    def on_options(req, resp, id_):
511
        resp.status = falcon.HTTP_200
512
513
    @staticmethod
514
    def on_get(req, resp, id_):
515
        if not id_.isdigit() or int(id_) <= 0:
516
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
517
                                   description='API.INVALID_SHOPFLOOR_ID')
518
519
        cnx = mysql.connector.connect(**config.myems_system_db)
520
        cursor = cnx.cursor()
521
522
        cursor.execute(" SELECT name "
523
                       " FROM tbl_shopfloors "
524
                       " WHERE id = %s ", (id_,))
525
        if cursor.fetchone() is None:
526
            cursor.close()
527
            cnx.disconnect()
528
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
529
                                   description='API.SHOPFLOOR_NOT_FOUND')
530
531
        query = (" SELECT e.id, e.name, e.uuid "
532
                 " FROM tbl_shopfloors s, tbl_shopfloors_equipments se, tbl_equipments e "
533
                 " WHERE se.shopfloor_id = s.id AND e.id = se.equipment_id AND s.id = %s "
534
                 " ORDER BY e.id ")
535
        cursor.execute(query, (id_,))
536
        rows = cursor.fetchall()
537
538
        result = list()
539
        if rows is not None and len(rows) > 0:
540
            for row in rows:
541
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
542
                result.append(meta_result)
543
544
        resp.text = json.dumps(result)
545
546
    @staticmethod
547
    @user_logger
548
    def on_post(req, resp, id_):
549
        """Handles POST requests"""
550
        access_control(req)
551
        try:
552
            raw_json = req.stream.read().decode('utf-8')
553
        except Exception as ex:
554
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
555
556
        if not id_.isdigit() or int(id_) <= 0:
557
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
558
                                   description='API.INVALID_SHOPFLOOR_ID')
559
560
        new_values = json.loads(raw_json)
561
562
        if 'equipment_id' not in new_values['data'].keys() or \
563
                not isinstance(new_values['data']['equipment_id'], int) or \
564
                new_values['data']['equipment_id'] <= 0:
565
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
566
                                   description='API.INVALID_EQUIPMENT_ID')
567
        equipment_id = new_values['data']['equipment_id']
568
569
        cnx = mysql.connector.connect(**config.myems_system_db)
570
        cursor = cnx.cursor()
571
572
        cursor.execute(" SELECT name "
573
                       " from tbl_shopfloors "
574
                       " WHERE id = %s ", (id_,))
575
        if cursor.fetchone() is None:
576
            cursor.close()
577
            cnx.disconnect()
578
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
579
                                   description='API.SHOPFLOOR_NOT_FOUND')
580
581
        cursor.execute(" SELECT name "
582
                       " FROM tbl_equipments "
583
                       " WHERE id = %s ", (equipment_id,))
584
        if cursor.fetchone() is None:
585
            cursor.close()
586
            cnx.disconnect()
587
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
588
                                   description='API.EQUIPMENT_NOT_FOUND')
589
590
        query = (" SELECT id " 
591
                 " FROM tbl_shopfloors_equipments "
592
                 " WHERE shopfloor_id = %s AND equipment_id = %s")
593
        cursor.execute(query, (id_, equipment_id,))
594
        if cursor.fetchone() is not None:
595
            cursor.close()
596
            cnx.disconnect()
597
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
598
                                   description='API.SHOPFLOOR_EQUIPMENT_RELATION_EXISTS')
599
600
        add_row = (" INSERT INTO tbl_shopfloors_equipments (shopfloor_id, equipment_id) "
601
                   " VALUES (%s, %s) ")
602
        cursor.execute(add_row, (id_, equipment_id,))
603
        new_id = cursor.lastrowid
604
        cnx.commit()
605
        cursor.close()
606
        cnx.disconnect()
607
608
        resp.status = falcon.HTTP_201
609
        resp.location = '/shopfloors/' + str(id_) + '/equipments/' + str(equipment_id)
610
611
612 View Code Duplication
class ShopfloorEquipmentItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
613
    @staticmethod
614
    def __init__():
615
        """Initializes ShopfloorEquipmentItem"""
616
        pass
617
618
    @staticmethod
619
    def on_options(req, resp, id_, eid):
620
        resp.status = falcon.HTTP_200
621
622
    @staticmethod
623
    @user_logger
624
    def on_delete(req, resp, id_, eid):
625
        access_control(req)
626
        if not id_.isdigit() or int(id_) <= 0:
627
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
628
                                   description='API.INVALID_SHOPFLOOR_ID')
629
630
        if not eid.isdigit() or int(eid) <= 0:
631
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
632
                                   description='API.INVALID_EQUIPMENT_ID')
633
634
        cnx = mysql.connector.connect(**config.myems_system_db)
635
        cursor = cnx.cursor()
636
637
        cursor.execute(" SELECT name "
638
                       " FROM tbl_shopfloors "
639
                       " WHERE id = %s ", (id_,))
640
        if cursor.fetchone() is None:
641
            cursor.close()
642
            cnx.disconnect()
643
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
644
                                   description='API.SHOPFLOOR_NOT_FOUND')
645
646
        cursor.execute(" SELECT name "
647
                       " FROM tbl_equipments "
648
                       " WHERE id = %s ", (eid,))
649
        if cursor.fetchone() is None:
650
            cursor.close()
651
            cnx.disconnect()
652
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
653
                                   description='API.EQUIPMENT_NOT_FOUND')
654
655
        cursor.execute(" SELECT id "
656
                       " FROM tbl_shopfloors_equipments "
657
                       " WHERE shopfloor_id = %s AND equipment_id = %s ", (id_, eid))
658
        if cursor.fetchone() is None:
659
            cursor.close()
660
            cnx.disconnect()
661
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
662
                                   description='API.SHOPFLOOR_EQUIPMENT_RELATION_NOT_FOUND')
663
664
        cursor.execute(" DELETE FROM tbl_shopfloors_equipments "
665
                       " WHERE shopfloor_id = %s AND equipment_id = %s ", (id_, eid))
666
        cnx.commit()
667
668
        cursor.close()
669
        cnx.disconnect()
670
671
        resp.status = falcon.HTTP_204
672
673
674 View Code Duplication
class ShopfloorMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
675
    @staticmethod
676
    def __init__():
677
        """Initializes ShopfloorMeterCollection"""
678
        pass
679
680
    @staticmethod
681
    def on_options(req, resp, id_):
682
        resp.status = falcon.HTTP_200
683
684
    @staticmethod
685
    def on_get(req, resp, id_):
686
        if not id_.isdigit() or int(id_) <= 0:
687
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
688
                                   description='API.INVALID_SHOPFLOOR_ID')
689
690
        cnx = mysql.connector.connect(**config.myems_system_db)
691
        cursor = cnx.cursor(dictionary=True)
692
693
        cursor.execute(" SELECT name "
694
                       " FROM tbl_shopfloors "
695
                       " WHERE id = %s ", (id_,))
696
        if cursor.fetchone() is None:
697
            cursor.close()
698
            cnx.disconnect()
699
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
700
                                   description='API.SHOPFLOOR_NOT_FOUND')
701
702
        query = (" SELECT id, name, uuid "
703
                 " FROM tbl_energy_categories ")
704
        cursor.execute(query)
705
        rows_energy_categories = cursor.fetchall()
706
707
        energy_category_dict = dict()
708
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
709
            for row in rows_energy_categories:
710
                energy_category_dict[row['id']] = {"id": row['id'],
711
                                                   "name": row['name'],
712
                                                   "uuid": row['uuid']}
713
714
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
715
                 " FROM tbl_shopfloors s, tbl_shopfloors_meters sm, tbl_meters m "
716
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.meter_id AND s.id = %s "
717
                 " ORDER BY m.id ")
718
        cursor.execute(query, (id_,))
719
        rows = cursor.fetchall()
720
721
        result = list()
722
        if rows is not None and len(rows) > 0:
723
            for row in rows:
724
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
725
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
726
                               "energy_category": energy_category}
727
                result.append(meta_result)
728
729
        resp.text = json.dumps(result)
730
731
    @staticmethod
732
    @user_logger
733
    def on_post(req, resp, id_):
734
        """Handles POST requests"""
735
        access_control(req)
736
        try:
737
            raw_json = req.stream.read().decode('utf-8')
738
        except Exception as ex:
739
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
740
741
        if not id_.isdigit() or int(id_) <= 0:
742
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
743
                                   description='API.INVALID_SHOPFLOOR_ID')
744
745
        new_values = json.loads(raw_json)
746
747
        if 'meter_id' not in new_values['data'].keys() or \
748
                not isinstance(new_values['data']['meter_id'], int) or \
749
                new_values['data']['meter_id'] <= 0:
750
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
751
                                   description='API.INVALID_METER_ID')
752
        meter_id = new_values['data']['meter_id']
753
754
        cnx = mysql.connector.connect(**config.myems_system_db)
755
        cursor = cnx.cursor()
756
757
        cursor.execute(" SELECT name "
758
                       " from tbl_shopfloors "
759
                       " WHERE id = %s ", (id_,))
760
        if cursor.fetchone() is None:
761
            cursor.close()
762
            cnx.disconnect()
763
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
764
                                   description='API.SHOPFLOOR_NOT_FOUND')
765
766
        cursor.execute(" SELECT name "
767
                       " FROM tbl_meters "
768
                       " WHERE id = %s ", (meter_id,))
769
        if cursor.fetchone() is None:
770
            cursor.close()
771
            cnx.disconnect()
772
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
773
                                   description='API.METER_NOT_FOUND')
774
775
        query = (" SELECT id " 
776
                 " FROM tbl_shopfloors_meters "
777
                 " WHERE shopfloor_id = %s AND meter_id = %s")
778
        cursor.execute(query, (id_, meter_id,))
779
        if cursor.fetchone() is not None:
780
            cursor.close()
781
            cnx.disconnect()
782
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
783
                                   description='API.SHOPFLOOR_METER_RELATION_EXISTS')
784
785
        add_row = (" INSERT INTO tbl_shopfloors_meters (shopfloor_id, meter_id) "
786
                   " VALUES (%s, %s) ")
787
        cursor.execute(add_row, (id_, meter_id,))
788
        new_id = cursor.lastrowid
789
        cnx.commit()
790
        cursor.close()
791
        cnx.disconnect()
792
793
        resp.status = falcon.HTTP_201
794
        resp.location = '/shopfloors/' + str(id_) + '/meters/' + str(meter_id)
795
796
797 View Code Duplication
class ShopfloorMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
798
    @staticmethod
799
    def __init__():
800
        """Initializes ShopfloorMeterItem"""
801
        pass
802
803
    @staticmethod
804
    def on_options(req, resp, id_, mid):
805
        resp.status = falcon.HTTP_200
806
807
    @staticmethod
808
    @user_logger
809
    def on_delete(req, resp, id_, mid):
810
        access_control(req)
811
        if not id_.isdigit() or int(id_) <= 0:
812
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
813
                                   description='API.INVALID_SHOPFLOOR_ID')
814
815
        if not mid.isdigit() or int(mid) <= 0:
816
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
817
                                   description='API.INVALID_METER_ID')
818
819
        cnx = mysql.connector.connect(**config.myems_system_db)
820
        cursor = cnx.cursor()
821
822
        cursor.execute(" SELECT name "
823
                       " FROM tbl_shopfloors "
824
                       " WHERE id = %s ", (id_,))
825
        if cursor.fetchone() is None:
826
            cursor.close()
827
            cnx.disconnect()
828
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
829
                                   description='API.SHOPFLOOR_NOT_FOUND')
830
831
        cursor.execute(" SELECT name "
832
                       " FROM tbl_meters "
833
                       " WHERE id = %s ", (mid,))
834
        if cursor.fetchone() is None:
835
            cursor.close()
836
            cnx.disconnect()
837
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
838
                                   description='API.METER_NOT_FOUND')
839
840
        cursor.execute(" SELECT id "
841
                       " FROM tbl_shopfloors_meters "
842
                       " WHERE shopfloor_id = %s AND meter_id = %s ", (id_, mid))
843
        if cursor.fetchone() is None:
844
            cursor.close()
845
            cnx.disconnect()
846
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
847
                                   description='API.SHOPFLOOR_METER_RELATION_NOT_FOUND')
848
849
        cursor.execute(" DELETE FROM tbl_shopfloors_meters WHERE shopfloor_id = %s AND meter_id = %s ", (id_, mid))
850
        cnx.commit()
851
852
        cursor.close()
853
        cnx.disconnect()
854
855
        resp.status = falcon.HTTP_204
856
857
858 View Code Duplication
class ShopfloorOfflineMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
859
    @staticmethod
860
    def __init__():
861
        """Initializes ShopfloorOfflineMeterCollection"""
862
        pass
863
864
    @staticmethod
865
    def on_options(req, resp, id_):
866
        resp.status = falcon.HTTP_200
867
868
    @staticmethod
869
    def on_get(req, resp, id_):
870
        if not id_.isdigit() or int(id_) <= 0:
871
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
872
                                   description='API.INVALID_SHOPFLOOR_ID')
873
874
        cnx = mysql.connector.connect(**config.myems_system_db)
875
        cursor = cnx.cursor(dictionary=True)
876
877
        cursor.execute(" SELECT name "
878
                       " FROM tbl_shopfloors "
879
                       " WHERE id = %s ", (id_,))
880
        if cursor.fetchone() is None:
881
            cursor.close()
882
            cnx.disconnect()
883
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
884
                                   description='API.SHOPFLOOR_NOT_FOUND')
885
886
        query = (" SELECT id, name, uuid "
887
                 " FROM tbl_energy_categories ")
888
        cursor.execute(query)
889
        rows_energy_categories = cursor.fetchall()
890
891
        energy_category_dict = dict()
892
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
893
            for row in rows_energy_categories:
894
                energy_category_dict[row['id']] = {"id": row['id'],
895
                                                   "name": row['name'],
896
                                                   "uuid": row['uuid']}
897
898
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
899
                 " FROM tbl_shopfloors s, tbl_shopfloors_offline_meters sm, tbl_offline_meters m "
900
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
901
                 " ORDER BY m.id ")
902
        cursor.execute(query, (id_,))
903
        rows = cursor.fetchall()
904
905
        result = list()
906
        if rows is not None and len(rows) > 0:
907
            for row in rows:
908
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
909
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
910
                               "energy_category": energy_category}
911
                result.append(meta_result)
912
913
        resp.text = json.dumps(result)
914
915
    @staticmethod
916
    @user_logger
917
    def on_post(req, resp, id_):
918
        """Handles POST requests"""
919
        access_control(req)
920
        try:
921
            raw_json = req.stream.read().decode('utf-8')
922
        except Exception as ex:
923
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
924
925
        if not id_.isdigit() or int(id_) <= 0:
926
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
927
                                   description='API.INVALID_SHOPFLOOR_ID')
928
929
        new_values = json.loads(raw_json)
930
931
        if 'offline_meter_id' not in new_values['data'].keys() or \
932
                not isinstance(new_values['data']['offline_meter_id'], int) or \
933
                new_values['data']['offline_meter_id'] <= 0:
934
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
935
                                   description='API.INVALID_OFFLINE_METER_ID')
936
        offline_meter_id = new_values['data']['offline_meter_id']
937
938
        cnx = mysql.connector.connect(**config.myems_system_db)
939
        cursor = cnx.cursor()
940
941
        cursor.execute(" SELECT name "
942
                       " from tbl_shopfloors "
943
                       " WHERE id = %s ", (id_,))
944
        if cursor.fetchone() is None:
945
            cursor.close()
946
            cnx.disconnect()
947
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
948
                                   description='API.SHOPFLOOR_NOT_FOUND')
949
950
        cursor.execute(" SELECT name "
951
                       " FROM tbl_offline_meters "
952
                       " WHERE id = %s ", (offline_meter_id,))
953
        if cursor.fetchone() is None:
954
            cursor.close()
955
            cnx.disconnect()
956
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
957
                                   description='API.OFFLINE_METER_NOT_FOUND')
958
959
        query = (" SELECT id " 
960
                 " FROM tbl_shopfloors_offline_meters "
961
                 " WHERE shopfloor_id = %s AND offline_meter_id = %s")
962
        cursor.execute(query, (id_, offline_meter_id,))
963
        if cursor.fetchone() is not None:
964
            cursor.close()
965
            cnx.disconnect()
966
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
967
                                   description='API.SHOPFLOOR_OFFLINE_METER_RELATION_EXISTS')
968
969
        add_row = (" INSERT INTO tbl_shopfloors_offline_meters (shopfloor_id, offline_meter_id) "
970
                   " VALUES (%s, %s) ")
971
        cursor.execute(add_row, (id_, offline_meter_id,))
972
        new_id = cursor.lastrowid
973
        cnx.commit()
974
        cursor.close()
975
        cnx.disconnect()
976
977
        resp.status = falcon.HTTP_201
978
        resp.location = '/shopfloors/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
979
980
981 View Code Duplication
class ShopfloorOfflineMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
982
    @staticmethod
983
    def __init__():
984
        """Initializes ShopfloorOfflineMeterItem"""
985
        pass
986
987
    @staticmethod
988
    def on_options(req, resp, id_, mid):
989
        resp.status = falcon.HTTP_200
990
991
    @staticmethod
992
    @user_logger
993
    def on_delete(req, resp, id_, mid):
994
        access_control(req)
995
        if not id_.isdigit() or int(id_) <= 0:
996
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
997
                                   description='API.INVALID_SHOPFLOOR_ID')
998
999
        if not mid.isdigit() or int(mid) <= 0:
1000
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1001
                                   description='API.INVALID_OFFLINE_METER_ID')
1002
1003
        cnx = mysql.connector.connect(**config.myems_system_db)
1004
        cursor = cnx.cursor()
1005
1006
        cursor.execute(" SELECT name "
1007
                       " FROM tbl_shopfloors "
1008
                       " WHERE id = %s ", (id_,))
1009
        if cursor.fetchone() is None:
1010
            cursor.close()
1011
            cnx.disconnect()
1012
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1013
                                   description='API.SHOPFLOOR_NOT_FOUND')
1014
1015
        cursor.execute(" SELECT name "
1016
                       " FROM tbl_offline_meters "
1017
                       " WHERE id = %s ", (mid,))
1018
        if cursor.fetchone() is None:
1019
            cursor.close()
1020
            cnx.disconnect()
1021
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1022
                                   description='API.OFFLINE_METER_NOT_FOUND')
1023
1024
        cursor.execute(" SELECT id "
1025
                       " FROM tbl_shopfloors_offline_meters "
1026
                       " WHERE shopfloor_id = %s AND offline_meter_id = %s ", (id_, mid))
1027
        if cursor.fetchone() is None:
1028
            cursor.close()
1029
            cnx.disconnect()
1030
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1031
                                   description='API.SHOPFLOOR_OFFLINE_METER_RELATION_NOT_FOUND')
1032
1033
        cursor.execute(" DELETE FROM tbl_shopfloors_offline_meters "
1034
                       " WHERE shopfloor_id = %s AND offline_meter_id = %s ", (id_, mid))
1035
        cnx.commit()
1036
1037
        cursor.close()
1038
        cnx.disconnect()
1039
1040
        resp.status = falcon.HTTP_204
1041
1042
1043 View Code Duplication
class ShopfloorPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1044
    @staticmethod
1045
    def __init__():
1046
        """Initializes ShopfloorPointCollection"""
1047
        pass
1048
1049
    @staticmethod
1050
    def on_options(req, resp, id_):
1051
        resp.status = falcon.HTTP_200
1052
1053
    @staticmethod
1054
    def on_get(req, resp, id_):
1055
        if not id_.isdigit() or int(id_) <= 0:
1056
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1057
                                   description='API.INVALID_SHOPFLOOR_ID')
1058
1059
        cnx = mysql.connector.connect(**config.myems_system_db)
1060
        cursor = cnx.cursor(dictionary=True)
1061
1062
        cursor.execute(" SELECT name "
1063
                       " FROM tbl_shopfloors "
1064
                       " WHERE id = %s ", (id_,))
1065
        if cursor.fetchone() is None:
1066
            cursor.close()
1067
            cnx.disconnect()
1068
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1069
                                   description='API.SHOPFLOOR_NOT_FOUND')
1070
1071
        query = (" SELECT id, name, uuid "
1072
                 " FROM tbl_data_sources ")
1073
        cursor.execute(query)
1074
        rows_data_sources = cursor.fetchall()
1075
1076
        data_source_dict = dict()
1077
        if rows_data_sources is not None and len(rows_data_sources) > 0:
1078
            for row in rows_data_sources:
1079
                data_source_dict[row['id']] = {"id": row['id'],
1080
                                               "name": row['name'],
1081
                                               "uuid": row['uuid']}
1082
1083
        query = (" SELECT p.id, p.name, p.data_source_id "
1084
                 " FROM tbl_shopfloors s, tbl_shopfloors_points sp, tbl_points p "
1085
                 " WHERE sp.shopfloor_id = s.id AND p.id = sp.point_id AND s.id = %s "
1086
                 " ORDER BY p.id ")
1087
        cursor.execute(query, (id_,))
1088
        rows = cursor.fetchall()
1089
1090
        result = list()
1091
        if rows is not None and len(rows) > 0:
1092
            for row in rows:
1093
                data_source = data_source_dict.get(row['data_source_id'], None)
1094
                meta_result = {"id": row['id'], "name": row['name'], "data_source": data_source}
1095
                result.append(meta_result)
1096
1097
        resp.text = json.dumps(result)
1098
1099
    @staticmethod
1100
    @user_logger
1101
    def on_post(req, resp, id_):
1102
        """Handles POST requests"""
1103
        access_control(req)
1104
        try:
1105
            raw_json = req.stream.read().decode('utf-8')
1106
        except Exception as ex:
1107
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1108
1109
        if not id_.isdigit() or int(id_) <= 0:
1110
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1111
                                   description='API.INVALID_SHOPFLOOR_ID')
1112
1113
        new_values = json.loads(raw_json)
1114
1115
        if 'point_id' not in new_values['data'].keys() or \
1116
                not isinstance(new_values['data']['point_id'], int) or \
1117
                new_values['data']['point_id'] <= 0:
1118
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1119
                                   description='API.INVALID_POINT_ID')
1120
        point_id = new_values['data']['point_id']
1121
1122
        cnx = mysql.connector.connect(**config.myems_system_db)
1123
        cursor = cnx.cursor()
1124
1125
        cursor.execute(" SELECT name "
1126
                       " from tbl_shopfloors "
1127
                       " WHERE id = %s ", (id_,))
1128
        if cursor.fetchone() is None:
1129
            cursor.close()
1130
            cnx.disconnect()
1131
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1132
                                   description='API.SHOPFLOOR_NOT_FOUND')
1133
1134
        cursor.execute(" SELECT name "
1135
                       " FROM tbl_points "
1136
                       " WHERE id = %s ", (point_id,))
1137
        if cursor.fetchone() is None:
1138
            cursor.close()
1139
            cnx.disconnect()
1140
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1141
                                   description='API.POINT_NOT_FOUND')
1142
1143
        query = (" SELECT id " 
1144
                 " FROM tbl_shopfloors_points "
1145
                 " WHERE shopfloor_id = %s AND point_id = %s")
1146
        cursor.execute(query, (id_, point_id,))
1147
        if cursor.fetchone() is not None:
1148
            cursor.close()
1149
            cnx.disconnect()
1150
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1151
                                   description='API.SHOPFLOOR_POINT_RELATION_EXISTS')
1152
1153
        add_row = (" INSERT INTO tbl_shopfloors_points (shopfloor_id, point_id) "
1154
                   " VALUES (%s, %s) ")
1155
        cursor.execute(add_row, (id_, point_id,))
1156
        new_id = cursor.lastrowid
1157
        cnx.commit()
1158
        cursor.close()
1159
        cnx.disconnect()
1160
1161
        resp.status = falcon.HTTP_201
1162
        resp.location = '/shopfloors/' + str(id_) + '/points/' + str(point_id)
1163
1164
1165 View Code Duplication
class ShopfloorPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1166
    @staticmethod
1167
    def __init__():
1168
        """Initializes ShopfloorPointItem"""
1169
        pass
1170
1171
    @staticmethod
1172
    def on_options(req, resp, id_, pid):
1173
        resp.status = falcon.HTTP_200
1174
1175
    @staticmethod
1176
    @user_logger
1177
    def on_delete(req, resp, id_, pid):
1178
        access_control(req)
1179
        if not id_.isdigit() or int(id_) <= 0:
1180
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1181
                                   description='API.INVALID_SHOPFLOOR_ID')
1182
1183
        if not pid.isdigit() or int(pid) <= 0:
1184
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1185
                                   description='API.INVALID_POINT_ID')
1186
1187
        cnx = mysql.connector.connect(**config.myems_system_db)
1188
        cursor = cnx.cursor()
1189
1190
        cursor.execute(" SELECT name "
1191
                       " FROM tbl_shopfloors "
1192
                       " WHERE id = %s ", (id_,))
1193
        if cursor.fetchone() is None:
1194
            cursor.close()
1195
            cnx.disconnect()
1196
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1197
                                   description='API.SHOPFLOOR_NOT_FOUND')
1198
1199
        cursor.execute(" SELECT name "
1200
                       " FROM tbl_points "
1201
                       " WHERE id = %s ", (pid,))
1202
        if cursor.fetchone() is None:
1203
            cursor.close()
1204
            cnx.disconnect()
1205
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1206
                                   description='API.POINT_NOT_FOUND')
1207
1208
        cursor.execute(" SELECT id "
1209
                       " FROM tbl_shopfloors_points "
1210
                       " WHERE shopfloor_id = %s AND point_id = %s ", (id_, pid))
1211
        if cursor.fetchone() is None:
1212
            cursor.close()
1213
            cnx.disconnect()
1214
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1215
                                   description='API.SHOPFLOOR_POINT_RELATION_NOT_FOUND')
1216
1217
        cursor.execute(" DELETE FROM tbl_shopfloors_points "
1218
                       " WHERE shopfloor_id = %s AND point_id = %s ", (id_, pid))
1219
        cnx.commit()
1220
1221
        cursor.close()
1222
        cnx.disconnect()
1223
1224
        resp.status = falcon.HTTP_204
1225
1226
1227 View Code Duplication
class ShopfloorSensorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1228
    @staticmethod
1229
    def __init__():
1230
        """Initializes ShopfloorSensorCollection"""
1231
        pass
1232
1233
    @staticmethod
1234
    def on_options(req, resp, id_):
1235
        resp.status = falcon.HTTP_200
1236
1237
    @staticmethod
1238
    def on_get(req, resp, id_):
1239
        if not id_.isdigit() or int(id_) <= 0:
1240
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1241
                                   description='API.INVALID_SHOPFLOOR_ID')
1242
1243
        cnx = mysql.connector.connect(**config.myems_system_db)
1244
        cursor = cnx.cursor()
1245
1246
        cursor.execute(" SELECT name "
1247
                       " FROM tbl_shopfloors "
1248
                       " WHERE id = %s ", (id_,))
1249
        if cursor.fetchone() is None:
1250
            cursor.close()
1251
            cnx.disconnect()
1252
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1253
                                   description='API.SHOPFLOOR_NOT_FOUND')
1254
1255
        query = (" SELECT se.id, se.name, se.uuid "
1256
                 " FROM tbl_shopfloors sp, tbl_shopfloors_sensors ss, tbl_sensors se "
1257
                 " WHERE ss.shopfloor_id = sp.id AND se.id = ss.sensor_id AND sp.id = %s "
1258
                 " ORDER BY se.id ")
1259
        cursor.execute(query, (id_,))
1260
        rows = cursor.fetchall()
1261
1262
        result = list()
1263
        if rows is not None and len(rows) > 0:
1264
            for row in rows:
1265
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1266
                result.append(meta_result)
1267
1268
        resp.text = json.dumps(result)
1269
1270
    @staticmethod
1271
    @user_logger
1272
    def on_post(req, resp, id_):
1273
        """Handles POST requests"""
1274
        access_control(req)
1275
        try:
1276
            raw_json = req.stream.read().decode('utf-8')
1277
        except Exception as ex:
1278
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1279
1280
        if not id_.isdigit() or int(id_) <= 0:
1281
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1282
                                   description='API.INVALID_SHOPFLOOR_ID')
1283
1284
        new_values = json.loads(raw_json)
1285
1286
        if 'sensor_id' not in new_values['data'].keys() or \
1287
                not isinstance(new_values['data']['sensor_id'], int) or \
1288
                new_values['data']['sensor_id'] <= 0:
1289
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1290
                                   description='API.INVALID_SENSOR_ID')
1291
        sensor_id = new_values['data']['sensor_id']
1292
1293
        cnx = mysql.connector.connect(**config.myems_system_db)
1294
        cursor = cnx.cursor()
1295
1296
        cursor.execute(" SELECT name "
1297
                       " from tbl_shopfloors "
1298
                       " WHERE id = %s ", (id_,))
1299
        if cursor.fetchone() is None:
1300
            cursor.close()
1301
            cnx.disconnect()
1302
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1303
                                   description='API.SHOPFLOOR_NOT_FOUND')
1304
1305
        cursor.execute(" SELECT name "
1306
                       " FROM tbl_sensors "
1307
                       " WHERE id = %s ", (sensor_id,))
1308
        if cursor.fetchone() is None:
1309
            cursor.close()
1310
            cnx.disconnect()
1311
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1312
                                   description='API.SENSOR_NOT_FOUND')
1313
1314
        query = (" SELECT id " 
1315
                 " FROM tbl_shopfloors_sensors "
1316
                 " WHERE shopfloor_id = %s AND sensor_id = %s")
1317
        cursor.execute(query, (id_, sensor_id,))
1318
        if cursor.fetchone() is not None:
1319
            cursor.close()
1320
            cnx.disconnect()
1321
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1322
                                   description='API.SHOPFLOOR_SENSOR_RELATION_EXISTS')
1323
1324
        add_row = (" INSERT INTO tbl_shopfloors_sensors (shopfloor_id, sensor_id) "
1325
                   " VALUES (%s, %s) ")
1326
        cursor.execute(add_row, (id_, sensor_id,))
1327
        new_id = cursor.lastrowid
1328
        cnx.commit()
1329
        cursor.close()
1330
        cnx.disconnect()
1331
1332
        resp.status = falcon.HTTP_201
1333
        resp.location = '/shopfloors/' + str(id_) + '/sensors/' + str(sensor_id)
1334
1335
1336 View Code Duplication
class ShopfloorSensorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1337
    @staticmethod
1338
    def __init__():
1339
        """Initializes ShopfloorSensorItem"""
1340
        pass
1341
1342
    @staticmethod
1343
    def on_options(req, resp, id_, sid):
1344
        resp.status = falcon.HTTP_200
1345
1346
    @staticmethod
1347
    @user_logger
1348
    def on_delete(req, resp, id_, sid):
1349
        access_control(req)
1350
        if not id_.isdigit() or int(id_) <= 0:
1351
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1352
                                   description='API.INVALID_SHOPFLOOR_ID')
1353
1354
        if not sid.isdigit() or int(sid) <= 0:
1355
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1356
                                   description='API.INVALID_SENSOR_ID')
1357
1358
        cnx = mysql.connector.connect(**config.myems_system_db)
1359
        cursor = cnx.cursor()
1360
1361
        cursor.execute(" SELECT name "
1362
                       " FROM tbl_shopfloors "
1363
                       " WHERE id = %s ", (id_,))
1364
        if cursor.fetchone() is None:
1365
            cursor.close()
1366
            cnx.disconnect()
1367
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1368
                                   description='API.SHOPFLOOR_NOT_FOUND')
1369
1370
        cursor.execute(" SELECT name "
1371
                       " FROM tbl_sensors "
1372
                       " WHERE id = %s ", (sid,))
1373
        if cursor.fetchone() is None:
1374
            cursor.close()
1375
            cnx.disconnect()
1376
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1377
                                   description='API.SENSOR_NOT_FOUND')
1378
1379
        cursor.execute(" SELECT id "
1380
                       " FROM tbl_shopfloors_sensors "
1381
                       " WHERE shopfloor_id = %s AND sensor_id = %s ", (id_, sid))
1382
        if cursor.fetchone() is None:
1383
            cursor.close()
1384
            cnx.disconnect()
1385
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1386
                                   description='API.SHOPFLOOR_SENSOR_RELATION_NOT_FOUND')
1387
1388
        cursor.execute(" DELETE FROM tbl_shopfloors_sensors WHERE shopfloor_id = %s AND sensor_id = %s ", (id_, sid))
1389
        cnx.commit()
1390
1391
        cursor.close()
1392
        cnx.disconnect()
1393
1394
        resp.status = falcon.HTTP_204
1395
1396
1397 View Code Duplication
class ShopfloorVirtualMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1398
    @staticmethod
1399
    def __init__():
1400
        """Initializes ShopfloorVirtualMeterCollection"""
1401
        pass
1402
1403
    @staticmethod
1404
    def on_options(req, resp, id_):
1405
        resp.status = falcon.HTTP_200
1406
1407
    @staticmethod
1408
    def on_get(req, resp, id_):
1409
        if not id_.isdigit() or int(id_) <= 0:
1410
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1411
                                   description='API.INVALID_SHOPFLOOR_ID')
1412
1413
        cnx = mysql.connector.connect(**config.myems_system_db)
1414
        cursor = cnx.cursor(dictionary=True)
1415
1416
        cursor.execute(" SELECT name "
1417
                       " FROM tbl_shopfloors "
1418
                       " WHERE id = %s ", (id_,))
1419
        if cursor.fetchone() is None:
1420
            cursor.close()
1421
            cnx.disconnect()
1422
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1423
                                   description='API.SHOPFLOOR_NOT_FOUND')
1424
1425
        query = (" SELECT id, name, uuid "
1426
                 " FROM tbl_energy_categories ")
1427
        cursor.execute(query)
1428
        rows_energy_categories = cursor.fetchall()
1429
1430
        energy_category_dict = dict()
1431
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1432
            for row in rows_energy_categories:
1433
                energy_category_dict[row['id']] = {"id": row['id'],
1434
                                                   "name": row['name'],
1435
                                                   "uuid": row['uuid']}
1436
1437
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1438
                 " FROM tbl_shopfloors s, tbl_shopfloors_virtual_meters sm, tbl_virtual_meters m "
1439
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
1440
                 " ORDER BY m.id ")
1441
        cursor.execute(query, (id_,))
1442
        rows = cursor.fetchall()
1443
1444
        result = list()
1445
        if rows is not None and len(rows) > 0:
1446
            for row in rows:
1447
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1448
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1449
                               "energy_category": energy_category}
1450
                result.append(meta_result)
1451
1452
        resp.text = json.dumps(result)
1453
1454
    @staticmethod
1455
    @user_logger
1456
    def on_post(req, resp, id_):
1457
        """Handles POST requests"""
1458
        access_control(req)
1459
        try:
1460
            raw_json = req.stream.read().decode('utf-8')
1461
        except Exception as ex:
1462
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1463
1464
        if not id_.isdigit() or int(id_) <= 0:
1465
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1466
                                   description='API.INVALID_SHOPFLOOR_ID')
1467
1468
        new_values = json.loads(raw_json)
1469
1470
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1471
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1472
                new_values['data']['virtual_meter_id'] <= 0:
1473
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1474
                                   description='API.INVALID_VIRTUAL_METER_ID')
1475
        virtual_meter_id = new_values['data']['virtual_meter_id']
1476
1477
        cnx = mysql.connector.connect(**config.myems_system_db)
1478
        cursor = cnx.cursor()
1479
1480
        cursor.execute(" SELECT name "
1481
                       " from tbl_shopfloors "
1482
                       " WHERE id = %s ", (id_,))
1483
        if cursor.fetchone() is None:
1484
            cursor.close()
1485
            cnx.disconnect()
1486
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1487
                                   description='API.SHOPFLOOR_NOT_FOUND')
1488
1489
        cursor.execute(" SELECT name "
1490
                       " FROM tbl_virtual_meters "
1491
                       " WHERE id = %s ", (virtual_meter_id,))
1492
        if cursor.fetchone() is None:
1493
            cursor.close()
1494
            cnx.disconnect()
1495
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1496
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1497
1498
        query = (" SELECT id " 
1499
                 " FROM tbl_shopfloors_virtual_meters "
1500
                 " WHERE shopfloor_id = %s AND virtual_meter_id = %s")
1501
        cursor.execute(query, (id_, virtual_meter_id,))
1502
        if cursor.fetchone() is not None:
1503
            cursor.close()
1504
            cnx.disconnect()
1505
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1506
                                   description='API.SHOPFLOOR_VIRTUAL_METER_RELATION_EXISTS')
1507
1508
        add_row = (" INSERT INTO tbl_shopfloors_virtual_meters (shopfloor_id, virtual_meter_id) "
1509
                   " VALUES (%s, %s) ")
1510
        cursor.execute(add_row, (id_, virtual_meter_id,))
1511
        new_id = cursor.lastrowid
1512
        cnx.commit()
1513
        cursor.close()
1514
        cnx.disconnect()
1515
1516
        resp.status = falcon.HTTP_201
1517
        resp.location = '/shopfloors/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1518
1519
1520 View Code Duplication
class ShopfloorVirtualMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1521
    @staticmethod
1522
    def __init__():
1523
        """Initializes ShopfloorVirtualMeterItem"""
1524
        pass
1525
1526
    @staticmethod
1527
    def on_options(req, resp, id_, mid):
1528
        resp.status = falcon.HTTP_200
1529
1530
    @staticmethod
1531
    @user_logger
1532
    def on_delete(req, resp, id_, mid):
1533
        access_control(req)
1534
        if not id_.isdigit() or int(id_) <= 0:
1535
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1536
                                   description='API.INVALID_SHOPFLOOR_ID')
1537
1538
        if not mid.isdigit() or int(mid) <= 0:
1539
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1540
                                   description='API.INVALID_VIRTUAL_METER_ID')
1541
1542
        cnx = mysql.connector.connect(**config.myems_system_db)
1543
        cursor = cnx.cursor()
1544
1545
        cursor.execute(" SELECT name "
1546
                       " FROM tbl_shopfloors "
1547
                       " WHERE id = %s ", (id_,))
1548
        if cursor.fetchone() is None:
1549
            cursor.close()
1550
            cnx.disconnect()
1551
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1552
                                   description='API.SHOPFLOOR_NOT_FOUND')
1553
1554
        cursor.execute(" SELECT name "
1555
                       " FROM tbl_virtual_meters "
1556
                       " WHERE id = %s ", (mid,))
1557
        if cursor.fetchone() is None:
1558
            cursor.close()
1559
            cnx.disconnect()
1560
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1561
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1562
1563
        cursor.execute(" SELECT id "
1564
                       " FROM tbl_shopfloors_virtual_meters "
1565
                       " WHERE shopfloor_id = %s AND virtual_meter_id = %s ", (id_, mid))
1566
        if cursor.fetchone() is None:
1567
            cursor.close()
1568
            cnx.disconnect()
1569
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1570
                                   description='API.SHOPFLOOR_VIRTUAL_METER_RELATION_NOT_FOUND')
1571
1572
        cursor.execute(" DELETE FROM tbl_shopfloors_virtual_meters "
1573
                       " WHERE shopfloor_id = %s AND virtual_meter_id = %s ", (id_, mid))
1574
        cnx.commit()
1575
1576
        cursor.close()
1577
        cnx.disconnect()
1578
1579
        resp.status = falcon.HTTP_204
1580
1581
1582