core.shopfloor   F
last analyzed

Complexity

Total Complexity 563

Size/Duplication

Total Lines 2952
Duplicated Lines 52.47 %

Importance

Changes 0
Metric Value
wmc 563
eloc 2179
dl 1549
loc 2952
rs 0.8
c 0
b 0
f 0

74 Methods

Rating   Name   Duplication   Size   Complexity  
A ShopfloorItem.__init__() 0 4 1
A ShopfloorItem.on_options() 0 3 1
A ShopfloorCollection.__init__() 0 4 1
A ShopfloorCollection.on_options() 0 3 1
D ShopfloorPointCollection.on_get() 50 50 13
D ShopfloorOfflineMeterCollection.on_get() 51 51 13
F ShopfloorCollection.on_post() 11 112 23
F ShopfloorItem.on_put() 11 124 26
C ShopfloorCommandCollection.on_get() 38 38 10
A ShopfloorWorkingCalendarCollection.__init__() 4 4 1
C ShopfloorVirtualMeterCollection.on_post() 65 65 10
C ShopfloorMeterCollection.on_post() 65 65 10
C ShopfloorSensorCollection.on_get() 38 38 10
C ShopfloorEquipmentCollection.on_get() 38 38 10
A ShopfloorPointCollection.on_options() 3 3 1
D ShopfloorMeterCollection.on_get() 51 51 13
C ShopfloorOfflineMeterCollection.on_post() 65 65 10
A ShopfloorCommandCollection.__init__() 4 4 1
A ShopfloorImport.on_options() 0 3 1
A ShopfloorMeterCollection.on_options() 3 3 1
F ShopfloorImport.on_post() 11 304 63
A ShopfloorEquipmentCollection.on_options() 3 3 1
A ShopfloorVirtualMeterCollection.__init__() 4 4 1
C ShopfloorWorkingCalendarCollection.on_post() 65 65 10
A ShopfloorOfflineMeterCollection.__init__() 4 4 1
A ShopfloorVirtualMeterCollection.on_options() 3 3 1
C ShopfloorCommandCollection.on_post() 65 65 10
A ShopfloorPointCollection.__init__() 4 4 1
A ShopfloorClone.__init__() 0 4 1
D ShopfloorCollection.on_get() 12 60 13
A ShopfloorEquipmentCollection.__init__() 4 4 1
A ShopfloorImport.__init__() 0 4 1
A ShopfloorOfflineMeterCollection.on_options() 3 3 1
A ShopfloorSensorCollection.on_options() 3 3 1
C ShopfloorSensorCollection.on_post() 65 65 10
A ShopfloorCommandCollection.on_options() 3 3 1
A ShopfloorExport.__init__() 0 4 1
A ShopfloorSensorCollection.__init__() 4 4 1
A ShopfloorMeterCollection.__init__() 4 4 1
C ShopfloorWorkingCalendarCollection.on_get() 38 38 10
F ShopfloorExport.on_get() 0 235 50
B ShopfloorItem.on_delete() 64 64 6
A ShopfloorWorkingCalendarCollection.on_options() 3 3 1
A ShopfloorExport.on_options() 0 3 1
D ShopfloorItem.on_get() 0 63 13
D ShopfloorVirtualMeterCollection.on_get() 51 51 13
C ShopfloorPointCollection.on_post() 65 65 10
F ShopfloorClone.on_post() 0 447 91
C ShopfloorEquipmentCollection.on_post() 65 65 10
A ShopfloorClone.on_options() 0 3 1
A ShopfloorPointItem.__init__() 4 4 1
A ShopfloorMeterItem.__init__() 4 4 1
A ShopfloorEquipmentItem.on_options() 3 3 1
A ShopfloorWorkingCalendarItem.__init__() 4 4 1
A ShopfloorCommandItem.on_options() 3 3 1
A ShopfloorOfflineMeterItem.on_options() 3 3 1
A ShopfloorEquipmentItem.__init__() 4 4 1
A ShopfloorVirtualMeterItem.on_options() 3 3 1
B ShopfloorEquipmentItem.on_delete() 50 50 8
A ShopfloorSensorItem.__init__() 4 4 1
B ShopfloorSensorItem.on_delete() 49 49 8
B ShopfloorVirtualMeterItem.on_delete() 50 50 8
B ShopfloorCommandItem.on_delete() 49 49 8
A ShopfloorCommandItem.__init__() 4 4 1
A ShopfloorVirtualMeterItem.__init__() 4 4 1
A ShopfloorMeterItem.on_options() 3 3 1
B ShopfloorMeterItem.on_delete() 49 49 8
A ShopfloorWorkingCalendarItem.on_options() 3 3 1
B ShopfloorWorkingCalendarItem.on_delete() 50 50 8
A ShopfloorOfflineMeterItem.__init__() 4 4 1
B ShopfloorPointItem.on_delete() 50 50 8
B ShopfloorOfflineMeterItem.on_delete() 50 50 8
A ShopfloorPointItem.on_options() 3 3 1
A ShopfloorSensorItem.on_options() 3 3 1

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