core.shopfloor   F
last analyzed

Complexity

Total Complexity 563

Size/Duplication

Total Lines 2989
Duplicated Lines 38.11 %

Importance

Changes 0
Metric Value
wmc 563
eloc 2216
dl 1139
loc 2989
rs 0.8
c 0
b 0
f 0

74 Methods

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