Passed
Push — master ( f8b1cd...9ee003 )
by
unknown
10:23 queued 16s
created

DistributionCircuitPointCollection.on_options()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nop 3
1
import uuid
2
import falcon
3
import mysql.connector
4
import simplejson as json
5
from core.useractivity import user_logger, admin_control, access_control, api_key_control
6
import config
7
8
9
class DistributionCircuitCollection:
10
    """
11
    Distribution Circuit Collection Resource
12
13
    This class handles CRUD operations for distribution circuit collection.
14
    It provides endpoints for listing all distribution circuits and creating new ones.
15
    Distribution circuits represent electrical circuits within distribution systems.
16
    """
17
    def __init__(self):
18
        """Initialize DistributionCircuitCollection"""
19
        pass
20
21
    @staticmethod
22
    def on_options(req, resp):
23
        """Handle OPTIONS requests for CORS preflight"""
24
        _ = req
25
        resp.status = falcon.HTTP_200
26
27
    @staticmethod
28
    def on_get(req, resp):
29
        if 'API-KEY' not in req.headers or \
30
                not isinstance(req.headers['API-KEY'], str) or \
31
                len(str.strip(req.headers['API-KEY'])) == 0:
32
            access_control(req)
33
        else:
34
            api_key_control(req)
35
        cnx = mysql.connector.connect(**config.myems_system_db)
36
        cursor = cnx.cursor()
37
38
        query = (" SELECT id, name, uuid "
39
                 " FROM tbl_distribution_systems ")
40
        cursor.execute(query)
41
        rows_distribution_systems = cursor.fetchall()
42
43
        distribution_system_dict = dict()
44
        if rows_distribution_systems is not None and len(rows_distribution_systems) > 0:
45
            for row in rows_distribution_systems:
46
                distribution_system_dict[row[0]] = {"id": row[0],
47
                                                    "name": row[1],
48
                                                    "uuid": row[2]}
49
        query = (" SELECT id, name, uuid, distribution_system_id, "
50
                 "        distribution_room, switchgear, peak_load, peak_current, customers, meters "
51
                 " FROM tbl_distribution_circuits "
52
                 " ORDER BY id ")
53
        cursor.execute(query)
54
        rows_distribution_circuits = cursor.fetchall()
55
56
        result = list()
57
        if rows_distribution_circuits is not None and len(rows_distribution_circuits) > 0:
58
            for row in rows_distribution_circuits:
59
                meta_result = {"id": row[0],
60
                               "name": row[1],
61
                               "uuid": row[2],
62
                               "distribution_system": distribution_system_dict.get(row[3]),
63
                               "distribution_room": row[4],
64
                               "switchgear": row[5],
65
                               "peak_load": row[6],
66
                               "peak_current": row[7],
67
                               "customers": row[8],
68
                               "meters": row[9]}
69
                result.append(meta_result)
70
71
        cursor.close()
72
        cnx.close()
73
        resp.text = json.dumps(result)
74
75
    @staticmethod
76
    @user_logger
77
    def on_post(req, resp):
78
        """Handles POST requests"""
79
        admin_control(req)
80
        try:
81
            raw_json = req.stream.read().decode('utf-8')
82
        except UnicodeDecodeError as ex:
83
            print("Failed to decode request")
84
            raise falcon.HTTPError(status=falcon.HTTP_400,
85
                                   title='API.BAD_REQUEST',
86
                                   description='API.INVALID_ENCODING')
87
        except Exception as ex:
88
            print("Unexpected error reading request stream")
