core.store.StoreCollection.__init__()   A
last analyzed

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 StoreCollection:
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_store_types ")
24
        cursor.execute(query)
25
        rows_store_types = cursor.fetchall()
26
27
        store_type_dict = dict()
28
        if rows_store_types is not None and len(rows_store_types) > 0:
29
            for row in rows_store_types:
30
                store_type_dict[row['id']] = {"id": row['id'],
31
                                              "name": row['name'],
32
                                              "uuid": row['uuid']}
33
34
        query = (" SELECT id, name, uuid "
35
                 " FROM tbl_contacts ")
36
        cursor.execute(query)
37
        rows_contacts = cursor.fetchall()
38
39
        contact_dict = dict()
40
        if rows_contacts is not None and len(rows_contacts) > 0:
41
            for row in rows_contacts:
42
                contact_dict[row['id']] = {"id": row['id'],
43
                                           "name": row['name'],
44
                                           "uuid": row['uuid']}
45
46
        query = (" SELECT id, name, uuid "
47
                 " FROM tbl_cost_centers ")
48
        cursor.execute(query)
49
        rows_cost_centers = cursor.fetchall()
50
51
        cost_center_dict = dict()
52
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
53
            for row in rows_cost_centers:
54
                cost_center_dict[row['id']] = {"id": row['id'],
55
                                               "name": row['name'],
56
                                               "uuid": row['uuid']}
57
58
        query = (" SELECT id, name, uuid, "
59
                 "        address, latitude, longitude, area, store_type_id, "
60
                 "        is_input_counted, contact_id, cost_center_id, description "
61
                 " FROM tbl_stores "
62
                 " ORDER BY id ")
63
        cursor.execute(query)
64
        rows_spaces = cursor.fetchall()
65
66
        result = list()
67
        if rows_spaces is not None and len(rows_spaces) > 0:
68
            for row in rows_spaces:
69
                store_type = store_type_dict.get(row['store_type_id'], None)
70
                contact = contact_dict.get(row['contact_id'], None)
71
                cost_center = cost_center_dict.get(row['cost_center_id'], None)
72
73
                meta_result = {"id": row['id'],
74
                               "name": row['name'],
75
                               "uuid": row['uuid'],
76
                               "address": row['address'],
77
                               "latitude": row['latitude'],
78
                               "longitude": row['longitude'],
79
                               "area": row['area'],
80
                               "store_type": store_type,
81
                               "is_input_counted": bool(row['is_input_counted']),
82
                               "contact": contact,
83
                               "cost_center": cost_center,
84
                               "description": row['description']}
85
                result.append(meta_result)
86
87
        cursor.close()
88
        cnx.disconnect()
89
        resp.body = json.dumps(result)
90
91
    @staticmethod
92
    def on_post(req, resp):
93
        """Handles POST requests"""
94
        try:
95
            raw_json = req.stream.read().decode('utf-8')
96
        except Exception as ex:
97
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex)
98
99
        new_values = json.loads(raw_json)
100
101
        if 'name' not in new_values['data'].keys() or \
102
                not isinstance(new_values['data']['name'], str) or \
103
                len(str.strip(new_values['data']['name'])) == 0:
104
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
105
                                   description='API.INVALID_STORE_NAME')
106
        name = str.strip(new_values['data']['name'])
107
108
        if 'address' not in new_values['data'].keys() or \
109
                not isinstance(new_values['data']['address'], str) or \
110
                len(str.strip(new_values['data']['address'])) == 0:
111
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
112
                                   description='API.INVALID_ADDRESS_VALUE')
113
        address = str.strip(new_values['data']['address'])
114
115
        if 'latitude' not in new_values['data'].keys() or \
116
                not (isinstance(new_values['data']['latitude'], float) or
117
                     isinstance(new_values['data']['latitude'], int)):
118
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
119
                                   description='API.INVALID_LATITUDE_VALUE')
120
        latitude = new_values['data']['latitude']
121
122
        if 'longitude' not in new_values['data'].keys() or \
123
                not (isinstance(new_values['data']['longitude'], float) or
124
                     isinstance(new_values['data']['longitude'], int)):
125
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
126
                                   description='API.INVALID_LONGITUDE_VALUE')
127
        longitude = new_values['data']['longitude']
128
129
        if 'area' not in new_values['data'].keys() or \
130
                not (isinstance(new_values['data']['area'], float) or
131
                     isinstance(new_values['data']['area'], int)):
132
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
133
                                   description='API.INVALID_AREA_VALUE')
134
        area = new_values['data']['area']
135
136
        if 'store_type_id' not in new_values['data'].keys() or \
137
                not isinstance(new_values['data']['store_type_id'], int) or \
138
                new_values['data']['store_type_id'] <= 0:
139
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
140
                                   description='API.INVALID_STORE_TYPE_ID')
141
        store_type_id = new_values['data']['store_type_id']
142
143
        if 'is_input_counted' not in new_values['data'].keys() or \
144
                not isinstance(new_values['data']['is_input_counted'], bool):
145
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
146
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
147
        is_input_counted = new_values['data']['is_input_counted']
148
149
        if 'contact_id' not in new_values['data'].keys() or \
150
                not isinstance(new_values['data']['contact_id'], int) or \
151
                new_values['data']['contact_id'] <= 0:
152
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
153
                                       description='API.INVALID_CONTACT_ID')
154
        contact_id = new_values['data']['contact_id']
155
156
        if 'cost_center_id' not in new_values['data'].keys() or \
157
                not isinstance(new_values['data']['cost_center_id'], int) or \
158
                new_values['data']['cost_center_id'] <= 0:
159
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
160
                                       description='API.INVALID_COST_CENTER_ID')
161
        cost_center_id = new_values['data']['cost_center_id']
162
163
        if 'description' in new_values['data'].keys() and \
164
                new_values['data']['description'] is not None and \
165
                len(str(new_values['data']['description'])) > 0:
166
            description = str.strip(new_values['data']['description'])
167
        else:
168
            description = None
169
170
        cnx = mysql.connector.connect(**config.myems_system_db)
171
        cursor = cnx.cursor()
172
173
        cursor.execute(" SELECT name "
174
                       " FROM tbl_stores "
175
                       " WHERE name = %s ", (name,))
176
        if cursor.fetchone() is not None:
177
            cursor.close()
178
            cnx.disconnect()
179
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
180
                                   description='API.STORE_NAME_IS_ALREADY_IN_USE')
181
182
        cursor.execute(" SELECT name "
183
                       " FROM tbl_store_types "
184
                       " WHERE id = %s ",
185
                       (store_type_id,))
186
        if cursor.fetchone() is None:
187
            cursor.close()
188
            cnx.disconnect()
189
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
190
                                   description='API.STORE_TYPE_NOT_FOUND')
