Passed
Push — master ( 8a9faa...4be142 )
by Guangyu
02:22 queued 10s
created

core.meter.MeterSubmeterCollection.__init__()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
import uuid
6
7
8
class MeterCollection:
9
    @staticmethod
10
    def __init__():
11
        pass
12
13
    @staticmethod
14
    def on_options(req, resp):
15
        resp.status = falcon.HTTP_200
16
17
    @staticmethod
18
    def on_get(req, resp):
19
        cnx = mysql.connector.connect(**config.myems_system_db)
20
        cursor = cnx.cursor(dictionary=True)
21
22
        query = (" SELECT id, name, uuid "
23
                 " FROM tbl_energy_categories ")
24
        cursor.execute(query)
25
        rows_energy_categories = cursor.fetchall()
26
27
        energy_category_dict = dict()
28
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
29
            for row in rows_energy_categories:
30
                energy_category_dict[row['id']] = {"id": row['id'],
31
                                                   "name": row['name'],
32
                                                   "uuid": row['uuid']}
33
34
        query = (" SELECT id, name, uuid "
35
                 " FROM tbl_cost_centers ")
36
        cursor.execute(query)
37
        rows_cost_centers = cursor.fetchall()
38
39
        cost_center_dict = dict()
40
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
41
            for row in rows_cost_centers:
42
                cost_center_dict[row['id']] = {"id": row['id'],
43
                                               "name": row['name'],
44
                                               "uuid": row['uuid']}
45
46
        query = (" SELECT id, name, uuid "
47
                 " FROM tbl_energy_items ")
48
        cursor.execute(query)
49
        rows_energy_items = cursor.fetchall()
50
51
        energy_item_dict = dict()
52
        if rows_energy_items is not None and len(rows_energy_items) > 0:
53
            for row in rows_energy_items:
54
                energy_item_dict[row['id']] = {"id": row['id'],
55
                                               "name": row['name'],
56
                                               "uuid": row['uuid']}
57
58
        query = (" SELECT id, name, uuid "
59
                 " FROM tbl_meters ")
60
        cursor.execute(query)
61
        rows_parent_meters = cursor.fetchall()
62
63
        parent_meter_dict = dict()
64
        if rows_parent_meters is not None and len(rows_parent_meters) > 0:
65
            for row in rows_parent_meters:
66
                parent_meter_dict[row['id']] = {"id": row['id'],
67
                                                "name": row['name'],
68
                                                "uuid": row['uuid']}
69
70
        query = (" SELECT id, name, uuid, energy_category_id, "
71
                 "        is_counted, hourly_low_limit, hourly_high_limit, "
72
                 "        cost_center_id, energy_item_id, parent_meter_id, description "
73
                 " FROM tbl_meters "
74
                 " ORDER BY id ")
75
        cursor.execute(query)
76
        rows_meters = cursor.fetchall()
77
78
        result = list()
79 View Code Duplication
        if rows_meters is not None and len(rows_meters) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
80
            for row in rows_meters:
81
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
82
                cost_center = cost_center_dict.get(row['cost_center_id'], None)
83
                energy_item = energy_item_dict.get(row['energy_item_id'], None)
84
                parent_meter = parent_meter_dict.get(row['parent_meter_id'], None)
85
                meta_result = {"id": row['id'],
86
                               "name": row['name'],
87
                               "uuid": row['uuid'],
88
                               "energy_category": energy_category,
89
                               "is_counted": True if row['is_counted'] else False,
90
                               "hourly_low_limit": row['hourly_low_limit'],
91
                               "hourly_high_limit": row['hourly_high_limit'],
92
                               "cost_center": cost_center,
93
                               "energy_item": energy_item,
94
                               "parent_meter": parent_meter,
95
                               "description": row['description']}
96
                result.append(meta_result)
97
98
        cursor.close()
99
        cnx.disconnect()
100
        resp.body = json.dumps(result)
101
102
    @staticmethod
103
    def on_post(req, resp):
104
        """Handles POST requests"""
105
        try:
106
            raw_json = req.stream.read().decode('utf-8')
107
        except Exception as ex:
108
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex)
109
110
        new_values = json.loads(raw_json)
111
112
        if 'name' not in new_values['data'].keys() or \
113
                not isinstance(new_values['data']['name'], str) or \
114
                len(str.strip(new_values['data']['name'])) == 0:
115
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
116
                                   description='API.INVALID_METER_NAME')
117
        name = str.strip(new_values['data']['name'])
118
119
        if 'energy_category_id' not in new_values['data'].keys() or \
120
                not isinstance(new_values['data']['energy_category_id'], int) or \
121
                new_values['data']['energy_category_id'] <= 0:
122
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
123
                                   description='API.INVALID_ENERGY_CATEGORY_ID')
124
        energy_category_id = new_values['data']['energy_category_id']
125
126
        if 'is_counted' not in new_values['data'].keys() or \
127
                not isinstance(new_values['data']['is_counted'], bool):
128
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
129
                                   description='API.INVALID_IS_COUNTED_VALUE')
130
        is_counted = new_values['data']['is_counted']