89
            raise falcon.HTTPError(status=falcon.HTTP_400,
90
                                   title='API.BAD_REQUEST',
91
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
92
93
        new_values = json.loads(raw_json)
94
95
        if 'name' not in new_values['data'].keys() or \
96
                not isinstance(new_values['data']['name'], str) or \
97
                len(str.strip(new_values['data']['name'])) == 0:
98
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
99
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_NAME')
100
        name = str.strip(new_values['data']['name'])
101
102
        if 'distribution_system_id' not in new_values['data'].keys() or \
103
                not isinstance(new_values['data']['distribution_system_id'], int) or \
104
                new_values['data']['distribution_system_id'] <= 0:
105
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
106
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
107
        distribution_system_id = new_values['data']['distribution_system_id']
108
109
        if 'distribution_room' not in new_values['data'].keys() or \
110
                not isinstance(new_values['data']['distribution_room'], str) or \
111
                len(str.strip(new_values['data']['distribution_room'])) == 0:
112
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
113
                                   description='API.INVALID_DISTRIBUTION_ROOM')
114
        distribution_room = str.strip(new_values['data']['distribution_room'])
115
116
        if 'switchgear' not in new_values['data'].keys() or \
117
                not isinstance(new_values['data']['switchgear'], str) or \
118
                len(str.strip(new_values['data']['switchgear'])) == 0:
119
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
120
                                   description='API.INVALID_SWITCHGEAR')
121
        switchgear = str.strip(new_values['data']['switchgear'])
122
123
        if 'peak_load' not in new_values['data'].keys() or \
124
                not (isinstance(new_values['data']['peak_load'], float) or
125
                     isinstance(new_values['data']['peak_load'], int)):
126
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
127
                                   description='API.INVALID_PEAK_LOAD')
128
        peak_load = float(new_values['data']['peak_load'])
129
130
        if 'peak_current' not in new_values['data'].keys() or \
131
                not (isinstance(new_values['data']['peak_current'], float) or
132
                     isinstance(new_values['data']['peak_current'], int)):
133
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
134
                                   description='API.INVALID_PEAK_CURRENT')
135
        peak_current = float(new_values['data']['peak_current'])
136
137
        if 'customers' in new_values['data'].keys() and \
138
                new_values['data']['customers'] is not None and \
139
                len(str(new_values['data']['customers'])) > 0:
140
            customers = str.strip(new_values['data']['customers'])
141
        else:
142
            customers = None
143
144
        if 'meters' in new_values['data'].keys() and \
145
                new_values['data']['meters'] is not None and \
146
                len(str(new_values['data']['meters'])) > 0:
147
            meters = str.strip(new_values['data']['meters'])
148
        else:
149
            meters = None
150
151
        cnx = mysql.connector.connect(**config.myems_system_db)
152
        cursor = cnx.cursor()
153
154
        cursor.execute(" SELECT name "
155
                       " FROM tbl_distribution_systems "
156
                       " WHERE id = %s ",
157
                       (distribution_system_id,))
158
        if cursor.fetchone() is None:
159
            cursor.close()
160
            cnx.close()
161
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
162
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
163
164
        cursor.execute(" SELECT name "
165
                       " FROM tbl_distribution_circuits "
166
                       " WHERE distribution_system_id = %s AND name = %s ",
167
                       (distribution_system_id, name,))
168
        if cursor.fetchone() is not None:
169
            cursor.close()
170
            cnx.close()
171
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
172
                                   description='API.DISTRIBUTION_CIRCUIT_NAME_IS_ALREADY_IN_USE')