191
192
        cursor.execute(" SELECT name "
193
                       " FROM tbl_contacts "
194
                       " WHERE id = %s ",
195
                       (new_values['data']['contact_id'],))
196
        row = cursor.fetchone()
197
        if row is None:
198
            cursor.close()
199
            cnx.disconnect()
200
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
201
                                   description='API.CONTACT_NOT_FOUND')
202
203
        cursor.execute(" SELECT name "
204
                       " FROM tbl_cost_centers "
205
                       " WHERE id = %s ",
206
                       (new_values['data']['cost_center_id'],))
207
        row = cursor.fetchone()
208
        if row is None:
209
            cursor.close()
210
            cnx.disconnect()
211
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
212
                                   description='API.COST_CENTER_NOT_FOUND')
213
214
        add_values = (" INSERT INTO tbl_stores "
215
                      "    (name, uuid, address, latitude, longitude, area, store_type_id, "
216
                      "     is_input_counted, "
217
                      "     contact_id, cost_center_id, description) "
218
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
219
        cursor.execute(add_values, (name,
220
                                    str(uuid.uuid4()),
221
                                    address,
222
                                    latitude,
223
                                    longitude,
224
                                    area,
225
                                    store_type_id,
226
                                    is_input_counted,
227
                                    contact_id,
228
                                    cost_center_id,
229
                                    description))
230
        new_id = cursor.lastrowid
231
        cnx.commit()
232
        cursor.close()
233
        cnx.disconnect()
234
235
        resp.status = falcon.HTTP_201
236
        resp.location = '/stores/' + str(new_id)
237
238
239
class StoreItem:
240
    @staticmethod
241
    def __init__():
242
        pass
243
244
    @staticmethod
245
    def on_options(req, resp, id_):
246
        resp.status = falcon.HTTP_200
247
248
    @staticmethod
249
    def on_get(req, resp, id_):
250
        if not id_.isdigit() or int(id_) <= 0:
251
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
252
                                   description='API.INVALID_STORE_ID')
253
254
        cnx = mysql.connector.connect(**config.myems_system_db)
255
        cursor = cnx.cursor(dictionary=True)
256
257
        query = (" SELECT id, name, uuid "
258
                 " FROM tbl_store_types ")
259
        cursor.execute(query)
260
        rows_store_types = cursor.fetchall()
261
262
        store_type_dict = dict()
263
        if rows_store_types is not None and len(rows_store_types) > 0:
264
            for row in rows_store_types:
265
                store_type_dict[row['id']] = {"id": row['id'],
266
                                              "name": row['name'],
267
                                              "uuid": row['uuid']}
268
269
        query = (" SELECT id, name, uuid "
270
                 " FROM tbl_contacts ")
271
        cursor.execute(query)
272
        rows_contacts = cursor.fetchall()
273
274
        contact_dict = dict()
275
        if rows_contacts is not None and len(rows_contacts) > 0:
276
            for row in rows_contacts:
277
                contact_dict[row['id']] = {"id": row['id'],
278
                                           "name": row['name'],
279
                                           "uuid": row['uuid']}
280
281
        query = (" SELECT id, name, uuid "
282
                 " FROM tbl_cost_centers ")
283
        cursor.execute(query)
284
        rows_cost_centers = cursor.fetchall()
285
286
        cost_center_dict = dict()
287
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
288
            for row in rows_cost_centers:
289
                cost_center_dict[row['id']] = {"id": row['id'],
290
                                               "name": row['name'],
291
                                               "uuid": row['uuid']}
292
293
        query = (" SELECT id, name, uuid, "
294
                 "        address, latitude, longitude, area, store_type_id,"
295
                 "        is_input_counted, "
296
                 "        contact_id, cost_center_id, description "
297
                 " FROM tbl_stores "
298
                 " WHERE id = %s ")
299
        cursor.execute(query, (id_,))
300
        row = cursor.fetchone()
301
        cursor.close()
302
        cnx.disconnect()
303
304
        if row is None:
305
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
306
                                   description='API.STORE_NOT_FOUND')
307
        else:
308
            store_type = store_type_dict.get(row['store_type_id'], None)
309
            contact = contact_dict.get(row['contact_id'], None)
310
            cost_center = cost_center_dict.get(row['cost_center_id'], None)
311
            meta_result = {"id": row['id'],
312
                           "name": row['name'],
313
                           "uuid": row['uuid'],
314
                           "address": row['address'],
315
                           "latitude": row['latitude'],
316
                           "longitude": row['longitude'],
317
                           "area": row['area'],
318
                           "store_type": store_type,
319
                           "is_input_counted": bool(row['is_input_counted']),
320
                           "contact": contact,
321
                           "cost_center": cost_center,
322
                           "description": row['description']}
323
324
        resp.body = json.dumps(meta_result)
325
326 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
327
    def on_delete(req, resp, id_):
328
        if not id_.isdigit() or int(id_) <= 0:
329
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
330
                                   description='API.INVALID_STORE_ID')
331
332
        cnx = mysql.connector.connect(**config.myems_system_db)
333
        cursor = cnx.cursor()
334
335
        cursor.execute(" SELECT name "
336
                       " FROM tbl_stores "
337
                       " WHERE id = %s ", (id_,))
338
        if cursor.fetchone() is None:
339
            cursor.close()
340
            cnx.disconnect()
341
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
342
                                   description='API.STORE_NOT_FOUND')
343
344
        # check relation with space
345
        cursor.execute(" SELECT space_id "
346
                       " FROM tbl_spaces_stores "
347
                       " WHERE store_id = %s ",
348
                       (id_,))
349
        rows_spaces = cursor.fetchall()
350
        if rows_spaces is not None and len(rows_spaces) > 0:
351
            cursor.close()
352
            cnx.disconnect()
353
            raise falcon.HTTPError(falcon.HTTP_400,
354
                                   title='API.BAD_REQUEST',
355
                                   description='API.THERE_IS_RELATION_WITH_SPACES')
356
357
        # check relation with meter
358
        cursor.execute(" SELECT meter_id "
359
                       " FROM tbl_stores_meters "
360
                       " WHERE store_id = %s ",
361
                       (id_,))
362
        rows_meters = cursor.fetchall()
363
        if rows_meters is not None and len(rows_meters) > 0:
364
            cursor.close()
365
            cnx.disconnect()
366
            raise falcon.HTTPError(falcon.HTTP_400,
367
                                   title='API.BAD_REQUEST',
368
                                   description='API.THERE_IS_RELATION_WITH_METERS')
369
370
        # check relation with offline meter
371
        cursor.execute(" SELECT offline_meter_id "
372
                       " FROM tbl_stores_offline_meters "
373
                       " WHERE store_id = %s ",
374
                       (id_,))
