core.shopfloor   F
last analyzed

Complexity

Total Complexity 282

Size/Duplication

Total Lines 1555
Duplicated Lines 66.95 %

Importance

Changes 0
Metric Value
eloc 1148
dl 1041
loc 1555
rs 1.008
c 0
b 0
f 0
wmc 282

51 Methods

Rating   Name   Duplication   Size   Complexity  
A ShopfloorPointItem.__init__() 3 3 1
C ShopfloorPointCollection.on_get() 45 45 10
A ShopfloorMeterItem.__init__() 3 3 1
C ShopfloorOfflineMeterCollection.on_get() 46 46 10
A ShopfloorEquipmentItem.on_options() 3 3 1
F ShopfloorCollection.on_post() 11 107 22
F ShopfloorItem.on_put() 11 119 25
C ShopfloorVirtualMeterCollection.on_post() 62 62 10
C ShopfloorMeterCollection.on_post() 62 62 10
B ShopfloorSensorCollection.on_get() 32 32 7
A ShopfloorItem.__init__() 0 3 1
B ShopfloorEquipmentCollection.on_get() 32 32 7
A ShopfloorPointCollection.on_options() 3 3 1
C ShopfloorMeterCollection.on_get() 46 46 10
C ShopfloorOfflineMeterCollection.on_post() 62 62 10
A ShopfloorOfflineMeterItem.on_options() 3 3 1
A ShopfloorEquipmentItem.__init__() 3 3 1
A ShopfloorCollection.__init__() 0 3 1
A ShopfloorMeterCollection.on_options() 3 3 1
A ShopfloorEquipmentCollection.on_options() 3 3 1
B ShopfloorEquipmentItem.on_delete() 48 48 8
A ShopfloorVirtualMeterItem.on_options() 3 3 1
A ShopfloorVirtualMeterCollection.__init__() 3 3 1
A ShopfloorCollection.on_options() 0 3 1
A ShopfloorOfflineMeterCollection.__init__() 3 3 1
A ShopfloorVirtualMeterCollection.on_options() 3 3 1
A ShopfloorSensorItem.__init__() 3 3 1
A ShopfloorPointCollection.__init__() 3 3 1
B ShopfloorSensorItem.on_delete() 47 47 8
D ShopfloorCollection.on_get() 0 67 13
A ShopfloorEquipmentCollection.__init__() 3 3 1
A ShopfloorSensorCollection.on_options() 3 3 1
A ShopfloorOfflineMeterCollection.on_options() 3 3 1
C ShopfloorSensorCollection.on_post() 62 62 10
B ShopfloorVirtualMeterItem.on_delete() 48 48 8
A ShopfloorSensorCollection.__init__() 3 3 1
A ShopfloorMeterCollection.__init__() 3 3 1
A ShopfloorVirtualMeterItem.__init__() 3 3 1
F ShopfloorItem.on_delete() 0 118 19
A ShopfloorItem.on_options() 0 3 1
A ShopfloorMeterItem.on_options() 3 3 1
D ShopfloorItem.on_get() 0 70 13
B ShopfloorMeterItem.on_delete() 47 47 8
C ShopfloorVirtualMeterCollection.on_get() 46 46 10
A ShopfloorOfflineMeterItem.__init__() 3 3 1
B ShopfloorPointItem.on_delete() 48 48 8
C ShopfloorPointCollection.on_post() 62 62 10
B ShopfloorOfflineMeterItem.on_delete() 48 48 8
A ShopfloorPointItem.on_options() 3 3 1
A ShopfloorSensorItem.on_options() 3 3 1
C ShopfloorEquipmentCollection.on_post() 62 62 10

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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