131
132
        if 'hourly_low_limit' not in new_values['data'].keys() or \
133
                not (isinstance(new_values['data']['hourly_low_limit'], float) or
134
                     isinstance(new_values['data']['hourly_low_limit'], int)):
135
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
136
                                   description='API.INVALID_HOURLY_LOW_LIMIT_VALUE')
137
        hourly_low_limit = new_values['data']['hourly_low_limit']
138
139
        if 'hourly_high_limit' not in new_values['data'].keys() or \
140
                not (isinstance(new_values['data']['hourly_high_limit'], float) or
141
                     isinstance(new_values['data']['hourly_high_limit'], int)):
142
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
143
                                   description='API.INVALID_HOURLY_HIGH_LIMIT_VALUE')
144
        hourly_high_limit = new_values['data']['hourly_high_limit']
145
146
        if 'cost_center_id' not in new_values['data'].keys() or \
147
                not isinstance(new_values['data']['cost_center_id'], int) or \
148
                new_values['data']['cost_center_id'] <= 0:
149
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
150
                                       description='API.INVALID_COST_CENTER_ID')
151
        cost_center_id = new_values['data']['cost_center_id']
152
153
        if 'energy_item_id' in new_values['data'].keys() and \
154
                new_values['data']['energy_item_id'] is not None:
155
            if not isinstance(new_values['data']['energy_item_id'], int) or \
156
                    new_values['data']['energy_item_id'] <= 0:
157
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
158
                                       description='API.INVALID_ENERGY_ITEM_ID')
159
            energy_item_id = new_values['data']['energy_item_id']
160
        else:
161
            energy_item_id = None
162
163
        if 'parent_meter_id' in new_values['data'].keys():
164
            if not isinstance(new_values['data']['parent_meter_id'], int) or \
165
                    new_values['data']['parent_meter_id'] <= 0:
166
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
167
                                       description='API.INVALID_PARENT_METER_ID')
168
            parent_meter_id = new_values['data']['parent_meter_id']
169
        else:
170
            parent_meter_id = None
171
172
        if 'description' in new_values['data'].keys() and \
173
                new_values['data']['description'] is not None and \
174
                len(str(new_values['data']['description'])) > 0:
175
            description = str.strip(new_values['data']['description'])
176
        else:
177
            description = None
178
179
        cnx = mysql.connector.connect(**config.myems_system_db)
180
        cursor = cnx.cursor()
181
182
        cursor.execute(" SELECT name "
183
                       " FROM tbl_meters "
184
                       " WHERE name = %s ", (name,))
185
        if cursor.fetchone() is not None:
186
            cursor.close()
187
            cnx.disconnect()
188
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
189
                                   description='API.METER_NAME_IS_ALREADY_IN_USE')
190
191
        cursor.execute(" SELECT name "
192
                       " FROM tbl_energy_categories "
193
                       " WHERE id = %s ",
194
                       (new_values['data']['energy_category_id'],))
195
        if cursor.fetchone() is None:
196
            cursor.close()
197
            cnx.disconnect()
198
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
199
                                   description='API.ENERGY_CATEGORY_NOT_FOUND')
200
201
        cursor.execute(" SELECT name "
202
                       " FROM tbl_cost_centers "
203
                       " WHERE id = %s ",
204
                       (new_values['data']['cost_center_id'],))
205
        row = cursor.fetchone()
206
        if row is None:
207
            cursor.close()
208
            cnx.disconnect()
209
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
210
                                   description='API.COST_CENTER_NOT_FOUND')
211
212 View Code Duplication
        if energy_item_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
213
            cursor.execute(" SELECT name, energy_category_id "
214
                           " FROM tbl_energy_items "
215
                           " WHERE id = %s ",
216
                           (new_values['data']['energy_item_id'],))
217
            row = cursor.fetchone()
218
            if row is None:
219
                cursor.close()
220
                cnx.disconnect()
221
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
222
                                       description='API.ENERGY_ITEM_NOT_FOUND')
223
            else:
224
                if row[1] != energy_category_id:
225
                    cursor.close()
226
                    cnx.disconnect()
227
                    raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
228
                                           description='API.ENERGY_ITEM_DOES_NOT_BELONG_TO_ENERGY_CATEGORY')
229
230 View Code Duplication
        if parent_meter_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
231
            cursor.execute(" SELECT name, energy_category_id "
232
                           " FROM tbl_meters "
233
                           " WHERE id = %s ",
234
                           (new_values['data']['parent_meter_id'],))
235
            row = cursor.fetchone()
236
            if row is None:
237
                cursor.close()
238
                cnx.disconnect()
239
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
240
                                       description='API.PARENT_METER_NOT_FOUND')
241
            else:
242
                if row[1] != energy_category_id:
243
                    cursor.close()
244
                    cnx.disconnect()
245
                    raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
246
                                           description='API.PARENT_METER_DOES_NOT BELONG_TO_SAME_ENERGY_CATEGORY')