375
        rows_offline_meters = cursor.fetchall()
376
        if rows_offline_meters is not None and len(rows_offline_meters) > 0:
377
            cursor.close()
378
            cnx.disconnect()
379
            raise falcon.HTTPError(falcon.HTTP_400,
380
                                   title='API.BAD_REQUEST',
381
                                   description='API.THERE_IS_RELATION_WITH_OFFLINE_METERS')
382
383
        # check relation with points
384
        cursor.execute(" SELECT point_id "
385
                       " FROM tbl_stores_points "
386
                       " WHERE store_id = %s ", (id_,))
387
        rows_points = cursor.fetchall()
388
        if rows_points is not None and len(rows_points) > 0:
389
            cursor.close()
390
            cnx.disconnect()
391
            raise falcon.HTTPError(falcon.HTTP_400,
392
                                   title='API.BAD_REQUEST',
393
                                   description='API.THERE_IS_RELATION_WITH_POINTS')
394
395
        # check relation with sensor
396
        cursor.execute(" SELECT sensor_id "
397
                       " FROM tbl_stores_sensors "
398
                       " WHERE store_id = %s ",
399
                       (id_,))
400
        rows_sensors = cursor.fetchall()
401
        if rows_sensors is not None and len(rows_sensors) > 0:
402
            cursor.close()
403
            cnx.disconnect()
404
            raise falcon.HTTPError(falcon.HTTP_400,
405
                                   title='API.BAD_REQUEST',
406
                                   description='API.THERE_IS_RELATION_WITH_SENSORS')
407
408
        # check relation with virtual meter
409
        cursor.execute(" SELECT virtual_meter_id "
410
                       " FROM tbl_stores_virtual_meters "
411
                       " WHERE store_id = %s ",
412
                       (id_,))
413
        rows_virtual_meters = cursor.fetchall()
414
        if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
415
            cursor.close()
416
            cnx.disconnect()
417
            raise falcon.HTTPError(falcon.HTTP_400,
418
                                   title='API.BAD_REQUEST',
419
                                   description='API.THERE_IS_RELATION_WITH_VIRTUAL_METERS')
420
421
        cursor.execute(" DELETE FROM tbl_stores WHERE id = %s ", (id_,))
422
        cnx.commit()
423
424
        cursor.close()
425
        cnx.disconnect()
426
427
        resp.status = falcon.HTTP_204
428
429
    @staticmethod
430
    def on_put(req, resp, id_):
431
        """Handles PUT requests"""
432
        try:
433
            raw_json = req.stream.read().decode('utf-8')
434
        except Exception as ex:
435
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
436
437
        if not id_.isdigit() or int(id_) <= 0:
438
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
439
                                   description='API.INVALID_STORE_ID')
440
441
        new_values = json.loads(raw_json)
442
443
        if 'name' not in new_values['data'].keys() or \
444
                not isinstance(new_values['data']['name'], str) or \
445
                len(str.strip(new_values['data']['name'])) == 0:
446
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
447
                                   description='API.INVALID_STORE_NAME')
448
        name = str.strip(new_values['data']['name'])
449
450
        if 'address' not in new_values['data'].keys() or \
451
                not isinstance(new_values['data']['address'], str) or \
452
                len(str.strip(new_values['data']['address'])) == 0:
453
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
454
                                   description='API.INVALID_ADDRESS_VALUE')
455
        address = str.strip(new_values['data']['address'])
456
457
        if 'latitude' not in new_values['data'].keys() or \
458
                not (isinstance(new_values['data']['latitude'], float) or
459
                     isinstance(new_values['data']['latitude'], int)):
460
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
461
                                   description='API.INVALID_LATITUDE_VALUE')
462
        latitude = new_values['data']['area']
463
464
        if 'longitude' not in new_values['data'].keys() or \
465
                not (isinstance(new_values['data']['longitude'], float) or
466
                     isinstance(new_values['data']['longitude'], int)):
467
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
468
                                   description='API.INVALID_LONGITUDE_VALUE')
469
        longitude = new_values['data']['longitude']
470
471
        if 'area' not in new_values['data'].keys() or \
472
                not (isinstance(new_values['data']['area'], float) or
473
                     isinstance(new_values['data']['area'], int)):
474
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
475
                                   description='API.INVALID_AREA_VALUE')
476
        area = new_values['data']['area']
477
478
        if 'store_type_id' not in new_values['data'].keys() or \
479
                not isinstance(new_values['data']['store_type_id'], int) or \
480
                new_values['data']['store_type_id'] <= 0:
481
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
482
                                   description='API.INVALID_STORE_TYPE_ID')
483
        store_type_id = new_values['data']['store_type_id']
484
485
        if 'is_input_counted' not in new_values['data'].keys() or \
486
                not isinstance(new_values['data']['is_input_counted'], bool):
487
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
488
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
489
        is_input_counted = new_values['data']['is_input_counted']
490
491
        if 'contact_id' not in new_values['data'].keys() or \
492
                not isinstance(new_values['data']['contact_id'], int) or \
493
                new_values['data']['contact_id'] <= 0:
494
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
495
                                   description='API.INVALID_CONTACT_ID')
496
        contact_id = new_values['data']['contact_id']
497
498
        if 'cost_center_id' not in new_values['data'].keys() or \
499
                not isinstance(new_values['data']['cost_center_id'], int) or \
500
                new_values['data']['cost_center_id'] <= 0:
501
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
502
                                   description='API.INVALID_COST_CENTER_ID')
503
        cost_center_id = new_values['data']['cost_center_id']
504
505
        if 'description' in new_values['data'].keys() and \
506
                new_values['data']['description'] is not None and \
507
                len(str(new_values['data']['description'])) > 0:
508
            description = str.strip(new_values['data']['description'])
509
        else:
510
            description = None
511
512
        cnx = mysql.connector.connect(**config.myems_system_db)
513
        cursor = cnx.cursor()
514
515
        cursor.execute(" SELECT name "
516
                       " FROM tbl_stores "
517
                       " WHERE id = %s ", (id_,))
518
        if cursor.fetchone() is None:
519
            cursor.close()
520
            cnx.disconnect()
521
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
522
                                   description='API.STORE_NOT_FOUND')
523
524
        cursor.execute(" SELECT name "
525
                       " FROM tbl_stores "
526
                       " WHERE name = %s AND id != %s ", (name, id_))
527
        if cursor.fetchone() is not None:
528
            cursor.close()
529
            cnx.disconnect()
530
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
531
                                   description='API.STORE_NAME_IS_ALREADY_IN_USE')
532
533
        cursor.execute(" SELECT name "
534
                       " FROM tbl_store_types "
535
                       " WHERE id = %s ",
536
                       (store_type_id,))