173
174
        add_values = (" INSERT INTO tbl_distribution_circuits "
175
                      "    (name, uuid, distribution_system_id,"
176
                      "     distribution_room, switchgear, peak_load, peak_current, customers, meters) "
177
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ")
178
        cursor.execute(add_values, (name,
179
                                    str(uuid.uuid4()),
180
                                    distribution_system_id,
181
                                    distribution_room,
182
                                    switchgear,
183
                                    peak_load,
184
                                    peak_current,
185
                                    customers,
186
                                    meters))
187
        new_id = cursor.lastrowid
188
        cnx.commit()
189
        cursor.close()
190
        cnx.close()
191
192
        resp.status = falcon.HTTP_201
193
        resp.location = '/distributioncircuits/' + str(new_id)
194
195
196
class DistributionCircuitItem:
197
    def __init__(self):
198
        pass
199
200
    @staticmethod
201
    def on_options(req, resp, id_):
202
        _ = req
203
        resp.status = falcon.HTTP_200
204
        _ = id_
205
206
    @staticmethod
207
    def on_get(req, resp, id_):
208
        if 'API-KEY' not in req.headers or \
209
                not isinstance(req.headers['API-KEY'], str) or \
210
                len(str.strip(req.headers['API-KEY'])) == 0:
211
            access_control(req)
212
        else:
213
            api_key_control(req)
214
        if not id_.isdigit() or int(id_) <= 0:
215
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
216
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
217
218
        cnx = mysql.connector.connect(**config.myems_system_db)
219
        cursor = cnx.cursor()
220
221
        query = (" SELECT id, name, uuid "
222
                 " FROM tbl_distribution_systems ")
223
        cursor.execute(query)
224
        rows_distribution_systems = cursor.fetchall()
225
226
        distribution_system_dict = dict()
227
        if rows_distribution_systems is not None and len(rows_distribution_systems) > 0:
228
            for row in rows_distribution_systems:
229
                distribution_system_dict[row[0]] = {"id": row[0],
230
                                                    "name": row[1],
231
                                                    "uuid": row[2]}
232
233
        query = (" SELECT id, name, uuid, distribution_system_id, "
234
                 "        distribution_room, switchgear, peak_load, peak_current, customers, meters "
235
                 " FROM tbl_distribution_circuits "
236
                 " WHERE id = %s ")
237
        cursor.execute(query, (id_,))
238
        row = cursor.fetchone()
239
        cursor.close()
240
        cnx.close()
241
242
        if row is None:
243
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
244
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
245
        else:
246
            meta_result = {"id": row[0],
247
                           "name": row[1],
248
                           "uuid": row[2],
249
                           "distribution_system": distribution_system_dict.get(row[3]),
250
                           "distribution_room": row[4],
251
                           "switchgear": row[5],
252
                           "peak_load": row[6],
253
                           "peak_current": row[7],
254
                           "customers": row[8],
255
                           "meters": row[9]}
256
257
        resp.text = json.dumps(meta_result)
258
259
    @staticmethod
260
    @user_logger
261
    def on_delete(req, resp, id_):
262
        admin_control(req)
263
        if not id_.isdigit() or int(id_) <= 0:
264
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
265
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
266
        cnx = mysql.connector.connect(**config.myems_system_db)
267
        cursor = cnx.cursor()
268
269
        cursor.execute(" SELECT name "
270
                       " FROM tbl_distribution_circuits "
271
                       " WHERE id = %s ", (id_,))
272
        if cursor.fetchone() is None:
273
            cursor.close()
274
            cnx.close()
275
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
276
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
277
278
        # Get distribution_system_id before deleting
279
        cursor.execute(" SELECT distribution_system_id "
280
                       " FROM tbl_distribution_circuits "
281
                       " WHERE id = %s ", (id_,))
282
        row = cursor.fetchone()
283
        distribution_system_id = row[0] if row else None
284
285
        # delete relation with points
286
        cursor.execute(" DELETE FROM tbl_distribution_circuits_points "
287
                       " WHERE distribution_circuit_id = %s ", (id_,))
288
        # delete distribution circuit itself
289
        cursor.execute(" DELETE FROM tbl_distribution_circuits "
290
                       " WHERE id = %s ", (id_,))
291
        cnx.commit()
292
293
        cursor.close()
294
        cnx.close()
295
296
        resp.status = falcon.HTTP_204
297
298
    @staticmethod
299
    @user_logger
300
    def on_put(req, resp, id_):
301
        """Handles PUT requests"""
302
        admin_control(req)
303
        try:
304
            raw_json = req.stream.read().decode('utf-8')
305
        except UnicodeDecodeError as ex:
306
            print("Failed to decode request")
307
            raise falcon.HTTPError(status=falcon.HTTP_400,
308
                                   title='API.BAD_REQUEST',
309
                                   description='API.INVALID_ENCODING')
310
        except Exception as ex:
311
            print("Unexpected error reading request stream")
312
            raise falcon.HTTPError(status=falcon.HTTP_400,
313
                                   title='API.BAD_REQUEST',
314
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
315
316
        if not id_.isdigit() or int(id_) <= 0:
317
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
318
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
319
320
        new_values = json.loads(raw_json)
321
322
        if 'name' not in new_values['data'].keys() or \
323
                not isinstance(new_values['data']['name'], str) or \
324
                len(str.strip(new_values['data']['name'])) == 0:
325
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
326
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_NAME')
327
        name = str.strip(new_values['data']['name'])
328
329
        if 'distribution_system_id' not in new_values['data'].keys() or \
330
                not isinstance(new_values['data']['distribution_system_id'], int) or \
331
                new_values['data']['distribution_system_id'] <= 0:
332
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
333
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
334
        distribution_system_id = new_values['data']['distribution_system_id']
335
336
        if 'distribution_room' not in new_values['data'].keys() or \
337
                not isinstance(new_values['data']['distribution_room'], str) or \
338
                len(str.strip(new_values['data']['distribution_room'])) == 0:
339
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
340
                                   description='API.INVALID_DISTRIBUTION_ROOM')
341
        distribution_room = str.strip(new_values['data']['distribution_room'])
342
343
        if 'switchgear' not in new_values['data'].keys() or \
344
                not isinstance(new_values['data']['switchgear'], str) or \
345
                len(str.strip(new_values['data']['switchgear'])) == 0:
346
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
347
                                   description='API.INVALID_SWITCHGEAR')