247
248
        add_values = (" INSERT INTO tbl_meters "
249
                      "    (name, uuid, energy_category_id, is_counted, hourly_low_limit, hourly_high_limit,"
250
                      "     cost_center_id, energy_item_id, parent_meter_id, description) "
251
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
252
        cursor.execute(add_values, (name,
253
                                    str(uuid.uuid4()),
254
                                    energy_category_id,
255
                                    is_counted,
256
                                    hourly_low_limit,
257
                                    hourly_high_limit,
258
                                    cost_center_id,
259
                                    energy_item_id,
260
                                    parent_meter_id,
261
                                    description))
262
        new_id = cursor.lastrowid
263
        cnx.commit()
264
        cursor.close()
265
        cnx.disconnect()
266
267
        resp.status = falcon.HTTP_201
268
        resp.location = '/meters/' + str(new_id)
269
270
271
class MeterItem:
272
    @staticmethod
273
    def __init__():
274
        pass
275
276
    @staticmethod
277
    def on_options(req, resp, id_):
278
        resp.status = falcon.HTTP_200
279
280
    @staticmethod
281
    def on_get(req, resp, id_):
282
        if not id_.isdigit() or int(id_) <= 0:
283
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
284
                                   description='API.INVALID_METER_ID')
285
286
        cnx = mysql.connector.connect(**config.myems_system_db)
287
        cursor = cnx.cursor(dictionary=True)
288
289
        query = (" SELECT id, name, uuid "
290
                 " FROM tbl_energy_categories ")
291
        cursor.execute(query)
292
        rows_energy_categories = cursor.fetchall()
293
294
        energy_category_dict = dict()
295
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
296
            for row in rows_energy_categories:
297
                energy_category_dict[row['id']] = {"id": row['id'],
298
                                                   "name": row['name'],
299
                                                   "uuid": row['uuid']}
300
301
        query = (" SELECT id, name, uuid "
302
                 " FROM tbl_cost_centers ")
303
        cursor.execute(query)
304
        rows_cost_centers = cursor.fetchall()
305
306
        cost_center_dict = dict()
307
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
308
            for row in rows_cost_centers:
309
                cost_center_dict[row['id']] = {"id": row['id'],
310
                                               "name": row['name'],
311
                                               "uuid": row['uuid']}
312
313
        query = (" SELECT id, name, uuid "
314
                 " FROM tbl_energy_items ")
315
        cursor.execute(query)
316
        rows_energy_items = cursor.fetchall()
317
318
        energy_item_dict = dict()
319
        if rows_energy_items is not None and len(rows_energy_items) > 0:
320
            for row in rows_energy_items:
321
                energy_item_dict[row['id']] = {"id": row['id'],
322
                                               "name": row['name'],
323
                                               "uuid": row['uuid']}
324
325
        query = (" SELECT id, name, uuid "
326
                 " FROM tbl_meters ")
327
        cursor.execute(query)
328
        rows_parent_meters = cursor.fetchall()
329
330
        parent_meter_dict = dict()
331
        if rows_parent_meters is not None and len(rows_parent_meters) > 0:
332
            for row in rows_parent_meters:
333
                parent_meter_dict[row['id']] = {"id": row['id'],
334
                                                "name": row['name'],
335
                                                "uuid": row['uuid']}
336
337
        query = (" SELECT id, name, uuid, energy_category_id, "
338
                 "        is_counted, hourly_low_limit, hourly_high_limit, "
339
                 "        cost_center_id, energy_item_id, parent_meter_id, description "
340
                 " FROM tbl_meters "
341
                 " WHERE id = %s ")
342
        cursor.execute(query, (id_,))
343
        row = cursor.fetchone()
344
        cursor.close()
345
        cnx.disconnect()
346
347 View Code Duplication
        if row is None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
348
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
349
                                   description='API.METER_NOT_FOUND')
350
        else:
351
            energy_category = energy_category_dict.get(row['energy_category_id'], None)
352
            cost_center = cost_center_dict.get(row['cost_center_id'], None)
353
            energy_item = energy_item_dict.get(row['energy_item_id'], None)
354
            parent_meter = parent_meter_dict.get(row['parent_meter_id'], None)
355
            meta_result = {"id": row['id'],
356
                           "name": row['name'],
357
                           "uuid": row['uuid'],
358
                           "energy_category": energy_category,
359
                           "is_counted": True if row['is_counted'] else False,
360
                           "hourly_low_limit": row['hourly_low_limit'],
361
                           "hourly_high_limit": row['hourly_high_limit'],
362
                           "cost_center": cost_center,
363
                           "energy_item": energy_item,
364
                           "parent_meter": parent_meter,
365
                           "description": row['description']}
366
367
        resp.body = json.dumps(meta_result)
368
369
    @staticmethod
370
    def on_delete(req, resp, id_):
371
        if not id_.isdigit() or int(id_) <= 0:
372
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
373
                                   description='API.INVALID_METER_ID')
374
375
        cnx = mysql.connector.connect(**config.myems_system_db)
376
        cursor = cnx.cursor()
377
378
        cursor.execute(" SELECT uuid "
379
                       " FROM tbl_meters "
380
                       " WHERE id = %s ", (id_,))
381
        row = cursor.fetchone()
382
        if row is None:
