Passed
Push — master ( 844492...7c39ee )
by
unknown
09:45 queued 11s
created

core.distributionsystem   F

Complexity

Total Complexity 135

Size/Duplication

Total Lines 746
Duplicated Lines 24.93 %

Importance

Changes 0
Metric Value
wmc 135
eloc 550
dl 186
loc 746
rs 2
c 0
b 0
f 0

21 Methods

Rating   Name   Duplication   Size   Complexity  
A DistributionSystemCollection.__init__() 0 3 1
A DistributionSystemCollection.on_options() 0 5 1
A DistributionSystemImport.__init__() 0 2 1
A DistributionSystemDistributionCircuitCollection.__init__() 2 2 1
A DistributionSystemExport.__init__() 0 2 1
D DistributionSystemCollection.on_get() 0 56 12
A DistributionSystemClone.on_options() 0 5 1
A DistributionSystemItem.on_options() 0 5 1
F DistributionSystemItem.on_put() 0 76 15
F DistributionSystemExport.on_get() 26 83 16
C DistributionSystemItem.on_get() 0 47 10
F DistributionSystemClone.on_post() 67 123 19
B DistributionSystemItem.on_delete() 0 41 6
A DistributionSystemExport.on_options() 0 5 1
A DistributionSystemImport.on_options() 0 4 1
A DistributionSystemItem.__init__() 0 2 1
A DistributionSystemDistributionCircuitCollection.on_options() 5 5 1
C DistributionSystemDistributionCircuitCollection.on_get() 42 42 10
A DistributionSystemClone.__init__() 0 2 1
D DistributionSystemCollection.on_post() 0 73 13
F DistributionSystemImport.on_post() 40 115 22

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