348
        switchgear = str.strip(new_values['data']['switchgear'])
349
350
        if 'peak_load' not in new_values['data'].keys() or \
351
                not (isinstance(new_values['data']['peak_load'], float) or
352
                     isinstance(new_values['data']['peak_load'], int)):
353
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
354
                                   description='API.INVALID_PEAK_LOAD')
355
        peak_load = float(new_values['data']['peak_load'])
356
357
        if 'peak_current' not in new_values['data'].keys() or \
358
                not (isinstance(new_values['data']['peak_current'], float) or
359
                     isinstance(new_values['data']['peak_current'], int)):
360
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
361
                                   description='API.INVALID_PEAK_CURRENT')
362
        peak_current = float(new_values['data']['peak_current'])
363
364
        if 'customers' in new_values['data'].keys() and \
365
                new_values['data']['customers'] is not None and \
366
                len(str(new_values['data']['customers'])) > 0:
367
            customers = str.strip(new_values['data']['customers'])
368
        else:
369
            customers = None
370
371
        if 'meters' in new_values['data'].keys() and \
372
                new_values['data']['meters'] is not None and \
373
                len(str(new_values['data']['meters'])) > 0:
374
            meters = str.strip(new_values['data']['meters'])
375
        else:
376
            meters = None
377
378
        cnx = mysql.connector.connect(**config.myems_system_db)
379
        cursor = cnx.cursor()
380
381
        cursor.execute(" SELECT name "
382
                       " FROM tbl_distribution_systems "
383
                       " WHERE id = %s ",
384
                       (distribution_system_id,))
385
        if cursor.fetchone() is None:
386
            cursor.close()
387
            cnx.close()
388
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
389
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
390
        cursor.execute(" SELECT name "
391
                       " FROM tbl_distribution_circuits "
392
                       " WHERE id = %s ", (id_,))
393
        if cursor.fetchone() is None:
394
            cursor.close()
395
            cnx.close()
396
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
397
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
398
399
        cursor.execute(" SELECT name "
400
                       " FROM tbl_distribution_circuits "
401
                       " WHERE distribution_system_id = %s AND name = %s AND id != %s ",
402
                       (distribution_system_id, name, id_))
403
        if cursor.fetchone() is not None:
404
            cursor.close()
405
            cnx.close()
406
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
407
                                   description='API.DISTRIBUTION_CIRCUIT_NAME_IS_ALREADY_IN_USE')
408
409
        # Get old distribution_system_id before updating (in case it changes)