383
            cursor.close()
384
            cnx.disconnect()
385
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
386
                                   description='API.METER_NOT_FOUND')
387
        else:
388
            meter_uuid = row[0]
389
390
        # check if this meter is being used by virtual meters
391
        cursor.execute(" SELECT vm.name "
392
                       " FROM tbl_variables va, tbl_expressions ex, tbl_virtual_meters vm "
393
                       " WHERE va.meter_id = %s AND va.meter_type = 'meter' AND va.expression_id = ex.id "
394
                       "       AND ex.virtual_meter_id = vm.id ",
395
                       (id_,))
396
        row_virtual_meter = cursor.fetchone()
397
        if row_virtual_meter is not None:
398
            cursor.close()
399
            cnx.disconnect()
400
            raise falcon.HTTPError(falcon.HTTP_400,
401
                                   title='API.BAD_REQUEST',
402
                                   description='API.THIS_METER_IS_BEING_USED_BY_A_VIRTUAL_METER')
403
404
        # check relation with child meters
405
        cursor.execute(" SELECT id "
406
                       " FROM tbl_meters "
407
                       " WHERE parent_meter_id = %s ", (id_,))
408
        rows_child_meters = cursor.fetchall()
409
        if rows_child_meters is not None and len(rows_child_meters) > 0:
410
            cursor.close()
411
            cnx.disconnect()
412
            raise falcon.HTTPError(falcon.HTTP_400,
413
                                   title='API.BAD_REQUEST',
414
                                   description='API.THERE_IS_RELATION_WITH_CHILD_METERS')
415
416
        # check relation with spaces
417
        cursor.execute(" SELECT id "
418
                       " FROM tbl_spaces_meters "
419
                       " WHERE meter_id = %s ", (id_,))
420
        rows_spaces = cursor.fetchall()
421
        if rows_spaces is not None and len(rows_spaces) > 0:
422
            cursor.close()
423
            cnx.disconnect()
424
            raise falcon.HTTPError(falcon.HTTP_400,
425
                                   title='API.BAD_REQUEST',
426
                                   description='API.THERE_IS_RELATION_WITH_SPACES')
427
428
        # check relation with tenants
429
        cursor.execute(" SELECT tenant_id "
430
                       " FROM tbl_tenants_meters "
431
                       " WHERE meter_id = %s ", (id_,))
432
        rows_tenants = cursor.fetchall()
433
        if rows_tenants is not None and len(rows_tenants) > 0:
434
            cursor.close()
435
            cnx.disconnect()
436
            raise falcon.HTTPError(falcon.HTTP_400,
437
                                   title='API.BAD_REQUEST',
438
                                   description='API.THERE_IS_RELATION_WITH_TENANTS')
439
440
        # check relation with stores
441
        cursor.execute(" SELECT store_id "
442
                       " FROM tbl_stores_meters "
443
                       " WHERE meter_id = %s ", (id_,))
444
        rows_stores = cursor.fetchall()
445
        if rows_stores is not None and len(rows_stores) > 0:
446
            cursor.close()
447
            cnx.disconnect()
448
            raise falcon.HTTPError(falcon.HTTP_400,
449
                                   title='API.BAD_REQUEST',
450
                                   description='API.THERE_IS_RELATION_WITH_STORES')
451
452
        # check relation with shopfloors
453
        cursor.execute(" SELECT shopfloor_id "
454
                       " FROM tbl_shopfloors_meters "
455
                       " WHERE meter_id = %s ", (id_,))
456
        rows_shopfloors = cursor.fetchall()
457
        if rows_shopfloors is not None and len(rows_shopfloors) > 0:
458
            cursor.close()
459
            cnx.disconnect()
460
            raise falcon.HTTPError(falcon.HTTP_400,
461
                                   title='API.BAD_REQUEST',
462
                                   description='API.THERE_IS_RELATION_WITH_SHOPFLOORS')
463
464
        # check relation with combined equipments
465
        cursor.execute(" SELECT combined_equipment_id "
466
                       " FROM tbl_combined_equipments_meters "
467
                       " WHERE meter_id = %s ",
468
                       (id_,))
469
        rows_combined_equipments = cursor.fetchall()
470
        if rows_combined_equipments is not None and len(rows_combined_equipments) > 0:
471
            cursor.close()
472
            cnx.disconnect()
473
            raise falcon.HTTPError(falcon.HTTP_400,
474
                                   title='API.BAD_REQUEST',
475
                                   description='API.THERE_IS_RELATION_WITH_COMBINED_EQUIPMENTS')
476
477
        # check relation with combined equipment parameters
478
        cursor.execute(" SELECT combined_equipment_id "
479
                       " FROM tbl_combined_equipments_parameters "
480
                       " WHERE numerator_meter_uuid = %s OR denominator_meter_uuid = %s", (meter_uuid, meter_uuid,))
481
        rows_combined_equipments = cursor.fetchall()
482
        if rows_combined_equipments is not None and len(rows_combined_equipments) > 0:
483
            cursor.close()
484
            cnx.disconnect()