537
        if cursor.fetchone() is None:
538
            cursor.close()
539
            cnx.disconnect()
540
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
541
                                   description='API.STORE_TYPE_NOT_FOUND')
542
543
        cursor.execute(" SELECT name "
544
                       " FROM tbl_contacts "
545
                       " WHERE id = %s ",
546
                       (new_values['data']['contact_id'],))
547
        row = cursor.fetchone()
548
        if row is None:
549
            cursor.close()
550
            cnx.disconnect()
551
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
552
                                   description='API.CONTACT_NOT_FOUND')
553
554
        cursor.execute(" SELECT name "
555
                       " FROM tbl_cost_centers "
556
                       " WHERE id = %s ",
557
                       (new_values['data']['cost_center_id'],))
558
        row = cursor.fetchone()
559
        if row is None:
560
            cursor.close()
561
            cnx.disconnect()
562
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
563
                                   description='API.COST_CENTER_NOT_FOUND')
564
565
        update_row = (" UPDATE tbl_stores "
566
                      " SET name = %s, address = %s, latitude = %s, longitude = %s, area = %s, "
567
                      "     store_type_id = %s, is_input_counted = %s, "
568
                      "     contact_id = %s, cost_center_id = %s, "
569
                      "     description = %s "
570
                      " WHERE id = %s ")
571
        cursor.execute(update_row, (name,
572
                                    address,
573
                                    latitude,
574
                                    longitude,
575
                                    area,
576
                                    store_type_id,
577
                                    is_input_counted,
578
                                    contact_id,
579
                                    cost_center_id,
580
                                    description,
581
                                    id_))
582
        cnx.commit()
583
584
        cursor.close()
585
        cnx.disconnect()
586
587
        resp.status = falcon.HTTP_200
588
589
590 View Code Duplication
class StoreMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
591
    @staticmethod
592
    def __init__():
593
        pass
594
595
    @staticmethod
596
    def on_options(req, resp, id_):
597
        resp.status = falcon.HTTP_200
598
599
    @staticmethod
600
    def on_get(req, resp, id_):
601
        if not id_.isdigit() or int(id_) <= 0:
602
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
603
                                   description='API.INVALID_STORE_ID')
604
605
        cnx = mysql.connector.connect(**config.myems_system_db)
606
        cursor = cnx.cursor(dictionary=True)
607
608
        cursor.execute(" SELECT name "
609
                       " FROM tbl_stores "
610
                       " WHERE id = %s ", (id_,))
611
        if cursor.fetchone() is None:
612
            cursor.close()
613
            cnx.disconnect()
614
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
615
                                   description='API.STORE_NOT_FOUND')
616
617
        query = (" SELECT id, name, uuid "
618
                 " FROM tbl_energy_categories ")
619
        cursor.execute(query)
620
        rows_energy_categories = cursor.fetchall()
621
622
        energy_category_dict = dict()
623
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
624
            for row in rows_energy_categories:
625
                energy_category_dict[row['id']] = {"id": row['id'],
626
                                                   "name": row['name'],
627
                                                   "uuid": row['uuid']}
628
629
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
630
                 " FROM tbl_stores t, tbl_stores_meters tm, tbl_meters m "
631
                 " WHERE tm.store_id = t.id AND m.id = tm.meter_id AND t.id = %s "
632
                 " ORDER BY m.id ")
633
        cursor.execute(query, (id_,))
634
        rows = cursor.fetchall()
635
636
        result = list()
637
        if rows is not None and len(rows) > 0:
638
            for row in rows:
639
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
640
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
641
                               "energy_category": energy_category}
642
                result.append(meta_result)
643
644
        resp.body = json.dumps(result)
645
646
    @staticmethod
647
    def on_post(req, resp, id_):
648
        """Handles POST requests"""
649
        try:
650
            raw_json = req.stream.read().decode('utf-8')
651
        except Exception as ex:
652
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
653
654
        if not id_.isdigit() or int(id_) <= 0:
655
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
656
                                   description='API.INVALID_STORE_ID')
657
658
        new_values = json.loads(raw_json)
659
660
        if 'meter_id' not in new_values['data'].keys() or \
661
                not isinstance(new_values['data']['meter_id'], int) or \
662
                new_values['data']['meter_id'] <= 0:
663
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
664
                                   description='API.INVALID_METER_ID')
665
        meter_id = new_values['data']['meter_id']
666
667
        cnx = mysql.connector.connect(**config.myems_system_db)
668
        cursor = cnx.cursor()
669
670
        cursor.execute(" SELECT name "
671
                       " from tbl_stores "
672
                       " WHERE id = %s ", (id_,))
673
        if cursor.fetchone() is None:
674
            cursor.close()
675
            cnx.disconnect()
676
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
677
                                   description='API.STORE_NOT_FOUND')
678
679
        cursor.execute(" SELECT name "
680
                       " FROM tbl_meters "
681
                       " WHERE id = %s ", (meter_id,))
682
        if cursor.fetchone() is None:
683
            cursor.close()
684
            cnx.disconnect()
685
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
686
                                   description='API.METER_NOT_FOUND')
687
688
        query = (" SELECT id " 
689
                 " FROM tbl_stores_meters "
690
                 " WHERE store_id = %s AND meter_id = %s")
691
        cursor.execute(query, (id_, meter_id,))
692
        if cursor.fetchone() is not None:
693
            cursor.close()
694
            cnx.disconnect()
695
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
696
                                   description='API.STORE_METER_RELATION_EXISTED')
697
698
        add_row = (" INSERT INTO tbl_stores_meters (store_id, meter_id) "
699
                   " VALUES (%s, %s) ")
700
        cursor.execute(add_row, (id_, meter_id,))
701
        new_id = cursor.lastrowid
702
        cnx.commit()
703
        cursor.close()
704
        cnx.disconnect()
705
706
        resp.status = falcon.HTTP_201
707
        resp.location = '/stores/' + str(id_) + '/meters/' + str(meter_id)
708
709
710 View Code Duplication
class StoreMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
711
    @staticmethod
712
    def __init__():
713
        pass
714
715
    @staticmethod
716
    def on_options(req, resp, id_, mid):
717
            resp.status = falcon.HTTP_200
718
719
    @staticmethod
720
    def on_delete(req, resp, id_, mid):
721
        if not id_.isdigit() or int(id_) <= 0:
722
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
723
                                   description='API.INVALID_STORE_ID')
724
725
        if not mid.isdigit() or int(mid) <= 0:
726
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
727
                                   description='API.INVALID_METER_ID')
728
729
        cnx = mysql.connector.connect(**config.myems_system_db)
730
        cursor = cnx.cursor()
731
732
        cursor.execute(" SELECT name "
733
                       " FROM tbl_stores "
734
                       " WHERE id = %s ", (id_,))