410
        cursor.execute(" SELECT distribution_system_id "
411
                       " FROM tbl_distribution_circuits "
412
                       " WHERE id = %s ", (id_,))
413
        row = cursor.fetchone()
414
        old_distribution_system_id = row[0] if row else None
415
416
        update_row = (" UPDATE tbl_distribution_circuits "
417
                      " SET name = %s, distribution_system_id = %s, distribution_room = %s, switchgear = %s, "
418
                      "     peak_load = %s, peak_current = %s, customers = %s, meters = %s "
419
                      " WHERE id = %s ")
420
        cursor.execute(update_row, (name,
421
                                    distribution_system_id,
422
                                    distribution_room,
423
                                    switchgear,
424
                                    peak_load,
425
                                    peak_current,
426
                                    customers,
427
                                    meters,
428
                                    id_))
429
        cnx.commit()
430
431
        cursor.close()
432
        cnx.close()
433
434
        resp.status = falcon.HTTP_200
435
436
437
class DistributionCircuitPointCollection:
438
    def __init__(self):
439
        pass
440
441
    @staticmethod
442
    def on_options(req, resp, id_):
443
        _ = req
444
        resp.status = falcon.HTTP_200
445
        _ = id_
446
447
    @staticmethod
448
    def on_get(req, resp, id_):
449
        if 'API-KEY' not in req.headers or \
450
                not isinstance(req.headers['API-KEY'], str) or \
451
                len(str.strip(req.headers['API-KEY'])) == 0:
452
            access_control(req)
453
        else:
454
            api_key_control(req)
455
        if not id_.isdigit() or int(id_) <= 0:
456
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
457
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
458
459
        cnx = mysql.connector.connect(**config.myems_system_db)
460
        cursor = cnx.cursor()
461
462
        query = (" SELECT id, name, uuid "
463
                 " FROM tbl_distribution_systems ")
464
        cursor.execute(query)
465
        rows_distribution_systems = cursor.fetchall()
466
467
        distribution_system_dict = dict()
468
        if rows_distribution_systems is not None and len(rows_distribution_systems) > 0:
469
            for row in rows_distribution_systems:
470
                distribution_system_dict[row[2]] = {"id": row[0],
471
                                                    "name": row[1],
472
                                                    "uuid": row[2]}
473
474
        cursor.execute(" SELECT name "
475
                       " FROM tbl_distribution_circuits "
476
                       " WHERE id = %s ", (id_,))
477
        if cursor.fetchone() is None:
478
            cursor.close()
479
            cnx.close()
480
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
481
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
482
483
        query = (" SELECT p.id AS point_id, p.name AS point_name, p.address AS point_address, "
484
                 "        dc.id AS distribution_circuit_id, dc.name AS distribution_circuit_name, "
485
                 "        dc.uuid AS distribution_circuit_uuid "
486
                 " FROM tbl_points p, tbl_distribution_circuits_points dcp, tbl_distribution_circuits dc "
487
                 " WHERE dcp.distribution_circuit_id = %s AND p.id = dcp.point_id "
488
                 "       AND dcp.distribution_circuit_id = dc.id "
489
                 " ORDER BY p.name ")
490
        cursor.execute(query, (id_,))
491
        rows = cursor.fetchall()
492
493
        result = list()
494
        if rows is not None and len(rows) > 0:
495
            for row in rows:
496
                meta_result = {"id": row[0], "name": row[1], "address": row[2],
497
                               "distribution_circuit": {"id": row[3],
498
                                                        "name": row[4],
499
                                                        "uuid": row[5]}}
500
                result.append(meta_result)
501
502
        resp.text = json.dumps(result)
503
504
    @staticmethod
505
    @user_logger
506
    def on_post(req, resp, id_):
507
        """Handles POST requests"""
508
        admin_control(req)
509
        try:
510
            raw_json = req.stream.read().decode('utf-8')
511
        except UnicodeDecodeError as ex:
512
            print("Failed to decode request")