485
            raise falcon.HTTPError(falcon.HTTP_400,
486
                                   title='API.BAD_REQUEST',
487
                                   description='API.THERE_IS_RELATION_WITH_COMBINED_EQUIPMENT_PARAMETERS')
488
489
        # check relation with equipments
490
        cursor.execute(" SELECT equipment_id "
491
                       " FROM tbl_equipments_meters "
492
                       " WHERE meter_id = %s ", (id_,))
493
        rows_equipments = cursor.fetchall()
494
        if rows_equipments is not None and len(rows_equipments) > 0:
495
            cursor.close()
496
            cnx.disconnect()
497
            raise falcon.HTTPError(falcon.HTTP_400,
498
                                   title='API.BAD_REQUEST',
499
                                   description='API.THERE_IS_RELATION_WITH_EQUIPMENTS')
500
501
        # check relation with equipment parameters
502
        cursor.execute(" SELECT equipment_id "
503
                       " FROM tbl_equipments_parameters "
504
                       " WHERE numerator_meter_uuid = %s OR denominator_meter_uuid = %s", (meter_uuid, meter_uuid, ))
505
        rows_equipments = cursor.fetchall()
506
        if rows_equipments is not None and len(rows_equipments) > 0:
507
            cursor.close()
508
            cnx.disconnect()
509
            raise falcon.HTTPError(falcon.HTTP_400,
510
                                   title='API.BAD_REQUEST',
511
                                   description='API.THERE_IS_RELATION_WITH_EQUIPMENT_PARAMETERS')
512
513
        # check relation with points
514
        cursor.execute(" SELECT id "
515
                       " FROM tbl_meters_points "
516
                       " WHERE meter_id = %s ", (id_,))
517
        rows_equipments = cursor.fetchall()
518
        if rows_equipments is not None and len(rows_equipments) > 0:
519
            cursor.close()
520
            cnx.disconnect()
521
            raise falcon.HTTPError(falcon.HTTP_400,
522
                                   title='API.BAD_REQUEST',
523
                                   description='API.THERE_IS_RELATION_WITH_POINTS')
524
525
        # check relation with energy flow diagram links
526
        cursor.execute(" SELECT id "
527
                       " FROM tbl_energy_flow_diagrams_links "
528
                       " WHERE meter_uuid = %s ", (meter_uuid,))
529
        rows_links = cursor.fetchall()
530
        if rows_links is not None and len(rows_links) > 0:
531
            cursor.close()
532
            cnx.disconnect()
533
            raise falcon.HTTPError(falcon.HTTP_400,
534
                                   title='API.BAD_REQUEST',
535
                                   description='API.THERE_IS_RELATION_WITH_ENERGY_FLOW_DIAGRAM_LINKS')
536
537
        cursor.execute(" DELETE FROM tbl_meters WHERE id = %s ", (id_,))
538
        cnx.commit()
539
540
        cursor.close()
541
        cnx.disconnect()
542
543
        resp.status = falcon.HTTP_204
544
545
    @staticmethod
546
    def on_put(req, resp, id_):
547
        """Handles PUT requests"""
548
        try:
549
            raw_json = req.stream.read().decode('utf-8')
550
        except Exception as ex:
551
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
552
553
        if not id_.isdigit() or int(id_) <= 0:
554
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
555
                                   description='API.INVALID_METER_ID')
556
557
        new_values = json.loads(raw_json)
558
559
        if 'name' not in new_values['data'].keys() or \
560
                not isinstance(new_values['data']['name'], str) or \
561
                len(str.strip(new_values['data']['name'])) == 0:
562
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
563
                                   description='API.INVALID_METER_NAME')
564
        name = str.strip(new_values['data']['name'])
565
566
        if 'energy_category_id' not in new_values['data'].keys() or \
567
                not isinstance(new_values['data']['energy_category_id'], int) or \
568
                new_values['data']['energy_category_id'] <= 0:
569
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
570
                                   description='API.INVALID_ENERGY_CATEGORY_ID')
571
        energy_category_id = new_values['data']['energy_category_id']
572
573
        if 'is_counted' not in new_values['data'].keys() or \
574
                not isinstance(new_values['data']['is_counted'], bool):
575
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
576
                                   description='API.INVALID_IS_COUNTED_VALUE')
577
        is_counted = new_values['data']['is_counted']
578
579
        if 'hourly_low_limit' not in new_values['data'].keys() or \
580
                not (isinstance(new_values['data']['hourly_low_limit'], float) or
581
                     isinstance(new_values['data']['hourly_low_limit'], int)):
582
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
583
                                   description='API.INVALID_HOURLY_LOW_LIMIT_VALUE')
584
        hourly_low_limit = new_values['data']['hourly_low_limit']
585
586
        if 'hourly_high_limit' not in new_values['data'].keys() or \
587
                not (isinstance(new_values['data']['hourly_high_limit'], float) or
588
                     isinstance(new_values['data']['hourly_high_limit'], int)):
589
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
590
                                   description='API.INVALID_HOURLY_HIGH_LIMIT_VALUE')
591
        hourly_high_limit = new_values['data']['hourly_high_limit']