735
        if cursor.fetchone() is None:
736
            cursor.close()
737
            cnx.disconnect()
738
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
739
                                   description='API.STORE_NOT_FOUND')
740
741
        cursor.execute(" SELECT name "
742
                       " FROM tbl_meters "
743
                       " WHERE id = %s ", (mid,))
744
        if cursor.fetchone() is None:
745
            cursor.close()
746
            cnx.disconnect()
747
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
748
                                   description='API.METER_NOT_FOUND')
749
750
        cursor.execute(" SELECT id "
751
                       " FROM tbl_stores_meters "
752
                       " WHERE store_id = %s AND meter_id = %s ", (id_, mid))
753
        if cursor.fetchone() is None:
754
            cursor.close()
755
            cnx.disconnect()
756
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
757
                                   description='API.STORE_METER_RELATION_NOT_FOUND')
758
759
        cursor.execute(" DELETE FROM tbl_stores_meters WHERE store_id = %s AND meter_id = %s ", (id_, mid))
760
        cnx.commit()
761
762
        cursor.close()
763
        cnx.disconnect()
764
765
        resp.status = falcon.HTTP_204
766
767
768 View Code Duplication
class StoreOfflineMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
769
    @staticmethod
770
    def __init__():
771
        pass
772
773
    @staticmethod
774
    def on_options(req, resp, id_):
775
        resp.status = falcon.HTTP_200
776
777
    @staticmethod
778
    def on_get(req, resp, id_):
779
        if not id_.isdigit() or int(id_) <= 0:
780
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
781
                                   description='API.INVALID_STORE_ID')
782
783
        cnx = mysql.connector.connect(**config.myems_system_db)
784
        cursor = cnx.cursor(dictionary=True)
785
786
        cursor.execute(" SELECT name "
787
                       " FROM tbl_stores "
788
                       " WHERE id = %s ", (id_,))
789
        if cursor.fetchone() is None:
790
            cursor.close()
791
            cnx.disconnect()
792
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
793
                                   description='API.STORE_NOT_FOUND')
794
795
        query = (" SELECT id, name, uuid "
796
                 " FROM tbl_energy_categories ")
797
        cursor.execute(query)
798
        rows_energy_categories = cursor.fetchall()
799
800
        energy_category_dict = dict()
801
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
802
            for row in rows_energy_categories:
803
                energy_category_dict[row['id']] = {"id": row['id'],
804
                                                   "name": row['name'],
805
                                                   "uuid": row['uuid']}
806
807
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
808
                 " FROM tbl_stores s, tbl_stores_offline_meters sm, tbl_offline_meters m "
809
                 " WHERE sm.store_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
810
                 " ORDER BY m.id ")
811
        cursor.execute(query, (id_,))
812
        rows = cursor.fetchall()
813
814
        result = list()
815
        if rows is not None and len(rows) > 0:
816
            for row in rows:
817
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
818
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
819
                               "energy_category": energy_category}
820
                result.append(meta_result)
821
822
        resp.body = json.dumps(result)
823
824
    @staticmethod
825
    def on_post(req, resp, id_):
826
        """Handles POST requests"""
827
        try:
828
            raw_json = req.stream.read().decode('utf-8')
829
        except Exception as ex:
830
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
831
832
        if not id_.isdigit() or int(id_) <= 0:
833
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
834
                                   description='API.INVALID_STORE_ID')
835
836
        new_values = json.loads(raw_json)
837
838
        if 'offline_meter_id' not in new_values['data'].keys() or \
839
                not isinstance(new_values['data']['offline_meter_id'], int) or \
840
                new_values['data']['offline_meter_id'] <= 0:
841
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
842
                                   description='API.INVALID_OFFLINE_METER_ID')
843
        offline_meter_id = new_values['data']['offline_meter_id']
844
845
        cnx = mysql.connector.connect(**config.myems_system_db)
846
        cursor = cnx.cursor()
847
848
        cursor.execute(" SELECT name "
849
                       " from tbl_stores "
850
                       " WHERE id = %s ", (id_,))
851
        if cursor.fetchone() is None:
852
            cursor.close()
853
            cnx.disconnect()
854
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
855
                                   description='API.STORE_NOT_FOUND')
856
857
        cursor.execute(" SELECT name "
858
                       " FROM tbl_offline_meters "
859
                       " WHERE id = %s ", (offline_meter_id,))
860
        if cursor.fetchone() is None:
861
            cursor.close()
862
            cnx.disconnect()
863
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
864
                                   description='API.OFFLINE_METER_NOT_FOUND')
865
866
        query = (" SELECT id " 
867
                 " FROM tbl_stores_offline_meters "
868
                 " WHERE store_id = %s AND offline_meter_id = %s")
869
        cursor.execute(query, (id_, offline_meter_id,))
870
        if cursor.fetchone() is not None:
871
            cursor.close()
872
            cnx.disconnect()
873
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
874
                                   description='API.STORE_OFFLINE_METER_RELATION_EXISTED')
875
876
        add_row = (" INSERT INTO tbl_stores_offline_meters (store_id, offline_meter_id) "
877
                   " VALUES (%s, %s) ")
878
        cursor.execute(add_row, (id_, offline_meter_id,))
879
        new_id = cursor.lastrowid
880
        cnx.commit()
881
        cursor.close()
882
        cnx.disconnect()
883
884
        resp.status = falcon.HTTP_201
885
        resp.location = '/stores/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
886
887
888 View Code Duplication
class StoreOfflineMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
889
    @staticmethod
890
    def __init__():
891
        pass
892
893
    @staticmethod
894
    def on_options(req, resp, id_, mid):
895
            resp.status = falcon.HTTP_200
896
897
    @staticmethod
898
    def on_delete(req, resp, id_, mid):
899
        if not id_.isdigit() or int(id_) <= 0:
900
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
901
                                   description='API.INVALID_STORE_ID')
902
903
        if not mid.isdigit() or int(mid) <= 0:
904
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
905
                                   description='API.INVALID_OFFLINE_METER_ID')
906
907
        cnx = mysql.connector.connect(**config.myems_system_db)
908
        cursor = cnx.cursor()
909
910
        cursor.execute(" SELECT name "
911
                       " FROM tbl_stores "
912
                       " WHERE id = %s ", (id_,))
913
        if cursor.fetchone() is None:
914
            cursor.close()
915
            cnx.disconnect()
916
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
917
                                   description='API.STORE_NOT_FOUND')
918
919
        cursor.execute(" SELECT name "
920
                       " FROM tbl_offline_meters "
921
                       " WHERE id = %s ", (mid,))
922
        if cursor.fetchone() is None:
923
            cursor.close()
924
            cnx.disconnect()