513
            raise falcon.HTTPError(status=falcon.HTTP_400,
514
                                   title='API.BAD_REQUEST',
515
                                   description='API.INVALID_ENCODING')
516
        except Exception as ex:
517
            print("Unexpected error reading request stream")
518
            raise falcon.HTTPError(status=falcon.HTTP_400,
519
                                   title='API.BAD_REQUEST',
520
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
521
522
        if not id_.isdigit() or int(id_) <= 0:
523
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
524
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
525
526
        new_values = json.loads(raw_json)
527
528
        cnx = mysql.connector.connect(**config.myems_system_db)
529
        cursor = cnx.cursor()
530
531
        cursor.execute(" SELECT name, distribution_system_id "
532
                       " from tbl_distribution_circuits "
533
                       " WHERE id = %s ", (id_,))
534
        row = cursor.fetchone()
535
        if row is None:
536
            cursor.close()
537
            cnx.close()
538
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
539
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
540
        distribution_system_id = row[1]
541
542
        cursor.execute(" SELECT name "
543
                       " FROM tbl_points "
544
                       " WHERE id = %s ", (new_values['data']['point_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.POINT_NOT_FOUND')
550
551
        query = (" SELECT id "
552
                 " FROM tbl_distribution_circuits_points "
553
                 " WHERE distribution_circuit_id = %s AND point_id = %s")
554
        cursor.execute(query, (id_, new_values['data']['point_id'],))
555
        if cursor.fetchone() is not None:
556
            cursor.close()
557
            cnx.close()
558
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
559
                                   description='API.DISTRIBUTION_CIRCUIT_POINT_RELATION_EXISTS')
560
561
        add_row = (" INSERT INTO tbl_distribution_circuits_points (distribution_circuit_id, point_id) "
562
                   " VALUES (%s, %s) ")
563
        cursor.execute(add_row, (id_, new_values['data']['point_id'],))
564
        cnx.commit()
565
        cursor.close()
566
        cnx.close()
567
568
        resp.status = falcon.HTTP_201
569
        resp.location = '/distributioncircuits/' + str(id_) + '/points/' + str(new_values['data']['point_id'])
570
571
572 View Code Duplication
class DistributionCircuitPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
573
    def __init__(self):
574
        pass
575
576
    @staticmethod
577
    def on_options(req, resp, id_, pid):
578
        _ = req
579
        resp.status = falcon.HTTP_200
580
        _ = id_
581
582
    @staticmethod
583
    @user_logger
584
    def on_delete(req, resp, id_, pid):
585
        admin_control(req)
586
        if not id_.isdigit() or int(id_) <= 0:
587
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
588
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
589
590
        if not pid.isdigit() or int(pid) <= 0:
591
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
592
                                   description='API.INVALID_POINT_ID')
593
594
        cnx = mysql.connector.connect(**config.myems_system_db)
595
        cursor = cnx.cursor()
596
597
        cursor.execute(" SELECT name, distribution_system_id "
598
                       " FROM tbl_distribution_circuits "
599
                       " WHERE id = %s ", (id_,))
600
        row = cursor.fetchone()
601
        if row is None:
602
            cursor.close()
603
            cnx.close()
604
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
605
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
606
        distribution_system_id = row[1]
607
608
        cursor.execute(" SELECT name "
609
                       " FROM tbl_points "
610
                       " WHERE id = %s ", (pid,))
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.POINT_NOT_FOUND')
616
617
        cursor.execute(" SELECT id "
618
                       " FROM tbl_distribution_circuits_points "
619
                       " WHERE distribution_circuit_id = %s AND point_id = %s ", (id_, pid))
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.DISTRIBUTION_CIRCUIT_POINT_RELATION_NOT_FOUND')
625
626
        cursor.execute(" DELETE FROM tbl_distribution_circuits_points "
627
                       " WHERE distribution_circuit_id = %s AND point_id = %s ", (id_, pid))
628
        cnx.commit()
629
630
        cursor.close()
631
        cnx.close()
632
633
        resp.status = falcon.HTTP_204
634
635