592
593
        if 'cost_center_id' not in new_values['data'].keys() or \
594
                not isinstance(new_values['data']['cost_center_id'], int) or \
595
                new_values['data']['cost_center_id'] <= 0:
596
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
597
                                       description='API.INVALID_COST_CENTER_ID')
598
599
        cost_center_id = new_values['data']['cost_center_id']
600
601
        if 'energy_item_id' in new_values['data'].keys() and \
602
                new_values['data']['energy_item_id'] is not None:
603
            if not isinstance(new_values['data']['energy_item_id'], int) or \
604
                    new_values['data']['energy_item_id'] <= 0:
605
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
606
                                       description='API.INVALID_ENERGY_ITEM_ID')
607
            energy_item_id = new_values['data']['energy_item_id']
608
        else:
609
            energy_item_id = None
610
611
        if 'parent_meter_id' in new_values['data'].keys():
612
            if not isinstance(new_values['data']['parent_meter_id'], int) or \
613
                    new_values['data']['parent_meter_id'] <= 0 or \
614
                    new_values['data']['parent_meter_id'] == int(id_):
615
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
616
                                       description='API.INVALID_PARENT_METER_ID')
617
            parent_meter_id = new_values['data']['parent_meter_id']
618
        else:
619
            parent_meter_id = None
620
621
        if 'description' in new_values['data'].keys() and \
622
                new_values['data']['description'] is not None and \
623
                len(str(new_values['data']['description'])) > 0:
624
            description = str.strip(new_values['data']['description'])
625
        else:
626
            description = None
627
628
        cnx = mysql.connector.connect(**config.myems_system_db)
629
        cursor = cnx.cursor()
630
631
        cursor.execute(" SELECT name "
632
                       " FROM tbl_meters "
633
                       " WHERE id = %s ", (id_,))
634
        if cursor.fetchone() is None:
635
            cursor.close()
636
            cnx.disconnect()
637
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
638
                                   description='API.METER_NOT_FOUND')
639
640
        cursor.execute(" SELECT name "
641
                       " FROM tbl_meters "
642
                       " WHERE name = %s AND id != %s ", (name, id_))
643
        if cursor.fetchone() is not None:
644
            cursor.close()
645
            cnx.disconnect()
646
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
647
                                   description='API.METER_NAME_IS_ALREADY_IN_USE')
648
649
        cursor.execute(" SELECT name "
650
                       " FROM tbl_energy_categories "
651
                       " WHERE id = %s ",
652
                       (new_values['data']['energy_category_id'],))
653
        if cursor.fetchone() is None:
654
            cursor.close()
655
            cnx.disconnect()
656
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
657
                                   description='API.ENERGY_CATEGORY_NOT_FOUND')
658
659
        cursor.execute(" SELECT name "
660
                       " FROM tbl_cost_centers "
661
                       " WHERE id = %s ",
662
                       (new_values['data']['cost_center_id'],))
663
        row = cursor.fetchone()
664
        if row is None:
665
            cursor.close()
666
            cnx.disconnect()
667
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
668
                                   description='API.COST_CENTER_NOT_FOUND')
669
670 View Code Duplication
        if energy_item_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
671
            cursor.execute(" SELECT name, energy_category_id "
672
                           " FROM tbl_energy_items "
673
                           " WHERE id = %s ",
674
                           (new_values['data']['energy_item_id'],))
675
            row = cursor.fetchone()
676
            if row is None:
677
                cursor.close()
678
                cnx.disconnect()
679
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
680
                                       description='API.ENERGY_ITEM_NOT_FOUND')
681
            else:
682
                if row[1] != energy_category_id:
683
                    cursor.close()
684
                    cnx.disconnect()
685
                    raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
686
                                           description='API.ENERGY_ITEM_DOES_NOT_BELONG_TO_ENERGY_CATEGORY')
687
688 View Code Duplication
        if parent_meter_id is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
689
            cursor.execute(" SELECT name, energy_category_id "
690
                           " FROM tbl_meters "
691
                           " WHERE id = %s ",
692
                           (new_values['data']['parent_meter_id'],))
693
            row = cursor.fetchone()
694
            if row is None:
695
                cursor.close()
696
                cnx.disconnect()
697
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
698
                                       description='API.PARENT_METER_NOT_FOUND')
699
            else:
700
                if row[1] != energy_category_id:
701
                    cursor.close()
702
                    cnx.disconnect()
703
                    raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
704
                                           description='API.PARENT_METER_DOES_NOT BELONG_TO_SAME_ENERGY_CATEGORY')
705
706
        if parent_meter_id is not None:
707
            cursor.execute(" SELECT name "
708
                           " FROM tbl_meters "
709
                           " WHERE id = %s AND parent_meter_id = %s ",
710
                           (new_values['data']['parent_meter_id'], id_))
711
            row = cursor.fetchone()
712
            if row is not None:
713
                cursor.close()
714
                cnx.disconnect()
715
                raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
716
                                       description='API.PARENT_METER_CAN_NOT_BE_CHILD_METER')