925
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
926
                                   description='API.OFFLINE_METER_NOT_FOUND')
927
928
        cursor.execute(" SELECT id "
929
                       " FROM tbl_stores_offline_meters "
930
                       " WHERE store_id = %s AND offline_meter_id = %s ", (id_, mid))
931
        if cursor.fetchone() is None:
932
            cursor.close()
933
            cnx.disconnect()
934
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
935
                                   description='API.STORE_OFFLINE_METER_RELATION_NOT_FOUND')
936
937
        cursor.execute(" DELETE FROM tbl_stores_offline_meters "
938
                       " WHERE store_id = %s AND offline_meter_id = %s ", (id_, mid))
939
        cnx.commit()
940
941
        cursor.close()
942
        cnx.disconnect()
943
944
        resp.status = falcon.HTTP_204
945
946
947 View Code Duplication
class StorePointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
948
    @staticmethod
949
    def __init__():
950
        pass
951
952
    @staticmethod
953
    def on_options(req, resp, id_):
954
        resp.status = falcon.HTTP_200
955
956
    @staticmethod
957
    def on_get(req, resp, id_):
958
        if not id_.isdigit() or int(id_) <= 0:
959
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
960
                                   description='API.INVALID_STORE_ID')
961
962
        cnx = mysql.connector.connect(**config.myems_system_db)
963
        cursor = cnx.cursor(dictionary=True)
964
965
        cursor.execute(" SELECT name "
966
                       " FROM tbl_stores "
967
                       " WHERE id = %s ", (id_,))
968
        if cursor.fetchone() is None:
969
            cursor.close()
970
            cnx.disconnect()
971
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
972
                                   description='API.STORE_NOT_FOUND')
973
974
        query = (" SELECT id, name, uuid "
975
                 " FROM tbl_data_sources ")
976
        cursor.execute(query)
977
        rows_data_sources = cursor.fetchall()
978
979
        data_source_dict = dict()
980
        if rows_data_sources is not None and len(rows_data_sources) > 0:
981
            for row in rows_data_sources:
982
                data_source_dict[row['id']] = {"id": row['id'],
983
                                               "name": row['name'],
984
                                               "uuid": row['uuid']}
985
986
        query = (" SELECT p.id, p.name, p.data_source_id "
987
                 " FROM tbl_stores t, tbl_stores_points tp, tbl_points p "
988
                 " WHERE tp.store_id = t.id AND p.id = tp.point_id AND t.id = %s "
989
                 " ORDER BY p.id ")
990
        cursor.execute(query, (id_,))
991
        rows = cursor.fetchall()
992
993
        result = list()
994
        if rows is not None and len(rows) > 0:
995
            for row in rows:
996
                data_source = data_source_dict.get(row['data_source_id'], None)
997
                meta_result = {"id": row['id'], "name": row['name'], "data_source": data_source}
998
                result.append(meta_result)
999
1000
        resp.body = json.dumps(result)
1001
1002
    @staticmethod
1003
    def on_post(req, resp, id_):
1004
        """Handles POST requests"""
1005
        try:
1006
            raw_json = req.stream.read().decode('utf-8')
1007
        except Exception as ex:
1008
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1009
1010
        if not id_.isdigit() or int(id_) <= 0:
1011
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1012
                                   description='API.INVALID_STORE_ID')
1013
1014
        new_values = json.loads(raw_json)
1015
1016
        if 'point_id' not in new_values['data'].keys() or \
1017
                not isinstance(new_values['data']['point_id'], int) or \
1018
                new_values['data']['point_id'] <= 0:
1019
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1020
                                   description='API.INVALID_POINT_ID')
1021
        point_id = new_values['data']['point_id']
1022
1023
        cnx = mysql.connector.connect(**config.myems_system_db)
1024
        cursor = cnx.cursor()
1025
1026
        cursor.execute(" SELECT name "
1027
                       " from tbl_stores "
1028
                       " WHERE id = %s ", (id_,))
1029
        if cursor.fetchone() is None:
1030
            cursor.close()
1031
            cnx.disconnect()
1032
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1033
                                   description='API.STORE_NOT_FOUND')
1034
1035
        cursor.execute(" SELECT name "
1036
                       " FROM tbl_points "
1037
                       " WHERE id = %s ", (point_id,))
1038
        if cursor.fetchone() is None:
1039
            cursor.close()
1040
            cnx.disconnect()
1041
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1042
                                   description='API.POINT_NOT_FOUND')
1043
1044
        query = (" SELECT id " 
1045
                 " FROM tbl_stores_points "
1046
                 " WHERE store_id = %s AND point_id = %s")
1047
        cursor.execute(query, (id_, point_id,))
1048
        if cursor.fetchone() is not None:
1049
            cursor.close()
1050
            cnx.disconnect()
1051
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1052
                                   description='API.STORE_POINT_RELATION_EXISTED')
1053
1054
        add_row = (" INSERT INTO tbl_stores_points (store_id, point_id) "
1055
                   " VALUES (%s, %s) ")
1056
        cursor.execute(add_row, (id_, point_id,))
1057
        new_id = cursor.lastrowid
1058
        cnx.commit()
1059
        cursor.close()
1060
        cnx.disconnect()
1061
1062
        resp.status = falcon.HTTP_201
1063
        resp.location = '/stores/' + str(id_) + '/points/' + str(point_id)
1064
1065
1066 View Code Duplication
class StorePointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1067
    @staticmethod
1068
    def __init__():
1069
        pass
1070
1071
    @staticmethod
1072
    def on_options(req, resp, id_, pid):
1073
            resp.status = falcon.HTTP_200
1074
1075
    @staticmethod
1076
    def on_delete(req, resp, id_, pid):
1077
        if not id_.isdigit() or int(id_) <= 0:
1078
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1079
                                   description='API.INVALID_STORE_ID')
1080
1081
        if not pid.isdigit() or int(pid) <= 0:
1082
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1083
                                   description='API.INVALID_POINT_ID')
1084
1085
        cnx = mysql.connector.connect(**config.myems_system_db)
1086
        cursor = cnx.cursor()
1087
1088
        cursor.execute(" SELECT name "
1089
                       " FROM tbl_stores "
1090
                       " WHERE id = %s ", (id_,))
1091
        if cursor.fetchone() is None:
1092
            cursor.close()
1093
            cnx.disconnect()
1094
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1095
                                   description='API.STORE_NOT_FOUND')
1096
1097
        cursor.execute(" SELECT name "
1098
                       " FROM tbl_points "
1099
                       " WHERE id = %s ", (pid,))
1100
        if cursor.fetchone() is None:
1101
            cursor.close()
1102
            cnx.disconnect()
1103
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1104
                                   description='API.POINT_NOT_FOUND')
