Passed
Push — master ( 42322a...183c79 )
by
unknown
10:22 queued 16s
created

DistributionSystemItem.on_delete()   B

Complexity

Conditions 6

Size

Total Lines 41
Code Lines 33

Duplication

Lines 41
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 33
dl 41
loc 41
rs 8.1546
c 0
b 0
f 0
cc 6
nop 3
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 DistributionSystemCollection:
11
    def __init__(self):
12
        """Initializes DistributionSystemCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        _ = req
18
        resp.status = falcon.HTTP_200
19
20
    @staticmethod
21
    def on_get(req, resp):
22
        if 'API-KEY' not in req.headers or \
23
                not isinstance(req.headers['API-KEY'], str) or \
24
                len(str.strip(req.headers['API-KEY'])) == 0:
25
            access_control(req)
26
        else:
27
            api_key_control(req)
28
        cnx = mysql.connector.connect(**config.myems_system_db)
29
        cursor = cnx.cursor()
30
31
        svg_dict = dict()
32
        query = (" SELECT id, name, uuid, source_code "
33
                 " FROM tbl_svgs ")
34
        cursor.execute(query)
35
        rows_svgs = cursor.fetchall()
36
        if rows_svgs is not None and len(rows_svgs) > 0:
37
            for row in rows_svgs:
38
                svg_dict[row[0]] = {"id": row[0],
39
                                    "name": row[1],
40
                                    "uuid": row[2],
41
                                    "source_code": row[3]}
42
43
        query = (" SELECT id, name, uuid, "
44
                 "        svg_id, description "
45
                 " FROM tbl_distribution_systems "
46
                 " ORDER BY id ")
47
        cursor.execute(query)
48
        rows_distribution_systems = cursor.fetchall()
49
50
        result = list()
51
        if rows_distribution_systems is not None and len(rows_distribution_systems) > 0:
52
            for row in rows_distribution_systems:
53
54
                meta_result = {"id": row[0],
55
                               "name": row[1],
56
                               "uuid": row[2],
57
                               "svg": svg_dict.get(row[3], None),
58
                               "description": row[4]}
59
                result.append(meta_result)
60
61
        cursor.close()
62
        cnx.close()
63
        resp.text = json.dumps(result)
64
65
    @staticmethod
66
    @user_logger
67
    def on_post(req, resp):
68
        """Handles POST requests"""
69
        admin_control(req)
70
        try:
71
            raw_json = req.stream.read().decode('utf-8')
72
        except Exception as ex:
73
            print(str(ex))
74
            raise falcon.HTTPError(status=falcon.HTTP_400,
75
                                   title='API.BAD_REQUEST',
76
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
77
78
        new_values = json.loads(raw_json)
79
80
        if 'name' not in new_values['data'].keys() or \
81
                not isinstance(new_values['data']['name'], str) or \
82
                len(str.strip(new_values['data']['name'])) == 0:
83
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
84
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_NAME')
85
        name = str.strip(new_values['data']['name'])
86
87
        if 'svg_id' not in new_values['data'].keys() or \
88
                not isinstance(new_values['data']['svg_id'], int) or \
89
                new_values['data']['svg_id'] <= 0:
90
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
91
                                   description='API.INVALID_SVG_ID')
92
        svg_id = new_values['data']['svg_id']
93
94
        if 'description' in new_values['data'].keys() and \
95
                new_values['data']['description'] is not None and \
96
                len(str(new_values['data']['description'])) > 0:
97
            description = str.strip(new_values['data']['description'])
98
        else:
99
            description = None
100
101
        cnx = mysql.connector.connect(**config.myems_system_db)
102
        cursor = cnx.cursor()
103
104
        cursor.execute(" SELECT name "
105
                       " FROM tbl_distribution_systems "
106
                       " WHERE name = %s ", (name,))
107
        if cursor.fetchone() is not None:
108
            cursor.close()
109
            cnx.close()
110
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
111
                                   description='API.DISTRIBUTION_SYSTEM_NAME_IS_ALREADY_IN_USE')
112
113
        cursor.execute(" SELECT name "
114
                       " FROM tbl_svgs "
115
                       " WHERE id = %s ",
116
                       (svg_id,))
117
        row = cursor.fetchone()
118
        if row is None:
119
            cursor.close()
120
            cnx.close()
121
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
122
                                   description='API.SVG_NOT_FOUND')
123
124
        add_values = (" INSERT INTO tbl_distribution_systems "
125
                      "    (name, uuid, svg_id, description) "
126
                      " VALUES (%s, %s, %s, %s) ")
127
        cursor.execute(add_values, (name,
128
                                    str(uuid.uuid4()),
129
                                    svg_id,
130
                                    description))
131
        new_id = cursor.lastrowid
132
        cnx.commit()
133
        cursor.close()
134
        cnx.close()
135
136
        resp.status = falcon.HTTP_201
137
        resp.location = '/distributionsystems/' + str(new_id)
138
139
140
class DistributionSystemItem:
141
    def __init__(self):
142
        """Initializes DistributionSystemItem"""
143
        pass
144
145
    @staticmethod
146
    def on_options(req, resp, id_):
147
        _ = req
148
        resp.status = falcon.HTTP_200
149
        _ = id_
150
151
    @staticmethod
152
    def on_get(req, resp, id_):
153
        if 'API-KEY' not in req.headers or \
154
                not isinstance(req.headers['API-KEY'], str) or \
155
                len(str.strip(req.headers['API-KEY'])) == 0:
156
            access_control(req)
157
        else:
158
            api_key_control(req)
159
        if not id_.isdigit() or int(id_) <= 0:
160
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
161
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
162
163
        cnx = mysql.connector.connect(**config.myems_system_db)
164
        cursor = cnx.cursor()
165
166
        svg_dict = dict()
167
        query = (" SELECT id, name, uuid, source_code "
168
                 " FROM tbl_svgs ")
169
        cursor.execute(query)
170
        rows_svgs = cursor.fetchall()
171
        if rows_svgs is not None and len(rows_svgs) > 0:
172
            for row in rows_svgs:
173
                svg_dict[row[0]] = {"id": row[0],
174
                                    "name": row[1],
175
                                    "uuid": row[2],
176
                                    "source_code": row[3]}
177
178
        query = (" SELECT id, name, uuid, "
179
                 "        svg_id, description "
180
                 " FROM tbl_distribution_systems "
181
                 " WHERE id = %s ")
182
        cursor.execute(query, (id_,))
183
        row = cursor.fetchone()
184
        cursor.close()
185
        cnx.close()
186
187
        if row is None:
188
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
189
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
190
        else:
191
            meta_result = {"id": row[0],
192
                           "name": row[1],
193
                           "uuid": row[2],
194
                           "svg": svg_dict.get(row[3], None),
195
                           "description": row[4]}
196
197
        resp.text = json.dumps(meta_result)
198
199 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
200
    @user_logger
201
    def on_delete(req, resp, id_):
202
        admin_control(req)
203
        if not id_.isdigit() or int(id_) <= 0:
204
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
205
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
206
        cnx = mysql.connector.connect(**config.myems_system_db)
207
        cursor = cnx.cursor()
208
209
        cursor.execute(" SELECT name "
210
                       " FROM tbl_distribution_systems "
211
                       " WHERE id = %s ", (id_,))
212
        if cursor.fetchone() is None:
213
            cursor.close()
214
            cnx.close()
215
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
216
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
217
218
        # check relation with spaces
219
        cursor.execute(" SELECT id "
220
                       " FROM tbl_spaces_distribution_systems "
221
                       " WHERE distribution_system_id = %s ", (id_,))
222
        rows_spaces = cursor.fetchall()
223
        if rows_spaces is not None and len(rows_spaces) > 0:
224
            cursor.close()
225
            cnx.close()
226
            raise falcon.HTTPError(status=falcon.HTTP_400,
227
                                   title='API.BAD_REQUEST',
228
                                   description='API.THERE_IS_RELATION_WITH_SPACES')
229
230
        cursor.execute(" DELETE FROM tbl_distribution_circuits_points WHERE distribution_circuit_id "
231
                       "IN (SELECT id FROM tbl_distribution_circuits WHERE distribution_system_id = %s) ", (id_,))
232
        cursor.execute(" DELETE FROM tbl_distribution_circuits WHERE distribution_system_id = %s ", (id_,))
233
        cursor.execute(" DELETE FROM tbl_distribution_systems WHERE id = %s ", (id_,))
234
        cnx.commit()
235
236
        cursor.close()
237
        cnx.close()
238
239
        resp.status = falcon.HTTP_204
240
241
    @staticmethod
242
    @user_logger
243
    def on_put(req, resp, id_):
244
        """Handles PUT requests"""
245
        admin_control(req)
246
        try:
247
            raw_json = req.stream.read().decode('utf-8')
248
        except Exception as ex:
249
            print(str(ex))
250
            raise falcon.HTTPError(status=falcon.HTTP_400,
251
                                   title='API.BAD_REQUEST',
252
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
253
254
        if not id_.isdigit() or int(id_) <= 0:
255
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
256
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
257
258
        new_values = json.loads(raw_json)
259
260
        if 'name' not in new_values['data'].keys() or \
261
                not isinstance(new_values['data']['name'], str) or \
262
                len(str.strip(new_values['data']['name'])) == 0:
263
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
264
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_NAME')
265
        name = str.strip(new_values['data']['name'])
266
267
        if 'svg_id' not in new_values['data'].keys() or \
268
                not isinstance(new_values['data']['svg_id'], int) or \
269
                new_values['data']['svg_id'] <= 0:
270
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
271
                                   description='API.INVALID_SVG_ID')
272
        svg_id = new_values['data']['svg_id']
273
274
        if 'description' in new_values['data'].keys() and \
275
                new_values['data']['description'] is not None and \
276
                len(str(new_values['data']['description'])) > 0:
277
            description = str.strip(new_values['data']['description'])
278
        else:
279
            description = None
280
281
        cnx = mysql.connector.connect(**config.myems_system_db)
282
        cursor = cnx.cursor()
283
284
        cursor.execute(" SELECT name "
285
                       " FROM tbl_distribution_systems "
286
                       " WHERE name = %s AND id != %s ", (name, id_))
287
        if cursor.fetchone() is not None:
288
            cursor.close()
289
            cnx.close()
290
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
291
                                   description='API.DISTRIBUTION_SYSTEM_NAME_IS_ALREADY_IN_USE')
292
293
        cursor.execute(" SELECT name "
294
                       " FROM tbl_svgs "
295
                       " WHERE id = %s ",
296
                       (new_values['data']['svg_id'],))
297
        row = cursor.fetchone()
298
        if row is None:
299
            cursor.close()
300
            cnx.close()
301
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
302
                                   description='API.SVG_NOT_FOUND')
303
304
        update_row = (" UPDATE tbl_distribution_systems "
305
                      " SET name = %s, svg_id = %s, description = %s "
306
                      " WHERE id = %s ")
307
        cursor.execute(update_row, (name,
308
                                    svg_id,
309
                                    description,
310
                                    id_))
311
        cnx.commit()
312
313
        cursor.close()
314
        cnx.close()
315
316
        resp.status = falcon.HTTP_200
317
318
319 View Code Duplication
class DistributionSystemDistributionCircuitCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
320
    def __init__(self):
321
        """Initializes DistributionSystemDistributionCircuitCollection"""
322
        pass
323
324
    @staticmethod
325
    def on_options(req, resp, id_):
326
        _ = req
327
        resp.status = falcon.HTTP_200
328
        _ = id_
329
330
    @staticmethod
331
    def on_get(req, resp, id_):
332
        if 'API-KEY' not in req.headers or \
333
                not isinstance(req.headers['API-KEY'], str) or \
334
                len(str.strip(req.headers['API-KEY'])) == 0:
335
            access_control(req)
336
        else:
337
            api_key_control(req)
338
        if not id_.isdigit() or int(id_) <= 0:
339
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
340
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
341
342
        cnx = mysql.connector.connect(**config.myems_system_db)
343
        cursor = cnx.cursor()
344
345
        cursor.execute(" SELECT name "
346
                       " FROM tbl_distribution_systems "
347
                       " WHERE id = %s ", (id_,))
348
        if cursor.fetchone() is None:
349
            cursor.close()
350
            cnx.close()
351
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
352
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
353
354
        query = (" SELECT id, name, uuid, "
355
                 "        distribution_room, switchgear, peak_load, peak_current, customers, meters "
356
                 " FROM tbl_distribution_circuits "
357
                 " WHERE distribution_system_id = %s "
358
                 " ORDER BY name ")
359
        cursor.execute(query, (id_,))
360
        rows = cursor.fetchall()
361
362
        result = list()
363
        if rows is not None and len(rows) > 0:
364
            for row in rows:
365
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
366
                               "distribution_room": row[3], "switchgear": row[4],
367
                               "peak_load": row[5], "peak_current": row[6],
368
                               "customers": row[7], "meters": row[8]}
369
                result.append(meta_result)
370
371
        resp.text = json.dumps(result)
372
373
374
class DistributionSystemExport:
375
    def __init__(self):
376
        """Initializes DistributionSystemExport"""
377
        pass
378
379
    @staticmethod
380
    def on_options(req, resp, id_):
381
        _ = req
382
        resp.status = falcon.HTTP_200
383
        _ = id_
384
385
    @staticmethod
386
    def on_get(req, resp, id_):
387
        if 'API-KEY' not in req.headers or \
388
                not isinstance(req.headers['API-KEY'], str) or \
389
                len(str.strip(req.headers['API-KEY'])) == 0:
390
            access_control(req)
391
        else:
392
            api_key_control(req)
393
        if not id_.isdigit() or int(id_) <= 0:
394
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
395
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
396
397
        cnx = mysql.connector.connect(**config.myems_system_db)
398
        cursor = cnx.cursor()
399
400
        query = (" SELECT id, name, uuid "
401
                 " FROM tbl_svgs ")
402
        cursor.execute(query)
403
        rows_svgs = cursor.fetchall()
404
405
        svg_dict = dict()
406
        if rows_svgs is not None and len(rows_svgs) > 0:
407
            for row in rows_svgs:
408
                svg_dict[row[0]] = {"id": row[0],
409
                                    "name": row[1],
410
                                    "uuid": row[2]}
411
412
        query = (" SELECT id, name, uuid, "
413
                 "        svg_id, description "
414
                 " FROM tbl_distribution_systems "
415
                 " WHERE id = %s ")
416
        cursor.execute(query, (id_,))
417
        row = cursor.fetchone()
418
419
        if row is None:
420
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
421
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
422
        else:
423
            meta_result = {"id": row[0],
424
                           "name": row[1],
425
                           "uuid": row[2],
426
                           "svg": svg_dict.get(row[3], None),
427
                           "description": row[4],
428
                           "circuits": None}
429
            query = (" SELECT id, name, uuid, "
430
                     "        distribution_room, switchgear, peak_load, peak_current, customers, meters "
431
                     " FROM tbl_distribution_circuits "
432
                     " WHERE distribution_system_id = %s "
433
                     " ORDER BY name ")
434
            cursor.execute(query, (id_,))
435
            rows = cursor.fetchall()
436
437
            result = list()
438 View Code Duplication
            if rows is not None and len(rows) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
439
                for row in rows:
440
                    circuit_result = {"id": row[0], "name": row[1], "uuid": row[2],
441
                                      "distribution_room": row[3], "switchgear": row[4],
442
                                      "peak_load": row[5], "peak_current": row[6],
443
                                      "customers": row[7], "meters": row[8],
444
                                      "points": None}
445
                    query = (" SELECT p.id AS point_id, p.name AS point_name, "
446
                             "        dc.id AS distribution_circuit_id, dc.name AS distribution_circuit_name, "
447
                             "        dc.uuid AS distribution_circuit_uuid "
448
                             " FROM tbl_points p, tbl_distribution_circuits_points dcp, tbl_distribution_circuits dc "
449
                             " WHERE dcp.distribution_circuit_id = %s AND p.id = dcp.point_id "
450
                             "       AND dcp.distribution_circuit_id = dc.id "
451
                             " ORDER BY p.name ")
452
                    cursor.execute(query, (circuit_result['id'],))
453
                    rows = cursor.fetchall()
454
455
                    points = list()
456
                    if rows is not None and len(rows) > 0:
457
                        for point_row in rows:
458
                            point_result = {"id": point_row[0], "name": point_row[1]}
459
                            points.append(point_result)
460
                        circuit_result['points'] = points
461
462
                    result.append(circuit_result)
463
                meta_result['circuits'] = result
464
465
        cursor.close()
466
        cnx.close()
467
        resp.text = json.dumps(meta_result)
468
469
470
class DistributionSystemImport:
471
    def __init__(self):
472
        """Initializes DistributionSystemImport"""
473
        pass
474
475
    @staticmethod
476
    def on_options(req, resp):
477
        _ = req
478
        resp.status = falcon.HTTP_200
479
480
    @staticmethod
481
    @user_logger
482
    def on_post(req, resp):
483
        """Handles POST requests"""
484
        admin_control(req)
485
        try:
486
            raw_json = req.stream.read().decode('utf-8')
487
        except Exception as ex:
488
            print(str(ex))
489
            raise falcon.HTTPError(status=falcon.HTTP_400,
490
                                   title='API.BAD_REQUEST',
491
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
492
493
        new_values = json.loads(raw_json)
494
495
        if 'name' not in new_values.keys() or \
496
                not isinstance(new_values['name'], str) or \
497
                len(str.strip(new_values['name'])) == 0:
498
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
499
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_NAME')
500
        name = str.strip(new_values['name'])
501
502
        if 'svg' not in new_values.keys() or \
503
                'id' not in new_values['svg'].keys() or \
504
                not isinstance(new_values['svg']['id'], int) or \
505
                new_values['svg']['id'] <= 0:
506
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
507
                                   description='API.INVALID_SVG_ID')
508
        svg_id = new_values['svg']['id']
509
510
        if 'description' in new_values.keys() and \
511
                new_values['description'] is not None and \
512
                len(str(new_values['description'])) > 0:
513
            description = str.strip(new_values['description'])
514
        else:
515
            description = None
516
517
        cnx = mysql.connector.connect(**config.myems_system_db)
518
        cursor = cnx.cursor()
519
520
        cursor.execute(" SELECT name "
521
                       " FROM tbl_distribution_systems "
522
                       " WHERE name = %s ", (name,))
523
        if cursor.fetchone() is not None:
524
            cursor.close()
525
            cnx.close()
526
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
527
                                   description='API.DISTRIBUTION_SYSTEM_NAME_IS_ALREADY_IN_USE')
528
529
        cursor.execute(" SELECT name "
530
                       " FROM tbl_svgs "
531
                       " WHERE id = %s ",
532
                       (svg_id,))
533
        row = cursor.fetchone()
534
        if row is None:
535
            cursor.close()
536
            cnx.close()
537
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
538
                                   description='API.SVG_NOT_FOUND')
539
540
        add_values = (" INSERT INTO tbl_distribution_systems "
541
                      "    (name, uuid, svg_id, description) "
542
                      " VALUES (%s, %s, %s, %s) ")
543
        cursor.execute(add_values, (name,
544
                                    str(uuid.uuid4()),
545
                                    svg_id,
546
                                    description))
547
        new_id = cursor.lastrowid
548 View Code Duplication
        if new_values['circuits'] is not None and len(new_values['circuits']) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
549
            for circuit in new_values['circuits']:
550
                add_values = (" INSERT INTO tbl_distribution_circuits "
551
                              "    (name, uuid, distribution_system_id,"
552
                              "     distribution_room, switchgear, peak_load, peak_current, customers, meters) "
553
                              " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ")
554
                cursor.execute(add_values, (circuit['name'],
555
                                            str(uuid.uuid4()),
556
                                            new_id,
557
                                            circuit['distribution_room'],
558
                                            circuit['switchgear'],
559
                                            circuit['peak_load'],
560
                                            circuit['peak_current'],
561
                                            circuit['customers'],
562
                                            circuit['meters']))
563
                circuit_id = cursor.lastrowid
564
                if circuit['points'] is not None and len(circuit['points']) > 0:
565
                    for point in circuit['points']:
566
                        cursor.execute(" SELECT name "
567
                                       " FROM tbl_points "
568
                                       " WHERE id = %s ", (point['id'],))
569
                        if cursor.fetchone() is None:
570
                            cursor.close()
571
                            cnx.close()
572
                            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
573
                                                   description='API.POINT_NOT_FOUND')
574
575
                        query = (" SELECT id "
576
                                 " FROM tbl_distribution_circuits_points "
577
                                 " WHERE distribution_circuit_id = %s AND point_id = %s")
578
                        cursor.execute(query, (circuit_id, point['id'],))
579
                        if cursor.fetchone() is not None:
580
                            cursor.close()
581
                            cnx.close()
582
                            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
583
                                                   description='API.DISTRIBUTION_CIRCUIT_POINT_RELATION_EXISTS')
584
585
                        add_row = (" INSERT INTO tbl_distribution_circuits_points (distribution_circuit_id, point_id) "
586
                                   " VALUES (%s, %s) ")
587
                        cursor.execute(add_row, (circuit_id, point['id'],))
588
589
        cnx.commit()
590
        cursor.close()
591
        cnx.close()
592
593
        resp.status = falcon.HTTP_201
594
        resp.location = '/distributionsystems/' + str(new_id)
595
596
597
class DistributionSystemClone:
598
    def __init__(self):
599
        """Initializes DistributionSystemClone"""
600
        pass
601
602
    @staticmethod
603
    def on_options(req, resp, id_):
604
        _ = req
605
        resp.status = falcon.HTTP_200
606
        _ = id_
607
608
    @staticmethod
609
    @user_logger
610
    def on_post(req, resp, id_):
611
        admin_control(req)
612
        if not id_.isdigit() or int(id_) <= 0:
613
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
614
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
615
616
        cnx = mysql.connector.connect(**config.myems_system_db)
617
        cursor = cnx.cursor()
618
619
        query = (" SELECT id, name, uuid, "
620
                 "        svg_id, description "
621
                 " FROM tbl_distribution_systems "
622
                 " WHERE id = %s ")
623
        cursor.execute(query, (id_,))
624
        row = cursor.fetchone()
625
626
        if row is None:
627
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
628
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
629
        else:
630
            meta_result = {"id": row[0],
631
                           "name": row[1],
632
                           "uuid": row[2],
633
                           "svg_id": row[3],
634
                           "description": row[4],
635
                           "circuits": None}
636
            query = (" SELECT id, name, uuid, "
637
                     "        distribution_room, switchgear, peak_load, peak_current, customers, meters "
638
                     " FROM tbl_distribution_circuits "
639
                     " WHERE distribution_system_id = %s "
640
                     " ORDER BY name ")
641
            cursor.execute(query, (id_,))
642
            rows = cursor.fetchall()
643
644
            result = list()
645 View Code Duplication
            if rows is not None and len(rows) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
646
                for row in rows:
647
                    circuit_result = {"id": row[0], "name": row[1], "uuid": row[2],
648
                                      "distribution_room": row[3], "switchgear": row[4],
649
                                      "peak_load": row[5], "peak_current": row[6],
650
                                      "customers": row[7], "meters": row[8],
651
                                      "points": None}
652
                    query = (" SELECT p.id AS point_id, p.name AS point_name, p.address AS point_address, "
653
                             "        dc.id AS distribution_circuit_id, dc.name AS distribution_circuit_name, "
654
                             "        dc.uuid AS distribution_circuit_uuid "
655
                             " FROM tbl_points p, tbl_distribution_circuits_points dcp, tbl_distribution_circuits dc "
656
                             " WHERE dcp.distribution_circuit_id = %s AND p.id = dcp.point_id "
657
                             "       AND dcp.distribution_circuit_id = dc.id "
658
                             " ORDER BY p.name ")
659
                    cursor.execute(query, (circuit_result['id'],))
660
                    rows = cursor.fetchall()
661
662
                    points = list()
663
                    if rows is not None and len(rows) > 0:
664
                        for point_row in rows:
665
                            point_result = {"id": point_row[0], "name": point_row[1], "address": point_row[2]}
666
                            points.append(point_result)
667
                        circuit_result['points'] = points
668
669
                    result.append(circuit_result)
670
                meta_result['circuits'] = result
671
            timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
672
            if config.utc_offset[0] == '-':
673
                timezone_offset = -timezone_offset
674
            new_name = (str.strip(meta_result['name']) +
675
                        (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds'))
676
            add_values = (" INSERT INTO tbl_distribution_systems "
677
                          "    (name, uuid, svg_id, description) "
678
                          " VALUES (%s, %s, %s, %s) ")
679
            cursor.execute(add_values, (new_name,
680
                                        str(uuid.uuid4()),
681
                                        meta_result['svg_id'],
682
                                        meta_result['description']))
683
            new_id = cursor.lastrowid
684 View Code Duplication
            if meta_result['circuits'] is not None and len(meta_result['circuits']) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
685
                for circuit in meta_result['circuits']:
686
                    add_values = (" INSERT INTO tbl_distribution_circuits "
687
                                  "    (name, uuid, distribution_system_id,"
688
                                  "     distribution_room, switchgear, peak_load, peak_current, customers, meters) "
689
                                  " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ")
690
                    cursor.execute(add_values, (circuit['name'],
691
                                                str(uuid.uuid4()),
692
                                                new_id,
693
                                                circuit['distribution_room'],
694
                                                circuit['switchgear'],
695
                                                circuit['peak_load'],
696
                                                circuit['peak_current'],
697
                                                circuit['customers'],
698
                                                circuit['meters']))
699
                    circuit_id = cursor.lastrowid
700
                    if circuit['points'] is not None and len(circuit['points']) > 0:
701
                        for point in circuit['points']:
702
                            cursor.execute(" SELECT name "
703
                                           " FROM tbl_points "
704
                                           " WHERE id = %s ", (point['id'],))
705
                            if cursor.fetchone() is None:
706
                                cursor.close()
707
                                cnx.close()
708
                                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
709
                                                       description='API.POINT_NOT_FOUND')
710
711
                            query = (" SELECT id "
712
                                     " FROM tbl_distribution_circuits_points "
713
                                     " WHERE distribution_circuit_id = %s AND point_id = %s")
714
                            cursor.execute(query, (circuit_id, point['id'],))
715
                            if cursor.fetchone() is not None:
716
                                cursor.close()
717
                                cnx.close()
718
                                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
719
                                                       description='API.DISTRIBUTION_CIRCUIT_POINT_RELATION_EXISTS')
720
721
                            add_row = (
722
                                " INSERT INTO tbl_distribution_circuits_points (distribution_circuit_id, point_id) "
723
                                " VALUES (%s, %s) ")
724
                            cursor.execute(add_row, (circuit_id, point['id'],))
725
            cnx.commit()
726
            cursor.close()
727
            cnx.close()
728
729
            resp.status = falcon.HTTP_201
730
            resp.location = '/distributionsystems/' + str(new_id)
731