717
718
        update_row = (" UPDATE tbl_meters "
719
                      " SET name = %s, energy_category_id = %s, is_counted = %s, "
720
                      "     hourly_low_limit = %s, hourly_high_limit = %s, "
721
                      "     cost_center_id = %s, energy_item_id = %s, parent_meter_id = %s, description = %s "
722
                      " WHERE id = %s ")
723
        cursor.execute(update_row, (name,
724
                                    energy_category_id,
725
                                    is_counted,
726
                                    hourly_low_limit,
727
                                    hourly_high_limit,
728
                                    cost_center_id,
729
                                    energy_item_id,
730
                                    parent_meter_id,
731
                                    description,
732
                                    id_,))
733
        cnx.commit()
734
735
        cursor.close()
736
        cnx.disconnect()
737
738
        resp.status = falcon.HTTP_200
739
740
741
class MeterSubmeterCollection:
742
    @staticmethod
743
    def __init__():
744
        pass
745
746
    @staticmethod
747
    def on_options(req, resp, id_):
748
        resp.status = falcon.HTTP_200
749
750
    @staticmethod
751
    def on_get(req, resp, id_):
752
        if not id_.isdigit() or int(id_) <= 0:
753
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
754
                                   description='API.INVALID_METER_ID')
755
756
        cnx = mysql.connector.connect(**config.myems_system_db)
757
        cursor = cnx.cursor(dictionary=True)
758
759
        cursor.execute(" SELECT name, uuid "
760
                       " FROM tbl_meters "
761
                       " WHERE id = %s ", (id_,))
762
        row = cursor.fetchone()
763
        if row is None:
764
            cursor.close()
765
            cnx.disconnect()
766
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
767
                                   description='API.METER_NOT_FOUND')
768
        else:
769
            parent_meter = {"id": id_,
770
                            "name": row['name'],
771
                            "uuid": row['uuid']}
772
773
        query = (" SELECT id, name, uuid "
774
                 " FROM tbl_energy_categories ")
775
        cursor.execute(query)
776
        rows_energy_categories = cursor.fetchall()
777
778
        energy_category_dict = dict()
779
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
780
            for row in rows_energy_categories:
781
                energy_category_dict[row['id']] = {"id": row['id'],
782
                                                   "name": row['name'],
783
                                                   "uuid": row['uuid']}
784
785
        query = (" SELECT id, name, uuid "
786
                 " FROM tbl_cost_centers ")
787
        cursor.execute(query)
788
        rows_cost_centers = cursor.fetchall()
789
790
        cost_center_dict = dict()
791
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
792
            for row in rows_cost_centers:
793
                cost_center_dict[row['id']] = {"id": row['id'],
794
                                               "name": row['name'],
795
                                               "uuid": row['uuid']}
796
797
        query = (" SELECT id, name, uuid "
798
                 " FROM tbl_energy_items ")
799
        cursor.execute(query)
800
        rows_energy_items = cursor.fetchall()
801
802
        energy_item_dict = dict()
803
        if rows_energy_items is not None and len(rows_energy_items) > 0:
804
            for row in rows_energy_items:
805
                energy_item_dict[row['id']] = {"id": row['id'],
806
                                               "name": row['name'],
807
                                               "uuid": row['uuid']}
808
809
        query = (" SELECT id, name, uuid, energy_category_id, "
810
                 "        is_counted, hourly_low_limit, hourly_high_limit, "
811
                 "        cost_center_id, energy_item_id, parent_meter_id, description "
812
                 " FROM tbl_meters "
813
                 " WHERE parent_meter_id = %s "
814
                 " ORDER BY id ")
815
        cursor.execute(query, (id_, ))
816
        rows_meters = cursor.fetchall()
817
818
        result = list()
819 View Code Duplication
        if rows_meters is not None and len(rows_meters) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
820
            for row in rows_meters:
821
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
822
                cost_center = cost_center_dict.get(row['cost_center_id'], None)
823
                energy_item = energy_item_dict.get(row['energy_item_id'], None)
824
                meta_result = {"id": row['id'],
825
                               "name": row['name'],
826
                               "uuid": row['uuid'],
827
                               "energy_category": energy_category,
828
                               "is_counted": True if row['is_counted'] else False,
829
                               "hourly_low_limit": row['hourly_low_limit'],
830
                               "hourly_high_limit": row['hourly_high_limit'],
831
                               "cost_center": cost_center,
832
                               "energy_item": energy_item,
833
                               "parent_meter": parent_meter,
834
                               "description": row['description']}
835
                result.append(meta_result)
836
837
        cursor.close()
838
        cnx.disconnect()
839
        resp.body = json.dumps(result)
840
841
842 View Code Duplication
class MeterPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
843
    @staticmethod
844
    def __init__():
845
        pass
846
847
    @staticmethod
848
    def on_options(req, resp, id_):
849
        resp.status = falcon.HTTP_200
850
851
    @staticmethod
852
    def on_get(req, resp, id_):
853
        if not id_.isdigit() or int(id_) <= 0:
854
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
855
                                   description='API.INVALID_METER_ID')
856
857
        cnx = mysql.connector.connect(**config.myems_system_db)