1105
1106
        cursor.execute(" SELECT id "
1107
                       " FROM tbl_stores_points "
1108
                       " WHERE store_id = %s AND point_id = %s ", (id_, pid))
1109
        if cursor.fetchone() is None:
1110
            cursor.close()
1111
            cnx.disconnect()
1112
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1113
                                   description='API.STORE_POINT_RELATION_NOT_FOUND')
1114
1115
        cursor.execute(" DELETE FROM tbl_stores_points "
1116
                       " WHERE store_id = %s AND point_id = %s ", (id_, pid))
1117
        cnx.commit()
1118
1119
        cursor.close()
1120
        cnx.disconnect()
1121
1122
        resp.status = falcon.HTTP_204
1123
1124
1125 View Code Duplication
class StoreSensorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1126
    @staticmethod
1127
    def __init__():
1128
        pass
1129
1130
    @staticmethod
1131
    def on_options(req, resp, id_):
1132
        resp.status = falcon.HTTP_200
1133
1134
    @staticmethod
1135
    def on_get(req, resp, id_):
1136
        if not id_.isdigit() or int(id_) <= 0:
1137
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1138
                                   description='API.INVALID_STORE_ID')
1139
1140
        cnx = mysql.connector.connect(**config.myems_system_db)
1141
        cursor = cnx.cursor()
1142
1143
        cursor.execute(" SELECT name "
1144
                       " FROM tbl_stores "
1145
                       " WHERE id = %s ", (id_,))
1146
        if cursor.fetchone() is None:
1147
            cursor.close()
1148
            cnx.disconnect()
1149
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1150
                                   description='API.STORE_NOT_FOUND')
1151
1152
        query = (" SELECT s.id, s.name, s.uuid "
1153
                 " FROM tbl_stores t, tbl_stores_sensors ts, tbl_sensors s "
1154
                 " WHERE ts.store_id = t.id AND s.id = ts.sensor_id AND t.id = %s "
1155
                 " ORDER BY s.id ")
1156
        cursor.execute(query, (id_,))
1157
        rows = cursor.fetchall()
1158
1159
        result = list()
1160
        if rows is not None and len(rows) > 0:
1161
            for row in rows:
1162
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1163
                result.append(meta_result)
1164
1165
        resp.body = json.dumps(result)
1166
1167
    @staticmethod
1168
    def on_post(req, resp, id_):
1169
        """Handles POST requests"""
1170
        try:
1171
            raw_json = req.stream.read().decode('utf-8')
1172
        except Exception as ex:
1173
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1174
1175
        if not id_.isdigit() or int(id_) <= 0:
1176
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1177
                                   description='API.INVALID_STORE_ID')
1178
1179
        new_values = json.loads(raw_json)
1180
1181
        if 'sensor_id' not in new_values['data'].keys() or \
1182
                not isinstance(new_values['data']['sensor_id'], int) or \
1183
                new_values['data']['sensor_id'] <= 0:
1184
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1185
                                   description='API.INVALID_SENSOR_ID')
1186
        sensor_id = new_values['data']['sensor_id']
1187
1188
        cnx = mysql.connector.connect(**config.myems_system_db)
1189
        cursor = cnx.cursor()
1190
1191
        cursor.execute(" SELECT name "
1192
                       " from tbl_stores "
1193
                       " WHERE id = %s ", (id_,))
1194
        if cursor.fetchone() is None:
1195
            cursor.close()
1196
            cnx.disconnect()
1197
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1198
                                   description='API.STORE_NOT_FOUND')
1199
1200
        cursor.execute(" SELECT name "
1201
                       " FROM tbl_sensors "
1202
                       " WHERE id = %s ", (sensor_id,))
1203
        if cursor.fetchone() is None:
1204
            cursor.close()
1205
            cnx.disconnect()
1206
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1207
                                   description='API.SENSOR_NOT_FOUND')
1208
1209
        query = (" SELECT id " 
1210
                 " FROM tbl_stores_sensors "
1211
                 " WHERE store_id = %s AND sensor_id = %s")
1212
        cursor.execute(query, (id_, sensor_id,))
1213
        if cursor.fetchone() is not None:
1214
            cursor.close()
1215
            cnx.disconnect()
1216
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1217
                                   description='API.STORE_SENSOR_RELATION_EXISTED')
1218
1219
        add_row = (" INSERT INTO tbl_stores_sensors (store_id, sensor_id) "
1220
                   " VALUES (%s, %s) ")
1221
        cursor.execute(add_row, (id_, sensor_id,))
1222
        new_id = cursor.lastrowid
1223
        cnx.commit()
1224
        cursor.close()
1225
        cnx.disconnect()
1226
1227
        resp.status = falcon.HTTP_201
1228
        resp.location = '/stores/' + str(id_) + '/sensors/' + str(sensor_id)
1229
1230
1231 View Code Duplication
class StoreSensorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1232
    @staticmethod
1233
    def __init__():
1234
        pass
1235
1236
    @staticmethod
1237
    def on_options(req, resp, id_, sid):
1238
            resp.status = falcon.HTTP_200
1239
1240
    @staticmethod
1241
    def on_delete(req, resp, id_, sid):
1242
        if not id_.isdigit() or int(id_) <= 0:
1243
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1244
                                   description='API.INVALID_STORE_ID')
1245
1246
        if not sid.isdigit() or int(sid) <= 0:
1247
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1248
                                   description='API.INVALID_SENSOR_ID')
1249
1250
        cnx = mysql.connector.connect(**config.myems_system_db)
1251
        cursor = cnx.cursor()
1252
1253
        cursor.execute(" SELECT name "
1254
                       " FROM tbl_stores "
1255
                       " WHERE id = %s ", (id_,))
1256
        if cursor.fetchone() is None:
1257
            cursor.close()
1258
            cnx.disconnect()
1259
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1260
                                   description='API.STORE_NOT_FOUND')
1261
1262
        cursor.execute(" SELECT name "
1263
                       " FROM tbl_sensors "
1264
                       " WHERE id = %s ", (sid,))
1265
        if cursor.fetchone() is None:
1266
            cursor.close()
1267
            cnx.disconnect()
1268
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1269
                                   description='API.SENSOR_NOT_FOUND')
1270
1271
        cursor.execute(" SELECT id "
1272
                       " FROM tbl_stores_sensors "
1273
                       " WHERE store_id = %s AND sensor_id = %s ", (id_, sid))
1274
        if cursor.fetchone() is None:
1275
            cursor.close()
1276
            cnx.disconnect()
1277
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1278
                                   description='API.STORE_SENSOR_RELATION_NOT_FOUND')
1279
1280
        cursor.execute(" DELETE FROM tbl_stores_sensors WHERE store_id = %s AND sensor_id = %s ", (id_, sid))