858
        cursor = cnx.cursor()
859
860
        cursor.execute(" SELECT name "
861
                       " FROM tbl_meters "
862
                       " WHERE id = %s ", (id_,))
863
        if cursor.fetchone() is None:
864
            cursor.close()
865
            cnx.disconnect()
866
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
867
                                   description='API.METER_NOT_FOUND')
868
869
        query = (" SELECT p.id, p.name, "
870
                 "        ds.id, ds.name, ds.uuid, "
871
                 "        p.address "
872
                 " FROM tbl_points p, tbl_meters_points mp, tbl_data_sources ds "
873
                 " WHERE mp.meter_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
874
                 " ORDER BY p.name ")
875
        cursor.execute(query, (id_,))
876
        rows = cursor.fetchall()
877
878
        result = list()
879
        if rows is not None and len(rows) > 0:
880
            for row in rows:
881
                meta_result = {"id": row[0], "name": row[1],
882
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
883
                               "address": row[5]}
884
                result.append(meta_result)
885
886
        resp.body = json.dumps(result)
887
888
    @staticmethod
889
    def on_post(req, resp, id_):
890
        """Handles POST requests"""
891
        try:
892
            raw_json = req.stream.read().decode('utf-8')
893
        except Exception as ex:
894
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
895
896
        if not id_.isdigit() or int(id_) <= 0:
897
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
898
                                   description='API.INVALID_METER_ID')
899
900
        new_values = json.loads(raw_json)
901
902
        cnx = mysql.connector.connect(**config.myems_system_db)
903
        cursor = cnx.cursor()
904
905
        cursor.execute(" SELECT name "
906
                       " from tbl_meters "
907
                       " WHERE id = %s ", (id_,))
908
        if cursor.fetchone() is None:
909
            cursor.close()
910
            cnx.disconnect()
911
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
912
                                   description='API.METER_NOT_FOUND')
913
914
        cursor.execute(" SELECT name "
915
                       " FROM tbl_points "
916
                       " WHERE id = %s ", (new_values['data']['point_id'],))
917
        if cursor.fetchone() is None:
918
            cursor.close()
919
            cnx.disconnect()
920
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
921
                                   description='API.POINT_NOT_FOUND')
922
923
        query = (" SELECT id " 
924
                 " FROM tbl_meters_points "
925
                 " WHERE meter_id = %s AND point_id = %s")
926
        cursor.execute(query, (id_, new_values['data']['point_id'],))
927
        if cursor.fetchone() is not None:
928
            cursor.close()
929
            cnx.disconnect()
930
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
931
                                   description='API.METER_POINT_RELATION_EXISTED')
932
933
        add_row = (" INSERT INTO tbl_meters_points (meter_id, point_id) "
934
                   " VALUES (%s, %s) ")
935
        cursor.execute(add_row, (id_, new_values['data']['point_id'],))
936
        new_id = cursor.lastrowid
937
        cnx.commit()
938
        cursor.close()
939
        cnx.disconnect()
940
941
        resp.status = falcon.HTTP_201
942
        resp.location = '/meters/' + str(id_) + '/points/' + str(new_values['data']['point_id'])
943
944
945 View Code Duplication
class MeterPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
946
    @staticmethod
947
    def __init__():
948
        pass
949
950
    @staticmethod
951
    def on_options(req, resp, id_, pid):
952
            resp.status = falcon.HTTP_200
953
954
    @staticmethod
955
    def on_delete(req, resp, id_, pid):
956
        if not id_.isdigit() or int(id_) <= 0:
957
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
958
                                   description='API.INVALID_METER_ID')
959
960
        if not pid.isdigit() or int(pid) <= 0:
961
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
962
                                   description='API.INVALID_POINT_ID')
963
964
        cnx = mysql.connector.connect(**config.myems_system_db)
965
        cursor = cnx.cursor()
966
967
        cursor.execute(" SELECT name "
968
                       " FROM tbl_meters "
969
                       " WHERE id = %s ", (id_,))
970
        if cursor.fetchone() is None:
971
            cursor.close()
972
            cnx.disconnect()
973
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
974
                                   description='API.METER_NOT_FOUND')
975
976
        cursor.execute(" SELECT name "
977
                       " FROM tbl_points "
978
                       " WHERE id = %s ", (pid,))
979
        if cursor.fetchone() is None:
980
            cursor.close()
981
            cnx.disconnect()
982
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
983
                                   description='API.POINT_NOT_FOUND')
984
985
        cursor.execute(" SELECT id "
986
                       " FROM tbl_meters_points "
987
                       " WHERE meter_id = %s AND point_id = %s ", (id_, pid))
988
        if cursor.fetchone() is None:
989
            cursor.close()
990
            cnx.disconnect()
991
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
992
                                   description='API.METER_POINT_RELATION_NOT_FOUND')
993
994
        cursor.execute(" DELETE FROM tbl_meters_points WHERE meter_id = %s AND point_id = %s ", (id_, pid))
995
        cnx.commit()
996
997
        cursor.close()
998
        cnx.disconnect()
999
1000
        resp.status = falcon.HTTP_204
1001
1002