1281
        cnx.commit()
1282
1283
        cursor.close()
1284
        cnx.disconnect()
1285
1286
        resp.status = falcon.HTTP_204
1287
1288
1289 View Code Duplication
class StoreVirtualMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1290
    @staticmethod
1291
    def __init__():
1292
        pass
1293
1294
    @staticmethod
1295
    def on_options(req, resp, id_):
1296
        resp.status = falcon.HTTP_200
1297
1298
    @staticmethod
1299
    def on_get(req, resp, id_):
1300
        if not id_.isdigit() or int(id_) <= 0:
1301
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1302
                                   description='API.INVALID_STORE_ID')
1303
1304
        cnx = mysql.connector.connect(**config.myems_system_db)
1305
        cursor = cnx.cursor(dictionary=True)
1306
1307
        cursor.execute(" SELECT name "
1308
                       " FROM tbl_stores "
1309
                       " WHERE id = %s ", (id_,))
1310
        if cursor.fetchone() is None:
1311
            cursor.close()
1312
            cnx.disconnect()
1313
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1314
                                   description='API.STORE_NOT_FOUND')
1315
1316
        query = (" SELECT id, name, uuid "
1317
                 " FROM tbl_energy_categories ")
1318
        cursor.execute(query)
1319
        rows_energy_categories = cursor.fetchall()
1320
1321
        energy_category_dict = dict()
1322
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1323
            for row in rows_energy_categories:
1324
                energy_category_dict[row['id']] = {"id": row['id'],
1325
                                                   "name": row['name'],
1326
                                                   "uuid": row['uuid']}
1327
1328
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1329
                 " FROM tbl_stores t, tbl_stores_virtual_meters tm, tbl_virtual_meters m "
1330
                 " WHERE tm.store_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s "
1331
                 " ORDER BY m.id ")
1332
        cursor.execute(query, (id_,))
1333
        rows = cursor.fetchall()
1334
1335
        result = list()
1336
        if rows is not None and len(rows) > 0:
1337
            for row in rows:
1338
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1339
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1340
                               "energy_category": energy_category}
1341
                result.append(meta_result)
1342
1343
        resp.body = json.dumps(result)
1344
1345
    @staticmethod
1346
    def on_post(req, resp, id_):
1347
        """Handles POST requests"""
1348
        try:
1349
            raw_json = req.stream.read().decode('utf-8')
1350
        except Exception as ex:
1351
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1352
1353
        if not id_.isdigit() or int(id_) <= 0:
1354
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1355
                                   description='API.INVALID_STORE_ID')
1356
1357
        new_values = json.loads(raw_json)
1358
1359
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1360
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1361
                new_values['data']['virtual_meter_id'] <= 0:
1362
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1363
                                   description='API.INVALID_VIRTUAL_METER_ID')
1364
        virtual_meter_id = new_values['data']['virtual_meter_id']
1365
1366
        cnx = mysql.connector.connect(**config.myems_system_db)
1367
        cursor = cnx.cursor()
1368
1369
        cursor.execute(" SELECT name "
1370
                       " from tbl_stores "
1371
                       " WHERE id = %s ", (id_,))
1372
        if cursor.fetchone() is None:
1373
            cursor.close()
1374
            cnx.disconnect()
1375
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1376
                                   description='API.STORE_NOT_FOUND')
1377
1378
        cursor.execute(" SELECT name "
1379
                       " FROM tbl_virtual_meters "
1380
                       " WHERE id = %s ", (virtual_meter_id,))
1381
        if cursor.fetchone() is None:
1382
            cursor.close()
1383
            cnx.disconnect()
1384
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1385
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1386
1387
        query = (" SELECT id " 
1388
                 " FROM tbl_stores_virtual_meters "
1389
                 " WHERE store_id = %s AND virtual_meter_id = %s")
1390
        cursor.execute(query, (id_, virtual_meter_id,))
1391
        if cursor.fetchone() is not None:
1392
            cursor.close()
1393
            cnx.disconnect()
1394
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1395
                                   description='API.STORE_VIRTUAL_METER_RELATION_EXISTED')
1396
1397
        add_row = (" INSERT INTO tbl_stores_virtual_meters (store_id, virtual_meter_id) "
1398
                   " VALUES (%s, %s) ")
1399
        cursor.execute(add_row, (id_, virtual_meter_id,))
1400
        new_id = cursor.lastrowid
1401
        cnx.commit()
1402
        cursor.close()
1403
        cnx.disconnect()
1404
1405
        resp.status = falcon.HTTP_201
1406
        resp.location = '/stores/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1407
1408
1409 View Code Duplication
class StoreVirtualMeterItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1410
    @staticmethod
1411
    def __init__():
1412
        pass
1413
1414
    @staticmethod
1415
    def on_options(req, resp, id_, mid):
1416
            resp.status = falcon.HTTP_200
1417
1418
    @staticmethod
1419
    def on_delete(req, resp, id_, mid):
1420
        if not id_.isdigit() or int(id_) <= 0:
1421
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1422
                                   description='API.INVALID_STORE_ID')
1423
1424
        if not mid.isdigit() or int(mid) <= 0:
1425
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1426
                                   description='API.INVALID_VIRTUAL_METER_ID')
1427
1428
        cnx = mysql.connector.connect(**config.myems_system_db)
1429
        cursor = cnx.cursor()
1430
1431
        cursor.execute(" SELECT name "
1432
                       " FROM tbl_stores "
1433
                       " WHERE id = %s ", (id_,))
1434
        if cursor.fetchone() is None:
1435
            cursor.close()
1436
            cnx.disconnect()
1437
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1438
                                   description='API.STORE_NOT_FOUND')
1439
1440
        cursor.execute(" SELECT name "
1441
                       " FROM tbl_virtual_meters "
1442
                       " WHERE id = %s ", (mid,))
1443
        if cursor.fetchone() is None:
1444
            cursor.close()
1445
            cnx.disconnect()
1446
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1447
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1448
1449
        cursor.execute(" SELECT id "
1450
                       " FROM tbl_stores_virtual_meters "
1451
                       " WHERE store_id = %s AND virtual_meter_id = %s ", (id_, mid))
1452
        if cursor.fetchone() is None:
1453
            cursor.close()
1454
            cnx.disconnect()
1455
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1456
                                   description='API.STORE_VIRTUAL_METER_RELATION_NOT_FOUND')
1457
1458
        cursor.execute(" DELETE FROM tbl_stores_virtual_meters "
1459
                       " WHERE store_id = %s AND virtual_meter_id = %s ", (id_, mid))
1460
        cnx.commit()
1461
1462
        cursor.close()
1463
        cnx.disconnect()
1464
1465
        resp.status = falcon.HTTP_204
1466
1467
1468