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

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 2
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 2
dl 2
loc 2
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
import uuid
2
from datetime import datetime, timedelta
3
import falcon
4
import mysql.connector
5
import simplejson as json
6
from core.useractivity import user_logger, admin_control, access_control, api_key_control
7
import config
8
9
10
class StoreCollection:
11
    """
12
    Store Collection Resource
13
14
    This class handles CRUD operations for store collection.
15
    It provides endpoints for listing all stores and creating new ones.
16
    Stores represent retail or commercial spaces within facilities,
17
    containing equipment, meters, and other components for monitoring
18
    and managing commercial operations and energy consumption.
19
    """
20
    def __init__(self):
21
        pass
22
23
    @staticmethod
24
    def on_options(req, resp):
25
        """
26
        Handle OPTIONS request for CORS preflight
27
28
        Args:
29
            req: Falcon request object
30
            resp: Falcon response object
31
        """
32
        _ = req
33
        resp.status = falcon.HTTP_200
34
35
    @staticmethod
36
    def on_get(req, resp):
37
        """
38
        Handle GET requests to retrieve all stores
39
40
        Returns a list of all stores with their complete information including:
41
        - Store ID, name, and UUID
42
        - Associated store type, contact, and cost center information
43
        - Store specifications and parameters
44
        - Related equipment and meter associations
45
        - Working calendar configurations
46
47
        Args:
48
            req: Falcon request object
49
            resp: Falcon response object
50
        """
51
        # Check authentication method (API key or session)
52
        if 'API-KEY' not in req.headers or \
53
                not isinstance(req.headers['API-KEY'], str) or \
54
                len(str.strip(req.headers['API-KEY'])) == 0:
55
            access_control(req)
56
        else:
57
            api_key_control(req)
58
59
        search_query = req.get_param('q', default=None)
60
        if search_query is not None and len(search_query.strip()) > 0:
61
            search_query = search_query.strip()
62
        else:
63
            search_query = ''
64
65
        cnx = mysql.connector.connect(**config.myems_system_db)
66
        cursor = cnx.cursor()
67
68
        query = (" SELECT id, name, uuid "
69
                 " FROM tbl_store_types ")
70
        cursor.execute(query)
71
        rows_store_types = cursor.fetchall()
72
73
        store_type_dict = dict()
74
        if rows_store_types is not None and len(rows_store_types) > 0:
75
            for row in rows_store_types:
76
                store_type_dict[row[0]] = {"id": row[0],
77
                                           "name": row[1],
78
                                           "uuid": row[2]}
79
80
        query = (" SELECT id, name, uuid "
81
                 " FROM tbl_contacts ")
82
        cursor.execute(query)
83
        rows_contacts = cursor.fetchall()
84
85
        contact_dict = dict()
86
        if rows_contacts is not None and len(rows_contacts) > 0:
87
            for row in rows_contacts:
88
                contact_dict[row[0]] = {"id": row[0],
89
                                        "name": row[1],
90
                                        "uuid": row[2]}
91
92
        query = (" SELECT id, name, uuid "
93
                 " FROM tbl_cost_centers ")
94
        cursor.execute(query)
95
        rows_cost_centers = cursor.fetchall()
96
97
        cost_center_dict = dict()
98
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
99
            for row in rows_cost_centers:
100
                cost_center_dict[row[0]] = {"id": row[0],
101
                                            "name": row[1],
102
                                            "uuid": row[2]}
103
104
        query = (" SELECT id, name, uuid, "
105
                 "        address, latitude, longitude, area, store_type_id, "
106
                 "        is_input_counted, contact_id, cost_center_id, description "
107
                 " FROM tbl_stores ")
108
        params = []
109
        if search_query:
110
            query += " WHERE name LIKE %s OR description LIKE %s OR address LIKE %s "
111
            params = [f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']
112
        query += " ORDER BY id "
113
        cursor.execute(query, params)
114
        rows_spaces = cursor.fetchall()
115
116
        result = list()
117 View Code Duplication
        if rows_spaces is not None and len(rows_spaces) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
118
            for row in rows_spaces:
119
120
                meta_result = {"id": row[0],
121
                               "name": row[1],
122
                               "uuid": row[2],
123
                               "address": row[3],
124
                               "latitude": row[4],
125
                               "longitude": row[5],
126
                               "area": row[6],
127
                               "store_type": store_type_dict.get(row[7], None),
128
                               "is_input_counted": bool(row[8]),
129
                               "contact": contact_dict.get(row[9], None),
130
                               "cost_center": cost_center_dict.get(row[10], None),
131
                               "description": row[11],
132
                               "qrcode": 'store:' + row[2]}
133
                result.append(meta_result)
134
135
        cursor.close()
136
        cnx.close()
137
        resp.text = json.dumps(result)
138
139
    @staticmethod
140
    @user_logger
141
    def on_post(req, resp):
142
        """Handles POST requests"""
143
        admin_control(req)
144
        try:
145
            raw_json = req.stream.read().decode('utf-8')
146
        except Exception as ex:
147
            print(str(ex))
148
            raise falcon.HTTPError(status=falcon.HTTP_400,
149
                                   title='API.BAD_REQUEST',
150
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
151
152
        new_values = json.loads(raw_json)
153
154
        if 'name' not in new_values['data'].keys() or \
155
                not isinstance(new_values['data']['name'], str) or \
156
                len(str.strip(new_values['data']['name'])) == 0:
157
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
158
                                   description='API.INVALID_STORE_NAME')
159
        name = str.strip(new_values['data']['name'])
160
161
        if 'address' not in new_values['data'].keys() or \
162
                not isinstance(new_values['data']['address'], str) or \
163
                len(str.strip(new_values['data']['address'])) == 0:
164
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
165
                                   description='API.INVALID_ADDRESS_VALUE')
166
        address = str.strip(new_values['data']['address'])
167
168
        if 'latitude' not in new_values['data'].keys() or \
169
                not (isinstance(new_values['data']['latitude'], float) or
170
                     isinstance(new_values['data']['latitude'], int)) or \
171
                new_values['data']['latitude'] < -90.0 or \
172
                new_values['data']['latitude'] > 90.0:
173
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
174
                                   description='API.INVALID_LATITUDE_VALUE')
175
        latitude = new_values['data']['latitude']
176
177
        if 'longitude' not in new_values['data'].keys() or \
178
                not (isinstance(new_values['data']['longitude'], float) or
179
                     isinstance(new_values['data']['longitude'], int)) or \
180
                new_values['data']['longitude'] < -180.0 or \
181
                new_values['data']['longitude'] > 180.0:
182
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
183
                                   description='API.INVALID_LONGITUDE_VALUE')
184
        longitude = new_values['data']['longitude']
185
186
        if 'area' not in new_values['data'].keys() or \
187
                not (isinstance(new_values['data']['area'], float) or
188
                     isinstance(new_values['data']['area'], int)) or \
189
                new_values['data']['area'] <= 0.0:
190
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
191
                                   description='API.INVALID_AREA_VALUE')
192
        area = new_values['data']['area']
193
194
        if 'store_type_id' not in new_values['data'].keys() or \
195
                not isinstance(new_values['data']['store_type_id'], int) or \
196
                new_values['data']['store_type_id'] <= 0:
197
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
198
                                   description='API.INVALID_STORE_TYPE_ID')
199
        store_type_id = new_values['data']['store_type_id']
200
201
        if 'is_input_counted' not in new_values['data'].keys() or \
202
                not isinstance(new_values['data']['is_input_counted'], bool):
203
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
204
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
205
        is_input_counted = new_values['data']['is_input_counted']
206
207
        if 'contact_id' not in new_values['data'].keys() or \
208
                not isinstance(new_values['data']['contact_id'], int) or \
209
                new_values['data']['contact_id'] <= 0:
210
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
211
                                   description='API.INVALID_CONTACT_ID')
212
        contact_id = new_values['data']['contact_id']
213
214
        if 'cost_center_id' not in new_values['data'].keys() or \
215
                not isinstance(new_values['data']['cost_center_id'], int) or \
216
                new_values['data']['cost_center_id'] <= 0:
217
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
218
                                   description='API.INVALID_COST_CENTER_ID')
219
        cost_center_id = new_values['data']['cost_center_id']
220
221
        if 'description' in new_values['data'].keys() and \
222
                new_values['data']['description'] is not None and \
223
                len(str(new_values['data']['description'])) > 0:
224
            description = str.strip(new_values['data']['description'])
225
        else:
226
            description = None
227
228
        cnx = mysql.connector.connect(**config.myems_system_db)
229
        cursor = cnx.cursor()
230
231
        cursor.execute(" SELECT name "
232
                       " FROM tbl_stores "
233
                       " WHERE name = %s ", (name,))
234
        if cursor.fetchone() is not None:
235
            cursor.close()
236
            cnx.close()
237
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
238
                                   description='API.STORE_NAME_IS_ALREADY_IN_USE')
239
240
        cursor.execute(" SELECT name "
241
                       " FROM tbl_store_types "
242
                       " WHERE id = %s ",
243
                       (store_type_id,))
244
        if cursor.fetchone() is None:
245
            cursor.close()
246
            cnx.close()
247
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
248
                                   description='API.STORE_TYPE_NOT_FOUND')
249
250
        cursor.execute(" SELECT name "
251
                       " FROM tbl_contacts "
252
                       " WHERE id = %s ",
253
                       (new_values['data']['contact_id'],))
254
        row = cursor.fetchone()
255
        if row is None:
256
            cursor.close()
257
            cnx.close()
258
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
259
                                   description='API.CONTACT_NOT_FOUND')
260
261
        cursor.execute(" SELECT name "
262
                       " FROM tbl_cost_centers "
263
                       " WHERE id = %s ",
264
                       (new_values['data']['cost_center_id'],))
265
        row = cursor.fetchone()
266
        if row is None:
267
            cursor.close()
268
            cnx.close()
269
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
270
                                   description='API.COST_CENTER_NOT_FOUND')
271
272
        add_values = (" INSERT INTO tbl_stores "
273
                      "    (name, uuid, address, latitude, longitude, area, store_type_id, "
274
                      "     is_input_counted, "
275
                      "     contact_id, cost_center_id, description) "
276
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
277
        cursor.execute(add_values, (name,
278
                                    str(uuid.uuid4()),
279
                                    address,
280
                                    latitude,
281
                                    longitude,
282
                                    area,
283
                                    store_type_id,
284
                                    is_input_counted,
285
                                    contact_id,
286
                                    cost_center_id,
287
                                    description))
288
        new_id = cursor.lastrowid
289
        cnx.commit()
290
        cursor.close()
291
        cnx.close()
292
293
        resp.status = falcon.HTTP_201
294
        resp.location = '/stores/' + str(new_id)
295
296
297
class StoreItem:
298
    def __init__(self):
299
        pass
300
301
    @staticmethod
302
    def on_options(req, resp, id_):
303
        _ = req
304
        resp.status = falcon.HTTP_200
305
        _ = id_
306
307
    @staticmethod
308
    def on_get(req, resp, id_):
309
        if 'API-KEY' not in req.headers or \
310
                not isinstance(req.headers['API-KEY'], str) or \
311
                len(str.strip(req.headers['API-KEY'])) == 0:
312
            access_control(req)
313
        else:
314
            api_key_control(req)
315
        if not id_.isdigit() or int(id_) <= 0:
316
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
317
                                   description='API.INVALID_STORE_ID')
318
319
        cnx = mysql.connector.connect(**config.myems_system_db)
320
        cursor = cnx.cursor()
321
322
        query = (" SELECT id, name, uuid "
323
                 " FROM tbl_store_types ")
324
        cursor.execute(query)
325
        rows_store_types = cursor.fetchall()
326
327
        store_type_dict = dict()
328
        if rows_store_types is not None and len(rows_store_types) > 0:
329
            for row in rows_store_types:
330
                store_type_dict[row[0]] = {"id": row[0],
331
                                           "name": row[1],
332
                                           "uuid": row[2]}
333
334
        query = (" SELECT id, name, uuid "
335
                 " FROM tbl_contacts ")
336
        cursor.execute(query)
337
        rows_contacts = cursor.fetchall()
338
339
        contact_dict = dict()
340
        if rows_contacts is not None and len(rows_contacts) > 0:
341
            for row in rows_contacts:
342
                contact_dict[row[0]] = {"id": row[0],
343
                                        "name": row[1],
344
                                        "uuid": row[2]}
345
346
        query = (" SELECT id, name, uuid "
347
                 " FROM tbl_cost_centers ")
348
        cursor.execute(query)
349
        rows_cost_centers = cursor.fetchall()
350
351
        cost_center_dict = dict()
352
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
353
            for row in rows_cost_centers:
354
                cost_center_dict[row[0]] = {"id": row[0],
355
                                            "name": row[1],
356
                                            "uuid": row[2]}
357
358
        query = (" SELECT id, name, uuid, "
359
                 "        address, latitude, longitude, area, store_type_id,"
360
                 "        is_input_counted, "
361
                 "        contact_id, cost_center_id, description "
362
                 " FROM tbl_stores "
363
                 " WHERE id = %s ")
364
        cursor.execute(query, (id_,))
365
        row = cursor.fetchone()
366
        cursor.close()
367
        cnx.close()
368
369 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...
370
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
371
                                   description='API.STORE_NOT_FOUND')
372
        else:
373
            meta_result = {"id": row[0],
374
                           "name": row[1],
375
                           "uuid": row[2],
376
                           "address": row[3],
377
                           "latitude": row[4],
378
                           "longitude": row[5],
379
                           "area": row[6],
380
                           "store_type": store_type_dict.get(row[7], None),
381
                           "is_input_counted": bool(row[8]),
382
                           "contact": contact_dict.get(row[9], None),
383
                           "cost_center": cost_center_dict.get(row[10], None),
384
                           "description": row[11],
385
                           "qrcode": 'store:' + row[2]}
386
387
        resp.text = json.dumps(meta_result)
388
389 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
390
    @user_logger
391
    def on_delete(req, resp, id_):
392
        admin_control(req)
393
        if not id_.isdigit() or int(id_) <= 0:
394
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
395
                                   description='API.INVALID_STORE_ID')
396
397
        cnx = mysql.connector.connect(**config.myems_system_db)
398
        cursor = cnx.cursor()
399
400
        cursor.execute(" SELECT name "
401
                       " FROM tbl_stores "
402
                       " WHERE id = %s ", (id_,))
403
        if cursor.fetchone() is None:
404
            cursor.close()
405
            cnx.close()
406
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
407
                                   description='API.STORE_NOT_FOUND')
408
409
        # check relation with space
410
        cursor.execute(" SELECT space_id "
411
                       " FROM tbl_spaces_stores "
412
                       " WHERE store_id = %s ",
413
                       (id_,))
414
        rows_spaces = cursor.fetchall()
415
        if rows_spaces is not None and len(rows_spaces) > 0:
416
            cursor.close()
417
            cnx.close()
418
            raise falcon.HTTPError(status=falcon.HTTP_400,
419
                                   title='API.BAD_REQUEST',
420
                                   description='API.THERE_IS_RELATION_WITH_SPACES')
421
422
        # delete relation with meter
423
        cursor.execute(" DELETE FROM tbl_stores_meters WHERE store_id = %s ", (id_,))
424
425
        # delete relation with offline meter
426
        cursor.execute(" DELETE FROM tbl_stores_offline_meters WHERE store_id = %s ", (id_,))
427
428
        # delete relation with points
429
        cursor.execute(" DELETE FROM tbl_stores_points WHERE store_id = %s ", (id_,))
430
431
        # delete relation with sensor
432
        cursor.execute(" DELETE FROM tbl_stores_sensors WHERE store_id = %s ", (id_,))
433
434
        # delete relation with virtual meter
435
        cursor.execute(" DELETE FROM tbl_stores_virtual_meters WHERE store_id = %s ", (id_,))
436
437
        # delete relation with command
438
        cursor.execute(" DELETE FROM tbl_stores_commands WHERE store_id = %s ", (id_,))
439
440
        # delete relation with working calendar
441
        cursor.execute(" DELETE FROM tbl_stores_working_calendars WHERE store_id = %s ", (id_,))
442
443
        cursor.execute(" DELETE FROM tbl_stores WHERE id = %s ", (id_,))
444
        cnx.commit()
445
446
        cursor.close()
447
        cnx.close()
448
449
        resp.status = falcon.HTTP_204
450
451
    @staticmethod
452
    @user_logger
453
    def on_put(req, resp, id_):
454
        """Handles PUT requests"""
455
        admin_control(req)
456
        try:
457
            raw_json = req.stream.read().decode('utf-8')
458
        except Exception as ex:
459
            print(str(ex))
460
            raise falcon.HTTPError(status=falcon.HTTP_400,
461
                                   title='API.BAD_REQUEST',
462
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
463
464
        if not id_.isdigit() or int(id_) <= 0:
465
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
466
                                   description='API.INVALID_STORE_ID')
467
468
        new_values = json.loads(raw_json)
469
470
        if 'name' not in new_values['data'].keys() or \
471
                not isinstance(new_values['data']['name'], str) or \
472
                len(str.strip(new_values['data']['name'])) == 0:
473
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
474
                                   description='API.INVALID_STORE_NAME')
475
        name = str.strip(new_values['data']['name'])
476
477
        if 'address' not in new_values['data'].keys() or \
478
                not isinstance(new_values['data']['address'], str) or \
479
                len(str.strip(new_values['data']['address'])) == 0:
480
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
481
                                   description='API.INVALID_ADDRESS_VALUE')
482
        address = str.strip(new_values['data']['address'])
483
484
        if 'latitude' not in new_values['data'].keys() or \
485
                not (isinstance(new_values['data']['latitude'], float) or
486
                     isinstance(new_values['data']['latitude'], int)) or \
487
                new_values['data']['latitude'] < -90.0 or \
488
                new_values['data']['latitude'] > 90.0:
489
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
490
                                   description='API.INVALID_LATITUDE_VALUE')
491
        latitude = new_values['data']['latitude']
492
493
        if 'longitude' not in new_values['data'].keys() or \
494
                not (isinstance(new_values['data']['longitude'], float) or
495
                     isinstance(new_values['data']['longitude'], int)) or \
496
                new_values['data']['longitude'] < -180.0 or \
497
                new_values['data']['longitude'] > 180.0:
498
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
499
                                   description='API.INVALID_LONGITUDE_VALUE')
500
        longitude = new_values['data']['longitude']
501
502
        if 'area' not in new_values['data'].keys() or \
503
                not (isinstance(new_values['data']['area'], float) or
504
                     isinstance(new_values['data']['area'], int)) or \
505
                new_values['data']['area'] <= 0.0:
506
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
507
                                   description='API.INVALID_AREA_VALUE')
508
        area = new_values['data']['area']
509
510
        if 'store_type_id' not in new_values['data'].keys() or \
511
                not isinstance(new_values['data']['store_type_id'], int) or \
512
                new_values['data']['store_type_id'] <= 0:
513
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
514
                                   description='API.INVALID_STORE_TYPE_ID')
515
        store_type_id = new_values['data']['store_type_id']
516
517
        if 'is_input_counted' not in new_values['data'].keys() or \
518
                not isinstance(new_values['data']['is_input_counted'], bool):
519
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
520
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
521
        is_input_counted = new_values['data']['is_input_counted']
522
523
        if 'contact_id' not in new_values['data'].keys() or \
524
                not isinstance(new_values['data']['contact_id'], int) or \
525
                new_values['data']['contact_id'] <= 0:
526
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
527
                                   description='API.INVALID_CONTACT_ID')
528
        contact_id = new_values['data']['contact_id']
529
530
        if 'cost_center_id' not in new_values['data'].keys() or \
531
                not isinstance(new_values['data']['cost_center_id'], int) or \
532
                new_values['data']['cost_center_id'] <= 0:
533
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
534
                                   description='API.INVALID_COST_CENTER_ID')
535
        cost_center_id = new_values['data']['cost_center_id']
536
537
        if 'description' in new_values['data'].keys() and \
538
                new_values['data']['description'] is not None and \
539
                len(str(new_values['data']['description'])) > 0:
540
            description = str.strip(new_values['data']['description'])
541
        else:
542
            description = None
543
544
        cnx = mysql.connector.connect(**config.myems_system_db)
545
        cursor = cnx.cursor()
546
547
        cursor.execute(" SELECT name "
548
                       " FROM tbl_stores "
549
                       " WHERE id = %s ", (id_,))
550
        if cursor.fetchone() is None:
551
            cursor.close()
552
            cnx.close()
553
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
554
                                   description='API.STORE_NOT_FOUND')
555
556
        cursor.execute(" SELECT name "
557
                       " FROM tbl_stores "
558
                       " WHERE name = %s AND id != %s ", (name, id_))
559
        if cursor.fetchone() is not None:
560
            cursor.close()
561
            cnx.close()
562
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
563
                                   description='API.STORE_NAME_IS_ALREADY_IN_USE')
564
565
        cursor.execute(" SELECT name "
566
                       " FROM tbl_store_types "
567
                       " WHERE id = %s ",
568
                       (store_type_id,))
569
        if cursor.fetchone() is None:
570
            cursor.close()
571
            cnx.close()
572
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
573
                                   description='API.STORE_TYPE_NOT_FOUND')
574
575
        cursor.execute(" SELECT name "
576
                       " FROM tbl_contacts "
577
                       " WHERE id = %s ",
578
                       (new_values['data']['contact_id'],))
579
        row = cursor.fetchone()
580
        if row is None:
581
            cursor.close()
582
            cnx.close()
583
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
584
                                   description='API.CONTACT_NOT_FOUND')
585
586
        cursor.execute(" SELECT name "
587
                       " FROM tbl_cost_centers "
588
                       " WHERE id = %s ",
589
                       (new_values['data']['cost_center_id'],))
590
        row = cursor.fetchone()
591
        if row is None:
592
            cursor.close()
593
            cnx.close()
594
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
595
                                   description='API.COST_CENTER_NOT_FOUND')
596
597
        update_row = (" UPDATE tbl_stores "
598
                      " SET name = %s, address = %s, latitude = %s, longitude = %s, area = %s, "
599
                      "     store_type_id = %s, is_input_counted = %s, "
600
                      "     contact_id = %s, cost_center_id = %s, "
601
                      "     description = %s "
602
                      " WHERE id = %s ")
603
        cursor.execute(update_row, (name,
604
                                    address,
605
                                    latitude,
606
                                    longitude,
607
                                    area,
608
                                    store_type_id,
609
                                    is_input_counted,
610
                                    contact_id,
611
                                    cost_center_id,
612
                                    description,
613
                                    id_))
614
        cnx.commit()
615
616
        cursor.close()
617
        cnx.close()
618
619
        resp.status = falcon.HTTP_200
620
621
622 View Code Duplication
class StoreMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
623
    def __init__(self):
624
        pass
625
626
    @staticmethod
627
    def on_options(req, resp, id_):
628
        _ = req
629
        resp.status = falcon.HTTP_200
630
        _ = id_
631
632
    @staticmethod
633
    def on_get(req, resp, id_):
634
        if 'API-KEY' not in req.headers or \
635
                not isinstance(req.headers['API-KEY'], str) or \
636
                len(str.strip(req.headers['API-KEY'])) == 0:
637
            access_control(req)
638
        else:
639
            api_key_control(req)
640
        if not id_.isdigit() or int(id_) <= 0:
641
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
642
                                   description='API.INVALID_STORE_ID')
643
644
        cnx = mysql.connector.connect(**config.myems_system_db)
645
        cursor = cnx.cursor()
646
647
        cursor.execute(" SELECT name "
648
                       " FROM tbl_stores "
649
                       " WHERE id = %s ", (id_,))
650
        if cursor.fetchone() is None:
651
            cursor.close()
652
            cnx.close()
653
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
654
                                   description='API.STORE_NOT_FOUND')
655
656
        query = (" SELECT id, name, uuid "
657
                 " FROM tbl_energy_categories ")
658
        cursor.execute(query)
659
        rows_energy_categories = cursor.fetchall()
660
661
        energy_category_dict = dict()
662
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
663
            for row in rows_energy_categories:
664
                energy_category_dict[row[0]] = {"id": row[0],
665
                                                "name": row[1],
666
                                                "uuid": row[2]}
667
668
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
669
                 " FROM tbl_stores t, tbl_stores_meters tm, tbl_meters m "
670
                 " WHERE tm.store_id = t.id AND m.id = tm.meter_id AND t.id = %s "
671
                 " ORDER BY m.id ")
672
        cursor.execute(query, (id_,))
673
        rows = cursor.fetchall()
674
675
        result = list()
676
        if rows is not None and len(rows) > 0:
677
            for row in rows:
678
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
679
                               "energy_category": energy_category_dict.get(row[3], None)}
680
                result.append(meta_result)
681
682
        resp.text = json.dumps(result)
683
684
    @staticmethod
685
    @user_logger
686
    def on_post(req, resp, id_):
687
        """Handles POST requests"""
688
        admin_control(req)
689
        try:
690
            raw_json = req.stream.read().decode('utf-8')
691
        except Exception as ex:
692
            print(str(ex))
693
            raise falcon.HTTPError(status=falcon.HTTP_400,
694
                                   title='API.BAD_REQUEST',
695
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
696
697
        if not id_.isdigit() or int(id_) <= 0:
698
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
699
                                   description='API.INVALID_STORE_ID')
700
701
        new_values = json.loads(raw_json)
702
703
        if 'meter_id' not in new_values['data'].keys() or \
704
                not isinstance(new_values['data']['meter_id'], int) or \
705
                new_values['data']['meter_id'] <= 0:
706
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
707
                                   description='API.INVALID_METER_ID')
708
        meter_id = new_values['data']['meter_id']
709
710
        cnx = mysql.connector.connect(**config.myems_system_db)
711
        cursor = cnx.cursor()
712
713
        cursor.execute(" SELECT name "
714
                       " from tbl_stores "
715
                       " WHERE id = %s ", (id_,))
716
        if cursor.fetchone() is None:
717
            cursor.close()
718
            cnx.close()
719
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
720
                                   description='API.STORE_NOT_FOUND')
721
722
        cursor.execute(" SELECT name "
723
                       " FROM tbl_meters "
724
                       " WHERE id = %s ", (meter_id,))
725
        if cursor.fetchone() is None:
726
            cursor.close()
727
            cnx.close()
728
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
729
                                   description='API.METER_NOT_FOUND')
730
731
        query = (" SELECT id "
732
                 " FROM tbl_stores_meters "
733
                 " WHERE store_id = %s AND meter_id = %s")
734
        cursor.execute(query, (id_, meter_id,))
735
        if cursor.fetchone() is not None:
736
            cursor.close()
737
            cnx.close()
738
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
739
                                   description='API.STORE_METER_RELATION_EXISTS')
740
741
        add_row = (" INSERT INTO tbl_stores_meters (store_id, meter_id) "
742
                   " VALUES (%s, %s) ")
743
        cursor.execute(add_row, (id_, meter_id,))
744
        cnx.commit()
745
        cursor.close()
746
        cnx.close()
747
748
        resp.status = falcon.HTTP_201
749
        resp.location = '/stores/' + str(id_) + '/meters/' + str(meter_id)
750
751
752
class StoreMeterItem:
753
    def __init__(self):
754
        pass
755
756
    @staticmethod
757
    def on_options(req, resp, id_, mid):
758
        _ = req
759
        resp.status = falcon.HTTP_200
760
        _ = id_
761
762
    @staticmethod
763
    @user_logger
764
    def on_delete(req, resp, id_, mid):
765
        admin_control(req)
766
        if not id_.isdigit() or int(id_) <= 0:
767
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
768
                                   description='API.INVALID_STORE_ID')
769
770
        if not mid.isdigit() or int(mid) <= 0:
771
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
772
                                   description='API.INVALID_METER_ID')
773
774
        cnx = mysql.connector.connect(**config.myems_system_db)
775
        cursor = cnx.cursor()
776
777
        cursor.execute(" SELECT name "
778
                       " FROM tbl_stores "
779
                       " WHERE id = %s ", (id_,))
780
        if cursor.fetchone() is None:
781
            cursor.close()
782
            cnx.close()
783
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
784
                                   description='API.STORE_NOT_FOUND')
785
786
        cursor.execute(" SELECT name "
787
                       " FROM tbl_meters "
788
                       " WHERE id = %s ", (mid,))
789
        if cursor.fetchone() is None:
790
            cursor.close()
791
            cnx.close()
792
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
793
                                   description='API.METER_NOT_FOUND')
794
795
        cursor.execute(" SELECT id "
796
                       " FROM tbl_stores_meters "
797
                       " WHERE store_id = %s AND meter_id = %s ", (id_, mid))
798
        if cursor.fetchone() is None:
799
            cursor.close()
800
            cnx.close()
801
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
802
                                   description='API.STORE_METER_RELATION_NOT_FOUND')
803
804
        cursor.execute(" DELETE FROM tbl_stores_meters WHERE store_id = %s AND meter_id = %s ", (id_, mid))
805
        cnx.commit()
806
807
        cursor.close()
808
        cnx.close()
809
810
        resp.status = falcon.HTTP_204
811
812
813 View Code Duplication
class StoreOfflineMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
814
    def __init__(self):
815
        pass
816
817
    @staticmethod
818
    def on_options(req, resp, id_):
819
        _ = req
820
        resp.status = falcon.HTTP_200
821
        _ = id_
822
823
    @staticmethod
824
    def on_get(req, resp, id_):
825
        if 'API-KEY' not in req.headers or \
826
                not isinstance(req.headers['API-KEY'], str) or \
827
                len(str.strip(req.headers['API-KEY'])) == 0:
828
            access_control(req)
829
        else:
830
            api_key_control(req)
831
        if not id_.isdigit() or int(id_) <= 0:
832
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
833
                                   description='API.INVALID_STORE_ID')
834
835
        cnx = mysql.connector.connect(**config.myems_system_db)
836
        cursor = cnx.cursor()
837
838
        cursor.execute(" SELECT name "
839
                       " FROM tbl_stores "
840
                       " WHERE id = %s ", (id_,))
841
        if cursor.fetchone() is None:
842
            cursor.close()
843
            cnx.close()
844
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
845
                                   description='API.STORE_NOT_FOUND')
846
847
        query = (" SELECT id, name, uuid "
848
                 " FROM tbl_energy_categories ")
849
        cursor.execute(query)
850
        rows_energy_categories = cursor.fetchall()
851
852
        energy_category_dict = dict()
853
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
854
            for row in rows_energy_categories:
855
                energy_category_dict[row[0]] = {"id": row[0],
856
                                                "name": row[1],
857
                                                "uuid": row[2]}
858
859
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
860
                 " FROM tbl_stores s, tbl_stores_offline_meters sm, tbl_offline_meters m "
861
                 " WHERE sm.store_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
862
                 " ORDER BY m.id ")
863
        cursor.execute(query, (id_,))
864
        rows = cursor.fetchall()
865
866
        result = list()
867
        if rows is not None and len(rows) > 0:
868
            for row in rows:
869
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
870
                               "energy_category": energy_category_dict.get(row[3], None)}
871
                result.append(meta_result)
872
873
        resp.text = json.dumps(result)
874
875
    @staticmethod
876
    @user_logger
877
    def on_post(req, resp, id_):
878
        """Handles POST requests"""
879
        admin_control(req)
880
        try:
881
            raw_json = req.stream.read().decode('utf-8')
882
        except Exception as ex:
883
            print(str(ex))
884
            raise falcon.HTTPError(status=falcon.HTTP_400,
885
                                   title='API.BAD_REQUEST',
886
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
887
888
        if not id_.isdigit() or int(id_) <= 0:
889
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
890
                                   description='API.INVALID_STORE_ID')
891
892
        new_values = json.loads(raw_json)
893
894
        if 'offline_meter_id' not in new_values['data'].keys() or \
895
                not isinstance(new_values['data']['offline_meter_id'], int) or \
896
                new_values['data']['offline_meter_id'] <= 0:
897
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
898
                                   description='API.INVALID_OFFLINE_METER_ID')
899
        offline_meter_id = new_values['data']['offline_meter_id']
900
901
        cnx = mysql.connector.connect(**config.myems_system_db)
902
        cursor = cnx.cursor()
903
904
        cursor.execute(" SELECT name "
905
                       " from tbl_stores "
906
                       " WHERE id = %s ", (id_,))
907
        if cursor.fetchone() is None:
908
            cursor.close()
909
            cnx.close()
910
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
911
                                   description='API.STORE_NOT_FOUND')
912
913
        cursor.execute(" SELECT name "
914
                       " FROM tbl_offline_meters "
915
                       " WHERE id = %s ", (offline_meter_id,))
916
        if cursor.fetchone() is None:
917
            cursor.close()
918
            cnx.close()
919
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
920
                                   description='API.OFFLINE_METER_NOT_FOUND')
921
922
        query = (" SELECT id "
923
                 " FROM tbl_stores_offline_meters "
924
                 " WHERE store_id = %s AND offline_meter_id = %s")
925
        cursor.execute(query, (id_, offline_meter_id,))
926
        if cursor.fetchone() is not None:
927
            cursor.close()
928
            cnx.close()
929
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
930
                                   description='API.STORE_OFFLINE_METER_RELATION_EXISTS')
931
932
        add_row = (" INSERT INTO tbl_stores_offline_meters (store_id, offline_meter_id) "
933
                   " VALUES (%s, %s) ")
934
        cursor.execute(add_row, (id_, offline_meter_id,))
935
        cnx.commit()
936
        cursor.close()
937
        cnx.close()
938
939
        resp.status = falcon.HTTP_201
940
        resp.location = '/stores/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
941
942
943
class StoreOfflineMeterItem:
944
    def __init__(self):
945
        pass
946
947
    @staticmethod
948
    def on_options(req, resp, id_, mid):
949
        _ = req
950
        resp.status = falcon.HTTP_200
951
        _ = id_
952
953
    @staticmethod
954
    @user_logger
955
    def on_delete(req, resp, id_, mid):
956
        admin_control(req)
957
        if not id_.isdigit() or int(id_) <= 0:
958
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
959
                                   description='API.INVALID_STORE_ID')
960
961
        if not mid.isdigit() or int(mid) <= 0:
962
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
963
                                   description='API.INVALID_OFFLINE_METER_ID')
964
965
        cnx = mysql.connector.connect(**config.myems_system_db)
966
        cursor = cnx.cursor()
967
968
        cursor.execute(" SELECT name "
969
                       " FROM tbl_stores "
970
                       " WHERE id = %s ", (id_,))
971
        if cursor.fetchone() is None:
972
            cursor.close()
973
            cnx.close()
974
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
975
                                   description='API.STORE_NOT_FOUND')
976
977
        cursor.execute(" SELECT name "
978
                       " FROM tbl_offline_meters "
979
                       " WHERE id = %s ", (mid,))
980
        if cursor.fetchone() is None:
981
            cursor.close()
982
            cnx.close()
983
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
984
                                   description='API.OFFLINE_METER_NOT_FOUND')
985
986
        cursor.execute(" SELECT id "
987
                       " FROM tbl_stores_offline_meters "
988
                       " WHERE store_id = %s AND offline_meter_id = %s ", (id_, mid))
989
        if cursor.fetchone() is None:
990
            cursor.close()
991
            cnx.close()
992
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
993
                                   description='API.STORE_OFFLINE_METER_RELATION_NOT_FOUND')
994
995
        cursor.execute(" DELETE FROM tbl_stores_offline_meters "
996
                       " WHERE store_id = %s AND offline_meter_id = %s ", (id_, mid))
997
        cnx.commit()
998
999
        cursor.close()
1000
        cnx.close()
1001
1002
        resp.status = falcon.HTTP_204
1003
1004
1005 View Code Duplication
class StorePointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1006
    def __init__(self):
1007
        pass
1008
1009
    @staticmethod
1010
    def on_options(req, resp, id_):
1011
        _ = req
1012
        resp.status = falcon.HTTP_200
1013
        _ = id_
1014
1015
    @staticmethod
1016
    def on_get(req, resp, id_):
1017
        if 'API-KEY' not in req.headers or \
1018
                not isinstance(req.headers['API-KEY'], str) or \
1019
                len(str.strip(req.headers['API-KEY'])) == 0:
1020
            access_control(req)
1021
        else:
1022
            api_key_control(req)
1023
        if not id_.isdigit() or int(id_) <= 0:
1024
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1025
                                   description='API.INVALID_STORE_ID')
1026
1027
        cnx = mysql.connector.connect(**config.myems_system_db)
1028
        cursor = cnx.cursor()
1029
1030
        cursor.execute(" SELECT name "
1031
                       " FROM tbl_stores "
1032
                       " WHERE id = %s ", (id_,))
1033
        if cursor.fetchone() is None:
1034
            cursor.close()
1035
            cnx.close()
1036
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1037
                                   description='API.STORE_NOT_FOUND')
1038
1039
        query = (" SELECT id, name, uuid "
1040
                 " FROM tbl_data_sources ")
1041
        cursor.execute(query)
1042
        rows_data_sources = cursor.fetchall()
1043
1044
        data_source_dict = dict()
1045
        if rows_data_sources is not None and len(rows_data_sources) > 0:
1046
            for row in rows_data_sources:
1047
                data_source_dict[row[0]] = {"id": row[0],
1048
                                            "name": row[1],
1049
                                            "uuid": row[2]}
1050
1051
        query = (" SELECT p.id, p.name, p.data_source_id "
1052
                 " FROM tbl_stores t, tbl_stores_points tp, tbl_points p "
1053
                 " WHERE tp.store_id = t.id AND p.id = tp.point_id AND t.id = %s "
1054
                 " ORDER BY p.id ")
1055
        cursor.execute(query, (id_,))
1056
        rows = cursor.fetchall()
1057
1058
        result = list()
1059
        if rows is not None and len(rows) > 0:
1060
            for row in rows:
1061
                meta_result = {"id": row[0], "name": row[1], "data_source": data_source_dict.get(row[2], None)}
1062
                result.append(meta_result)
1063
1064
        resp.text = json.dumps(result)
1065
1066
    @staticmethod
1067
    @user_logger
1068
    def on_post(req, resp, id_):
1069
        """Handles POST requests"""
1070
        admin_control(req)
1071
        try:
1072
            raw_json = req.stream.read().decode('utf-8')
1073
        except Exception as ex:
1074
            print(str(ex))
1075
            raise falcon.HTTPError(status=falcon.HTTP_400,
1076
                                   title='API.BAD_REQUEST',
1077
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1078
1079
        if not id_.isdigit() or int(id_) <= 0:
1080
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1081
                                   description='API.INVALID_STORE_ID')
1082
1083
        new_values = json.loads(raw_json)
1084
1085
        if 'point_id' not in new_values['data'].keys() or \
1086
                not isinstance(new_values['data']['point_id'], int) or \
1087
                new_values['data']['point_id'] <= 0:
1088
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1089
                                   description='API.INVALID_POINT_ID')
1090
        point_id = new_values['data']['point_id']
1091
1092
        cnx = mysql.connector.connect(**config.myems_system_db)
1093
        cursor = cnx.cursor()
1094
1095
        cursor.execute(" SELECT name "
1096
                       " from tbl_stores "
1097
                       " WHERE id = %s ", (id_,))
1098
        if cursor.fetchone() is None:
1099
            cursor.close()
1100
            cnx.close()
1101
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1102
                                   description='API.STORE_NOT_FOUND')
1103
1104
        cursor.execute(" SELECT name "
1105
                       " FROM tbl_points "
1106
                       " WHERE id = %s ", (point_id,))
1107
        if cursor.fetchone() is None:
1108
            cursor.close()
1109
            cnx.close()
1110
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1111
                                   description='API.POINT_NOT_FOUND')
1112
1113
        query = (" SELECT id "
1114
                 " FROM tbl_stores_points "
1115
                 " WHERE store_id = %s AND point_id = %s")
1116
        cursor.execute(query, (id_, point_id,))
1117
        if cursor.fetchone() is not None:
1118
            cursor.close()
1119
            cnx.close()
1120
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1121
                                   description='API.STORE_POINT_RELATION_EXISTS')
1122
1123
        add_row = (" INSERT INTO tbl_stores_points (store_id, point_id) "
1124
                   " VALUES (%s, %s) ")
1125
        cursor.execute(add_row, (id_, point_id,))
1126
        cnx.commit()
1127
        cursor.close()
1128
        cnx.close()
1129
1130
        resp.status = falcon.HTTP_201
1131
        resp.location = '/stores/' + str(id_) + '/points/' + str(point_id)
1132
1133
1134
class StorePointItem:
1135
    def __init__(self):
1136
        pass
1137
1138
    @staticmethod
1139
    def on_options(req, resp, id_, pid):
1140
        _ = req
1141
        resp.status = falcon.HTTP_200
1142
        _ = id_
1143
1144
    @staticmethod
1145
    @user_logger
1146
    def on_delete(req, resp, id_, pid):
1147
        admin_control(req)
1148
        if not id_.isdigit() or int(id_) <= 0:
1149
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1150
                                   description='API.INVALID_STORE_ID')
1151
1152
        if not pid.isdigit() or int(pid) <= 0:
1153
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1154
                                   description='API.INVALID_POINT_ID')
1155
1156
        cnx = mysql.connector.connect(**config.myems_system_db)
1157
        cursor = cnx.cursor()
1158
1159
        cursor.execute(" SELECT name "
1160
                       " FROM tbl_stores "
1161
                       " WHERE id = %s ", (id_,))
1162
        if cursor.fetchone() is None:
1163
            cursor.close()
1164
            cnx.close()
1165
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1166
                                   description='API.STORE_NOT_FOUND')
1167
1168
        cursor.execute(" SELECT name "
1169
                       " FROM tbl_points "
1170
                       " WHERE id = %s ", (pid,))
1171
        if cursor.fetchone() is None:
1172
            cursor.close()
1173
            cnx.close()
1174
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1175
                                   description='API.POINT_NOT_FOUND')
1176
1177
        cursor.execute(" SELECT id "
1178
                       " FROM tbl_stores_points "
1179
                       " WHERE store_id = %s AND point_id = %s ", (id_, pid))
1180
        if cursor.fetchone() is None:
1181
            cursor.close()
1182
            cnx.close()
1183
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1184
                                   description='API.STORE_POINT_RELATION_NOT_FOUND')
1185
1186
        cursor.execute(" DELETE FROM tbl_stores_points "
1187
                       " WHERE store_id = %s AND point_id = %s ", (id_, pid))
1188
        cnx.commit()
1189
1190
        cursor.close()
1191
        cnx.close()
1192
1193
        resp.status = falcon.HTTP_204
1194
1195
1196 View Code Duplication
class StoreSensorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1197
    def __init__(self):
1198
        pass
1199
1200
    @staticmethod
1201
    def on_options(req, resp, id_):
1202
        _ = req
1203
        resp.status = falcon.HTTP_200
1204
        _ = id_
1205
1206
    @staticmethod
1207
    def on_get(req, resp, id_):
1208
        if 'API-KEY' not in req.headers or \
1209
                not isinstance(req.headers['API-KEY'], str) or \
1210
                len(str.strip(req.headers['API-KEY'])) == 0:
1211
            access_control(req)
1212
        else:
1213
            api_key_control(req)
1214
        if not id_.isdigit() or int(id_) <= 0:
1215
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1216
                                   description='API.INVALID_STORE_ID')
1217
1218
        cnx = mysql.connector.connect(**config.myems_system_db)
1219
        cursor = cnx.cursor()
1220
1221
        cursor.execute(" SELECT name "
1222
                       " FROM tbl_stores "
1223
                       " WHERE id = %s ", (id_,))
1224
        if cursor.fetchone() is None:
1225
            cursor.close()
1226
            cnx.close()
1227
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1228
                                   description='API.STORE_NOT_FOUND')
1229
1230
        query = (" SELECT s.id, s.name, s.uuid "
1231
                 " FROM tbl_stores t, tbl_stores_sensors ts, tbl_sensors s "
1232
                 " WHERE ts.store_id = t.id AND s.id = ts.sensor_id AND t.id = %s "
1233
                 " ORDER BY s.id ")
1234
        cursor.execute(query, (id_,))
1235
        rows = cursor.fetchall()
1236
1237
        result = list()
1238
        if rows is not None and len(rows) > 0:
1239
            for row in rows:
1240
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1241
                result.append(meta_result)
1242
1243
        resp.text = json.dumps(result)
1244
1245
    @staticmethod
1246
    @user_logger
1247
    def on_post(req, resp, id_):
1248
        """Handles POST requests"""
1249
        admin_control(req)
1250
        try:
1251
            raw_json = req.stream.read().decode('utf-8')
1252
        except Exception as ex:
1253
            print(str(ex))
1254
            raise falcon.HTTPError(status=falcon.HTTP_400,
1255
                                   title='API.BAD_REQUEST',
1256
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1257
1258
        if not id_.isdigit() or int(id_) <= 0:
1259
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1260
                                   description='API.INVALID_STORE_ID')
1261
1262
        new_values = json.loads(raw_json)
1263
1264
        if 'sensor_id' not in new_values['data'].keys() or \
1265
                not isinstance(new_values['data']['sensor_id'], int) or \
1266
                new_values['data']['sensor_id'] <= 0:
1267
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1268
                                   description='API.INVALID_SENSOR_ID')
1269
        sensor_id = new_values['data']['sensor_id']
1270
1271
        cnx = mysql.connector.connect(**config.myems_system_db)
1272
        cursor = cnx.cursor()
1273
1274
        cursor.execute(" SELECT name "
1275
                       " from tbl_stores "
1276
                       " WHERE id = %s ", (id_,))
1277
        if cursor.fetchone() is None:
1278
            cursor.close()
1279
            cnx.close()
1280
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1281
                                   description='API.STORE_NOT_FOUND')
1282
1283
        cursor.execute(" SELECT name "
1284
                       " FROM tbl_sensors "
1285
                       " WHERE id = %s ", (sensor_id,))
1286
        if cursor.fetchone() is None:
1287
            cursor.close()
1288
            cnx.close()
1289
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1290
                                   description='API.SENSOR_NOT_FOUND')
1291
1292
        query = (" SELECT id "
1293
                 " FROM tbl_stores_sensors "
1294
                 " WHERE store_id = %s AND sensor_id = %s")
1295
        cursor.execute(query, (id_, sensor_id,))
1296
        if cursor.fetchone() is not None:
1297
            cursor.close()
1298
            cnx.close()
1299
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1300
                                   description='API.STORE_SENSOR_RELATION_EXISTS')
1301
1302
        add_row = (" INSERT INTO tbl_stores_sensors (store_id, sensor_id) "
1303
                   " VALUES (%s, %s) ")
1304
        cursor.execute(add_row, (id_, sensor_id,))
1305
        cnx.commit()
1306
        cursor.close()
1307
        cnx.close()
1308
1309
        resp.status = falcon.HTTP_201
1310
        resp.location = '/stores/' + str(id_) + '/sensors/' + str(sensor_id)
1311
1312
1313
class StoreSensorItem:
1314
    def __init__(self):
1315
        pass
1316
1317
    @staticmethod
1318
    def on_options(req, resp, id_, sid):
1319
        _ = req
1320
        resp.status = falcon.HTTP_200
1321
        _ = id_
1322
1323
    @staticmethod
1324
    @user_logger
1325
    def on_delete(req, resp, id_, sid):
1326
        admin_control(req)
1327
        if not id_.isdigit() or int(id_) <= 0:
1328
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1329
                                   description='API.INVALID_STORE_ID')
1330
1331
        if not sid.isdigit() or int(sid) <= 0:
1332
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1333
                                   description='API.INVALID_SENSOR_ID')
1334
1335
        cnx = mysql.connector.connect(**config.myems_system_db)
1336
        cursor = cnx.cursor()
1337
1338
        cursor.execute(" SELECT name "
1339
                       " FROM tbl_stores "
1340
                       " WHERE id = %s ", (id_,))
1341
        if cursor.fetchone() is None:
1342
            cursor.close()
1343
            cnx.close()
1344
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1345
                                   description='API.STORE_NOT_FOUND')
1346
1347
        cursor.execute(" SELECT name "
1348
                       " FROM tbl_sensors "
1349
                       " WHERE id = %s ", (sid,))
1350
        if cursor.fetchone() is None:
1351
            cursor.close()
1352
            cnx.close()
1353
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1354
                                   description='API.SENSOR_NOT_FOUND')
1355
1356
        cursor.execute(" SELECT id "
1357
                       " FROM tbl_stores_sensors "
1358
                       " WHERE store_id = %s AND sensor_id = %s ", (id_, sid))
1359
        if cursor.fetchone() is None:
1360
            cursor.close()
1361
            cnx.close()
1362
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1363
                                   description='API.STORE_SENSOR_RELATION_NOT_FOUND')
1364
1365
        cursor.execute(" DELETE FROM tbl_stores_sensors WHERE store_id = %s AND sensor_id = %s ", (id_, sid))
1366
        cnx.commit()
1367
1368
        cursor.close()
1369
        cnx.close()
1370
1371
        resp.status = falcon.HTTP_204
1372
1373
1374 View Code Duplication
class StoreVirtualMeterCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1375
    def __init__(self):
1376
        pass
1377
1378
    @staticmethod
1379
    def on_options(req, resp, id_):
1380
        _ = req
1381
        resp.status = falcon.HTTP_200
1382
        _ = id_
1383
1384
    @staticmethod
1385
    def on_get(req, resp, id_):
1386
        if 'API-KEY' not in req.headers or \
1387
                not isinstance(req.headers['API-KEY'], str) or \
1388
                len(str.strip(req.headers['API-KEY'])) == 0:
1389
            access_control(req)
1390
        else:
1391
            api_key_control(req)
1392
        if not id_.isdigit() or int(id_) <= 0:
1393
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1394
                                   description='API.INVALID_STORE_ID')
1395
1396
        cnx = mysql.connector.connect(**config.myems_system_db)
1397
        cursor = cnx.cursor()
1398
1399
        cursor.execute(" SELECT name "
1400
                       " FROM tbl_stores "
1401
                       " WHERE id = %s ", (id_,))
1402
        if cursor.fetchone() is None:
1403
            cursor.close()
1404
            cnx.close()
1405
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1406
                                   description='API.STORE_NOT_FOUND')
1407
1408
        query = (" SELECT id, name, uuid "
1409
                 " FROM tbl_energy_categories ")
1410
        cursor.execute(query)
1411
        rows_energy_categories = cursor.fetchall()
1412
1413
        energy_category_dict = dict()
1414
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1415
            for row in rows_energy_categories:
1416
                energy_category_dict[row[0]] = {"id": row[0],
1417
                                                "name": row[1],
1418
                                                "uuid": row[2]}
1419
1420
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1421
                 " FROM tbl_stores t, tbl_stores_virtual_meters tm, tbl_virtual_meters m "
1422
                 " WHERE tm.store_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s "
1423
                 " ORDER BY m.id ")
1424
        cursor.execute(query, (id_,))
1425
        rows = cursor.fetchall()
1426
1427
        result = list()
1428
        if rows is not None and len(rows) > 0:
1429
            for row in rows:
1430
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1431
                               "energy_category": energy_category_dict.get(row[3], None)}
1432
                result.append(meta_result)
1433
1434
        resp.text = json.dumps(result)
1435
1436
    @staticmethod
1437
    @user_logger
1438
    def on_post(req, resp, id_):
1439
        """Handles POST requests"""
1440
        admin_control(req)
1441
        try:
1442
            raw_json = req.stream.read().decode('utf-8')
1443
        except Exception as ex:
1444
            print(str(ex))
1445
            raise falcon.HTTPError(status=falcon.HTTP_400,
1446
                                   title='API.BAD_REQUEST',
1447
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1448
1449
        if not id_.isdigit() or int(id_) <= 0:
1450
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1451
                                   description='API.INVALID_STORE_ID')
1452
1453
        new_values = json.loads(raw_json)
1454
1455
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1456
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1457
                new_values['data']['virtual_meter_id'] <= 0:
1458
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1459
                                   description='API.INVALID_VIRTUAL_METER_ID')
1460
        virtual_meter_id = new_values['data']['virtual_meter_id']
1461
1462
        cnx = mysql.connector.connect(**config.myems_system_db)
1463
        cursor = cnx.cursor()
1464
1465
        cursor.execute(" SELECT name "
1466
                       " from tbl_stores "
1467
                       " WHERE id = %s ", (id_,))
1468
        if cursor.fetchone() is None:
1469
            cursor.close()
1470
            cnx.close()
1471
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1472
                                   description='API.STORE_NOT_FOUND')
1473
1474
        cursor.execute(" SELECT name "
1475
                       " FROM tbl_virtual_meters "
1476
                       " WHERE id = %s ", (virtual_meter_id,))
1477
        if cursor.fetchone() is None:
1478
            cursor.close()
1479
            cnx.close()
1480
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1481
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1482
1483
        query = (" SELECT id "
1484
                 " FROM tbl_stores_virtual_meters "
1485
                 " WHERE store_id = %s AND virtual_meter_id = %s")
1486
        cursor.execute(query, (id_, virtual_meter_id,))
1487
        if cursor.fetchone() is not None:
1488
            cursor.close()
1489
            cnx.close()
1490
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1491
                                   description='API.STORE_VIRTUAL_METER_RELATION_EXISTS')
1492
1493
        add_row = (" INSERT INTO tbl_stores_virtual_meters (store_id, virtual_meter_id) "
1494
                   " VALUES (%s, %s) ")
1495
        cursor.execute(add_row, (id_, virtual_meter_id,))
1496
        cnx.commit()
1497
        cursor.close()
1498
        cnx.close()
1499
1500
        resp.status = falcon.HTTP_201
1501
        resp.location = '/stores/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1502
1503
1504
class StoreVirtualMeterItem:
1505
    def __init__(self):
1506
        pass
1507
1508
    @staticmethod
1509
    def on_options(req, resp, id_, mid):
1510
        _ = req
1511
        resp.status = falcon.HTTP_200
1512
        _ = id_
1513
1514
    @staticmethod
1515
    @user_logger
1516
    def on_delete(req, resp, id_, mid):
1517
        admin_control(req)
1518
        if not id_.isdigit() or int(id_) <= 0:
1519
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1520
                                   description='API.INVALID_STORE_ID')
1521
1522
        if not mid.isdigit() or int(mid) <= 0:
1523
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1524
                                   description='API.INVALID_VIRTUAL_METER_ID')
1525
1526
        cnx = mysql.connector.connect(**config.myems_system_db)
1527
        cursor = cnx.cursor()
1528
1529
        cursor.execute(" SELECT name "
1530
                       " FROM tbl_stores "
1531
                       " WHERE id = %s ", (id_,))
1532
        if cursor.fetchone() is None:
1533
            cursor.close()
1534
            cnx.close()
1535
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1536
                                   description='API.STORE_NOT_FOUND')
1537
1538
        cursor.execute(" SELECT name "
1539
                       " FROM tbl_virtual_meters "
1540
                       " WHERE id = %s ", (mid,))
1541
        if cursor.fetchone() is None:
1542
            cursor.close()
1543
            cnx.close()
1544
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1545
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1546
1547
        cursor.execute(" SELECT id "
1548
                       " FROM tbl_stores_virtual_meters "
1549
                       " WHERE store_id = %s AND virtual_meter_id = %s ", (id_, mid))
1550
        if cursor.fetchone() is None:
1551
            cursor.close()
1552
            cnx.close()
1553
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1554
                                   description='API.STORE_VIRTUAL_METER_RELATION_NOT_FOUND')
1555
1556
        cursor.execute(" DELETE FROM tbl_stores_virtual_meters "
1557
                       " WHERE store_id = %s AND virtual_meter_id = %s ", (id_, mid))
1558
        cnx.commit()
1559
1560
        cursor.close()
1561
        cnx.close()
1562
1563
        resp.status = falcon.HTTP_204
1564
1565
1566 View Code Duplication
class StoreWorkingCalendarCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1567
    def __init__(self):
1568
        pass
1569
1570
    @staticmethod
1571
    def on_options(req, resp, id_):
1572
        _ = req
1573
        resp.status = falcon.HTTP_200
1574
        _ = id_
1575
1576
    @staticmethod
1577
    def on_get(req, resp, id_):
1578
        if 'API-KEY' not in req.headers or \
1579
                not isinstance(req.headers['API-KEY'], str) or \
1580
                len(str.strip(req.headers['API-KEY'])) == 0:
1581
            access_control(req)
1582
        else:
1583
            api_key_control(req)
1584
        if not id_.isdigit() or int(id_) <= 0:
1585
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1586
                                   description='API.INVALID_STORE_ID')
1587
1588
        cnx = mysql.connector.connect(**config.myems_system_db)
1589
        cursor = cnx.cursor()
1590
1591
        cursor.execute(" SELECT name "
1592
                       " FROM tbl_stores "
1593
                       " WHERE id = %s ", (id_,))
1594
        if cursor.fetchone() is None:
1595
            cursor.close()
1596
            cnx.close()
1597
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1598
                                   description='API.STORE_NOT_FOUND')
1599
1600
        query = (" SELECT wc.id, wc.name, wc.description "
1601
                 " FROM tbl_stores s, tbl_stores_working_calendars swc, tbl_working_calendars wc "
1602
                 " WHERE swc.store_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
1603
                 " ORDER BY wc.id ")
1604
        cursor.execute(query, (id_,))
1605
        rows = cursor.fetchall()
1606
1607
        result = list()
1608
        if rows is not None and len(rows) > 0:
1609
            for row in rows:
1610
                meta_result = {"id": row[0], "name": row[1], "description": row[2]}
1611
                result.append(meta_result)
1612
1613
        resp.text = json.dumps(result)
1614
1615
    @staticmethod
1616
    @user_logger
1617
    def on_post(req, resp, id_):
1618
        """Handles POST requests"""
1619
        admin_control(req)
1620
        try:
1621
            raw_json = req.stream.read().decode('utf-8')
1622
        except Exception as ex:
1623
            print(str(ex))
1624
            raise falcon.HTTPError(status=falcon.HTTP_400,
1625
                                   title='API.BAD_REQUEST',
1626
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1627
1628
        if not id_.isdigit() or int(id_) <= 0:
1629
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1630
                                   description='API.INVALID_STORE_ID')
1631
1632
        new_values = json.loads(raw_json)
1633
1634
        if 'working_calendar_id' not in new_values['data'].keys() or \
1635
                not isinstance(new_values['data']['working_calendar_id'], int) or \
1636
                new_values['data']['working_calendar_id'] <= 0:
1637
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1638
                                   description='API.INVALID_WORKING_CALENDAR_ID')
1639
        working_calendar_id = new_values['data']['working_calendar_id']
1640
1641
        cnx = mysql.connector.connect(**config.myems_system_db)
1642
        cursor = cnx.cursor()
1643
1644
        cursor.execute(" SELECT name "
1645
                       " from tbl_stores "
1646
                       " WHERE id = %s ", (id_,))
1647
        if cursor.fetchone() is None:
1648
            cursor.close()
1649
            cnx.close()
1650
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1651
                                   description='API.STORE_NOT_FOUND')
1652
1653
        cursor.execute(" SELECT name "
1654
                       " FROM tbl_working_calendars "
1655
                       " WHERE id = %s ", (working_calendar_id,))
1656
        if cursor.fetchone() is None:
1657
            cursor.close()
1658
            cnx.close()
1659
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1660
                                   description='API.WORKING_CALENDAR_NOT_FOUND')
1661
1662
        query = (" SELECT id "
1663
                 " FROM tbl_stores_working_calendars "
1664
                 " WHERE store_id = %s AND working_calendar_id = %s")
1665
        cursor.execute(query, (id_, working_calendar_id,))
1666
        if cursor.fetchone() is not None:
1667
            cursor.close()
1668
            cnx.close()
1669
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1670
                                   description='API.STORE_WORKING_CALENDAR_RELATION_EXISTS')
1671
1672
        add_row = (" INSERT INTO tbl_stores_working_calendars (store_id, working_calendar_id) "
1673
                   " VALUES (%s, %s) ")
1674
        cursor.execute(add_row, (id_, working_calendar_id,))
1675
        cnx.commit()
1676
        cursor.close()
1677
        cnx.close()
1678
1679
        resp.status = falcon.HTTP_201
1680
        resp.location = '/stores/' + str(id_) + '/workingcalendars/' + str(working_calendar_id)
1681
1682
1683
class StoreWorkingCalendarItem:
1684
    def __init__(self):
1685
        pass
1686
1687
    @staticmethod
1688
    def on_options(req, resp, id_, wcid):
1689
        _ = req
1690
        resp.status = falcon.HTTP_200
1691
        _ = id_
1692
1693
    @staticmethod
1694
    @user_logger
1695
    def on_delete(req, resp, id_, wcid):
1696
        admin_control(req)
1697
        if not id_.isdigit() or int(id_) <= 0:
1698
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1699
                                   description='API.INVALID_STORE_ID')
1700
1701
        if not wcid.isdigit() or int(wcid) <= 0:
1702
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1703
                                   description='API.INVALID_WORKING_CALENDAR_ID')
1704
1705
        cnx = mysql.connector.connect(**config.myems_system_db)
1706
        cursor = cnx.cursor()
1707
1708
        cursor.execute(" SELECT name "
1709
                       " FROM tbl_stores "
1710
                       " WHERE id = %s ", (id_,))
1711
        if cursor.fetchone() is None:
1712
            cursor.close()
1713
            cnx.close()
1714
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1715
                                   description='API.STORE_NOT_FOUND')
1716
1717
        cursor.execute(" SELECT name "
1718
                       " FROM tbl_working_calendars "
1719
                       " WHERE id = %s ", (wcid,))
1720
        if cursor.fetchone() is None:
1721
            cursor.close()
1722
            cnx.close()
1723
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1724
                                   description='API.WORKING_CALENDAR_NOT_FOUND')
1725
1726
        cursor.execute(" SELECT id "
1727
                       " FROM tbl_stores_working_calendars "
1728
                       " WHERE store_id = %s AND working_calendar_id = %s ", (id_, wcid))
1729
        if cursor.fetchone() is None:
1730
            cursor.close()
1731
            cnx.close()
1732
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1733
                                   description='API.STORE_WORKING_CALENDAR_RELATION_NOT_FOUND')
1734
1735
        cursor.execute(" DELETE FROM tbl_stores_working_calendars "
1736
                       " WHERE store_id = %s AND working_calendar_id = %s ", (id_, wcid))
1737
        cnx.commit()
1738
1739
        cursor.close()
1740
        cnx.close()
1741
1742
        resp.status = falcon.HTTP_204
1743
1744
1745 View Code Duplication
class StoreCommandCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1746
    def __init__(self):
1747
        pass
1748
1749
    @staticmethod
1750
    def on_options(req, resp, id_):
1751
        _ = req
1752
        resp.status = falcon.HTTP_200
1753
        _ = id_
1754
1755
    @staticmethod
1756
    def on_get(req, resp, id_):
1757
        if 'API-KEY' not in req.headers or \
1758
                not isinstance(req.headers['API-KEY'], str) or \
1759
                len(str.strip(req.headers['API-KEY'])) == 0:
1760
            access_control(req)
1761
        else:
1762
            api_key_control(req)
1763
        if not id_.isdigit() or int(id_) <= 0:
1764
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1765
                                   description='API.INVALID_STORE_ID')
1766
1767
        cnx = mysql.connector.connect(**config.myems_system_db)
1768
        cursor = cnx.cursor()
1769
1770
        cursor.execute(" SELECT name "
1771
                       " FROM tbl_stores "
1772
                       " WHERE id = %s ", (id_,))
1773
        if cursor.fetchone() is None:
1774
            cursor.close()
1775
            cnx.close()
1776
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1777
                                   description='API.STORE_NOT_FOUND')
1778
1779
        query = (" SELECT c.id, c.name, c.uuid "
1780
                 " FROM tbl_stores s, tbl_stores_commands sc, tbl_commands c "
1781
                 " WHERE sc.store_id = s.id AND c.id = sc.command_id AND s.id = %s "
1782
                 " ORDER BY c.id ")
1783
        cursor.execute(query, (id_,))
1784
        rows = cursor.fetchall()
1785
1786
        result = list()
1787
        if rows is not None and len(rows) > 0:
1788
            for row in rows:
1789
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1790
                result.append(meta_result)
1791
1792
        resp.text = json.dumps(result)
1793
1794
    @staticmethod
1795
    @user_logger
1796
    def on_post(req, resp, id_):
1797
        """Handles POST requests"""
1798
        admin_control(req)
1799
        try:
1800
            raw_json = req.stream.read().decode('utf-8')
1801
        except Exception as ex:
1802
            print(str(ex))
1803
            raise falcon.HTTPError(status=falcon.HTTP_400,
1804
                                   title='API.BAD_REQUEST',
1805
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1806
1807
        if not id_.isdigit() or int(id_) <= 0:
1808
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1809
                                   description='API.INVALID_STORE_ID')
1810
1811
        new_values = json.loads(raw_json)
1812
1813
        if 'command_id' not in new_values['data'].keys() or \
1814
                not isinstance(new_values['data']['command_id'], int) or \
1815
                new_values['data']['command_id'] <= 0:
1816
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1817
                                   description='API.INVALID_COMMAND_ID')
1818
        command_id = new_values['data']['command_id']
1819
1820
        cnx = mysql.connector.connect(**config.myems_system_db)
1821
        cursor = cnx.cursor()
1822
1823
        cursor.execute(" SELECT name "
1824
                       " from tbl_stores "
1825
                       " WHERE id = %s ", (id_,))
1826
        if cursor.fetchone() is None:
1827
            cursor.close()
1828
            cnx.close()
1829
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1830
                                   description='API.STORE_NOT_FOUND')
1831
1832
        cursor.execute(" SELECT name "
1833
                       " FROM tbl_commands "
1834
                       " WHERE id = %s ", (command_id,))
1835
        if cursor.fetchone() is None:
1836
            cursor.close()
1837
            cnx.close()
1838
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1839
                                   description='API.COMMAND_NOT_FOUND')
1840
1841
        query = (" SELECT id "
1842
                 " FROM tbl_stores_commands "
1843
                 " WHERE store_id = %s AND command_id = %s")
1844
        cursor.execute(query, (id_, command_id,))
1845
        if cursor.fetchone() is not None:
1846
            cursor.close()
1847
            cnx.close()
1848
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1849
                                   description='API.STORE_COMMAND_RELATION_EXISTS')
1850
1851
        add_row = (" INSERT INTO tbl_stores_commands (store_id, command_id) "
1852
                   " VALUES (%s, %s) ")
1853
        cursor.execute(add_row, (id_, command_id,))
1854
        cnx.commit()
1855
        cursor.close()
1856
        cnx.close()
1857
1858
        resp.status = falcon.HTTP_201
1859
        resp.location = '/stores/' + str(id_) + '/commands/' + str(command_id)
1860
1861
1862
class StoreCommandItem:
1863
    def __init__(self):
1864
        pass
1865
1866
    @staticmethod
1867
    def on_options(req, resp, id_, cid):
1868
        _ = req
1869
        resp.status = falcon.HTTP_200
1870
        _ = id_
1871
1872
    @staticmethod
1873
    @user_logger
1874
    def on_delete(req, resp, id_, cid):
1875
        admin_control(req)
1876
        if not id_.isdigit() or int(id_) <= 0:
1877
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1878
                                   description='API.INVALID_STORE_ID')
1879
1880
        if not cid.isdigit() or int(cid) <= 0:
1881
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1882
                                   description='API.INVALID_COMMAND_ID')
1883
1884
        cnx = mysql.connector.connect(**config.myems_system_db)
1885
        cursor = cnx.cursor()
1886
1887
        cursor.execute(" SELECT name "
1888
                       " FROM tbl_stores "
1889
                       " WHERE id = %s ", (id_,))
1890
        if cursor.fetchone() is None:
1891
            cursor.close()
1892
            cnx.close()
1893
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1894
                                   description='API.STORE_NOT_FOUND')
1895
1896
        cursor.execute(" SELECT name "
1897
                       " FROM tbl_commands "
1898
                       " WHERE id = %s ", (cid,))
1899
        if cursor.fetchone() is None:
1900
            cursor.close()
1901
            cnx.close()
1902
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1903
                                   description='API.COMMAND_NOT_FOUND')
1904
1905
        cursor.execute(" SELECT id "
1906
                       " FROM tbl_stores_commands "
1907
                       " WHERE store_id = %s AND command_id = %s ", (id_, cid))
1908
        if cursor.fetchone() is None:
1909
            cursor.close()
1910
            cnx.close()
1911
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1912
                                   description='API.STORE_COMMAND_RELATION_NOT_FOUND')
1913
1914
        cursor.execute(" DELETE FROM tbl_stores_commands WHERE store_id = %s AND command_id = %s ", (id_, cid))
1915
        cnx.commit()
1916
1917
        cursor.close()
1918
        cnx.close()
1919
1920
        resp.status = falcon.HTTP_204
1921
1922
1923
class StoreExport:
1924
    def __init__(self):
1925
        pass
1926
1927
    @staticmethod
1928
    def on_options(req, resp, id_):
1929
        _ = req
1930
        resp.status = falcon.HTTP_200
1931
        _ = id_
1932
1933
    @staticmethod
1934
    def on_get(req, resp, id_):
1935
        if 'API-KEY' not in req.headers or \
1936
                not isinstance(req.headers['API-KEY'], str) or \
1937
                len(str.strip(req.headers['API-KEY'])) == 0:
1938
            access_control(req)
1939
        else:
1940
            api_key_control(req)
1941
        if not id_.isdigit() or int(id_) <= 0:
1942
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1943
                                   description='API.INVALID_STORE_ID')
1944
1945
        cnx = mysql.connector.connect(**config.myems_system_db)
1946
        cursor = cnx.cursor()
1947
1948
        query = (" SELECT id, name, uuid "
1949
                 " FROM tbl_store_types ")
1950
        cursor.execute(query)
1951
        rows_store_types = cursor.fetchall()
1952
1953
        store_type_dict = dict()
1954
        if rows_store_types is not None and len(rows_store_types) > 0:
1955
            for row in rows_store_types:
1956
                store_type_dict[row[0]] = {"id": row[0],
1957
                                           "name": row[1],
1958
                                           "uuid": row[2]}
1959
1960
        query = (" SELECT id, name, uuid "
1961
                 " FROM tbl_contacts ")
1962
        cursor.execute(query)
1963
        rows_contacts = cursor.fetchall()
1964
1965
        contact_dict = dict()
1966
        if rows_contacts is not None and len(rows_contacts) > 0:
1967
            for row in rows_contacts:
1968
                contact_dict[row[0]] = {"id": row[0],
1969
                                        "name": row[1],
1970
                                        "uuid": row[2]}
1971
1972
        query = (" SELECT id, name, uuid "
1973
                 " FROM tbl_cost_centers ")
1974
        cursor.execute(query)
1975
        rows_cost_centers = cursor.fetchall()
1976
1977
        cost_center_dict = dict()
1978
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
1979
            for row in rows_cost_centers:
1980
                cost_center_dict[row[0]] = {"id": row[0],
1981
                                            "name": row[1],
1982
                                            "uuid": row[2]}
1983
1984
        query = (" SELECT id, name, uuid, "
1985
                 "        address, latitude, longitude, area, store_type_id,"
1986
                 "        is_input_counted, "
1987
                 "        contact_id, cost_center_id, description "
1988
                 " FROM tbl_stores "
1989
                 " WHERE id = %s ")
1990
        cursor.execute(query, (id_,))
1991
        row = cursor.fetchone()
1992
1993
        if row is None:
1994
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1995
                                   description='API.STORE_NOT_FOUND')
1996
        else:
1997
            meta_result = {"id": row[0],
1998
                           "name": row[1],
1999
                           "uuid": row[2],
2000
                           "address": row[3],
2001
                           "latitude": row[4],
2002
                           "longitude": row[5],
2003
                           "area": row[6],
2004
                           "store_type": store_type_dict.get(row[7], None),
2005
                           "is_input_counted": bool(row[8]),
2006
                           "contact": contact_dict.get(row[9], None),
2007
                           "cost_center": cost_center_dict.get(row[10], None),
2008
                           "description": row[11],
2009
                           "commands": None,
2010
                           "meters": None,
2011
                           "offline_meters": None,
2012
                           "virtual_meters": None,
2013
                           "points": None,
2014
                           "sensors": None,
2015
                           "working_calendars": None
2016
                           }
2017
            query = (" SELECT c.id, c.name, c.uuid "
2018
                     " FROM tbl_stores s, tbl_stores_commands sc, tbl_commands c "
2019
                     " WHERE sc.store_id = s.id AND c.id = sc.command_id AND s.id = %s "
2020
                     " ORDER BY c.id ")
2021
            cursor.execute(query, (id_,))
2022
            rows = cursor.fetchall()
2023
2024
            command_result = list()
2025
            if rows is not None and len(rows) > 0:
2026
                for row in rows:
2027
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
2028
                    command_result.append(result)
2029
                meta_result['commands'] = command_result
2030
2031
            query = (" SELECT id, name, uuid "
2032
                     " FROM tbl_energy_categories ")
2033
            cursor.execute(query)
2034
            rows_energy_categories = cursor.fetchall()
2035
2036
            energy_category_dict = dict()
2037
            if rows_energy_categories is not None and len(rows_energy_categories) > 0:
2038
                for row in rows_energy_categories:
2039
                    energy_category_dict[row[0]] = {"id": row[0],
2040
                                                    "name": row[1],
2041
                                                    "uuid": row[2]}
2042
2043
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
2044
                     " FROM tbl_stores t, tbl_stores_meters tm, tbl_meters m "
2045
                     " WHERE tm.store_id = t.id AND m.id = tm.meter_id AND t.id = %s "
2046
                     " ORDER BY m.id ")
2047
            cursor.execute(query, (id_,))
2048
            rows = cursor.fetchall()
2049
2050
            meter_result = list()
2051
            if rows is not None and len(rows) > 0:
2052
                for row in rows:
2053
                    result = {"id": row[0], "name": row[1], "uuid": row[2],
2054
                              "energy_category": energy_category_dict.get(row[3], None)}
2055
                    meter_result.append(result)
2056
                meta_result['meters'] = meter_result
2057
2058
            query = (" SELECT id, name, uuid "
2059
                     " FROM tbl_energy_categories ")
2060
            cursor.execute(query)
2061
            rows_energy_categories = cursor.fetchall()
2062
2063
            energy_category_dict = dict()
2064
            if rows_energy_categories is not None and len(rows_energy_categories) > 0:
2065
                for row in rows_energy_categories:
2066
                    energy_category_dict[row[0]] = {"id": row[0],
2067
                                                    "name": row[1],
2068
                                                    "uuid": row[2]}
2069
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
2070
                     " FROM tbl_stores s, tbl_stores_offline_meters sm, tbl_offline_meters m "
2071
                     " WHERE sm.store_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
2072
                     " ORDER BY m.id ")
2073
            cursor.execute(query, (id_,))
2074
            rows = cursor.fetchall()
2075
2076
            offlinemeter_result = list()
2077
            if rows is not None and len(rows) > 0:
2078
                for row in rows:
2079
                    result = {"id": row[0], "name": row[1], "uuid": row[2],
2080
                              "energy_category": energy_category_dict.get(row[3], None)}
2081
                    offlinemeter_result.append(result)
2082
                meta_result['offline_meters'] = offlinemeter_result
2083
            query = (" SELECT id, name, uuid "
2084
                     " FROM tbl_energy_categories ")
2085
            cursor.execute(query)
2086
            rows_energy_categories = cursor.fetchall()
2087
2088
            energy_category_dict = dict()
2089
            if rows_energy_categories is not None and len(rows_energy_categories) > 0:
2090
                for row in rows_energy_categories:
2091
                    energy_category_dict[row[0]] = {"id": row[0],
2092
                                                    "name": row[1],
2093
                                                    "uuid": row[2]}
2094
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
2095
                     " FROM tbl_stores t, tbl_stores_virtual_meters tm, tbl_virtual_meters m "
2096
                     " WHERE tm.store_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s "
2097
                     " ORDER BY m.id ")
2098
            cursor.execute(query, (id_,))
2099
            rows = cursor.fetchall()
2100
2101
            virtualmeter_result = list()
2102
            if rows is not None and len(rows) > 0:
2103
                for row in rows:
2104
                    result = {"id": row[0], "name": row[1], "uuid": row[2],
2105
                              "energy_category": energy_category_dict.get(row[3], None)}
2106
                    virtualmeter_result.append(result)
2107
                meta_result['virtual_meters'] = virtualmeter_result
2108
            query = (" SELECT id, name, uuid "
2109
                     " FROM tbl_data_sources ")
2110
            cursor.execute(query)
2111
            rows_data_sources = cursor.fetchall()
2112
2113
            data_source_dict = dict()
2114
            if rows_data_sources is not None and len(rows_data_sources) > 0:
2115
                for row in rows_data_sources:
2116
                    data_source_dict[row[0]] = {"id": row[0],
2117
                                                "name": row[1],
2118
                                                "uuid": row[2]}
2119
2120
            query = (" SELECT p.id, p.name, p.data_source_id "
2121
                     " FROM tbl_stores t, tbl_stores_points tp, tbl_points p "
2122
                     " WHERE tp.store_id = t.id AND p.id = tp.point_id AND t.id = %s "
2123
                     " ORDER BY p.id ")
2124
            cursor.execute(query, (id_,))
2125
            rows = cursor.fetchall()
2126
2127
            point_result = list()
2128
            if rows is not None and len(rows) > 0:
2129
                for row in rows:
2130
                    result = {"id": row[0], "name": row[1], "data_source": data_source_dict.get(row[2], None)}
2131
                    point_result.append(result)
2132
                meta_result['points'] = point_result
2133
            query = (" SELECT s.id, s.name, s.uuid "
2134
                     " FROM tbl_stores t, tbl_stores_sensors ts, tbl_sensors s "
2135
                     " WHERE ts.store_id = t.id AND s.id = ts.sensor_id AND t.id = %s "
2136
                     " ORDER BY s.id ")
2137
            cursor.execute(query, (id_,))
2138
            rows = cursor.fetchall()
2139
2140
            sensor_result = list()
2141
            if rows is not None and len(rows) > 0:
2142
                for row in rows:
2143
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
2144
                    sensor_result.append(result)
2145
                meta_result['sensors'] = sensor_result
2146
            query = (" SELECT wc.id, wc.name, wc.description "
2147
                     " FROM tbl_stores s, tbl_stores_working_calendars swc, tbl_working_calendars wc "
2148
                     " WHERE swc.store_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
2149
                     " ORDER BY wc.id ")
2150
            cursor.execute(query, (id_,))
2151
            rows = cursor.fetchall()
2152
2153
            workingcalendar_result = list()
2154
            if rows is not None and len(rows) > 0:
2155
                for row in rows:
2156
                    result = {"id": row[0], "name": row[1], "description": row[2]}
2157
                    workingcalendar_result.append(result)
2158
                meta_result['working_calendar'] = workingcalendar_result
2159
2160
        cursor.close()
2161
        cnx.close()
2162
        resp.text = json.dumps(meta_result)
2163
2164
2165
class StoreImport:
2166
    def __init__(self):
2167
        pass
2168
2169
    @staticmethod
2170
    def on_options(req, resp):
2171
        _ = req
2172
        resp.status = falcon.HTTP_200
2173
2174
    @staticmethod
2175
    @user_logger
2176
    def on_post(req, resp):
2177
        """Handles POST requests"""
2178
        admin_control(req)
2179
        try:
2180
            raw_json = req.stream.read().decode('utf-8')
2181
        except Exception as ex:
2182
            print(str(ex))
2183
            raise falcon.HTTPError(status=falcon.HTTP_400,
2184
                                   title='API.BAD_REQUEST',
2185
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2186
2187
        new_values = json.loads(raw_json)
2188
2189
        if 'name' not in new_values.keys() or \
2190
                not isinstance(new_values['name'], str) or \
2191
                len(str.strip(new_values['name'])) == 0:
2192
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2193
                                   description='API.INVALID_STORE_NAME')
2194
        name = str.strip(new_values['name'])
2195
2196
        if 'address' not in new_values.keys() or \
2197
                not isinstance(new_values['address'], str) or \
2198
                len(str.strip(new_values['address'])) == 0:
2199
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2200
                                   description='API.INVALID_ADDRESS_VALUE')
2201
        address = str.strip(new_values['address'])
2202
2203
        if 'latitude' not in new_values.keys() or \
2204
                not (isinstance(new_values['latitude'], float) or
2205
                     isinstance(new_values['latitude'], int)) or \
2206
                new_values['latitude'] < -90.0 or \
2207
                new_values['latitude'] > 90.0:
2208
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2209
                                   description='API.INVALID_LATITUDE_VALUE')
2210
        latitude = new_values['latitude']
2211
2212
        if 'longitude' not in new_values.keys() or \
2213
                not (isinstance(new_values['longitude'], float) or
2214
                     isinstance(new_values['longitude'], int)) or \
2215
                new_values['longitude'] < -180.0 or \
2216
                new_values['longitude'] > 180.0:
2217
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2218
                                   description='API.INVALID_LONGITUDE_VALUE')
2219
        longitude = new_values['longitude']
2220
2221
        if 'area' not in new_values.keys() or \
2222
                not (isinstance(new_values['area'], float) or
2223
                     isinstance(new_values['area'], int)) or \
2224
                new_values['area'] <= 0.0:
2225
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2226
                                   description='API.INVALID_AREA_VALUE')
2227
        area = new_values['area']
2228
2229
        if 'id' not in new_values['store_type'].keys() or \
2230
                not isinstance(new_values['store_type']['id'], int) or \
2231
                new_values['store_type']['id'] <= 0:
2232
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2233
                                   description='API.INVALID_STORE_TYPE_ID')
2234
        store_type_id = new_values['store_type']['id']
2235
2236
        if 'is_input_counted' not in new_values.keys() or \
2237
                not isinstance(new_values['is_input_counted'], bool):
2238
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2239
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
2240
        is_input_counted = new_values['is_input_counted']
2241
2242
        if 'id' not in new_values['contact'].keys() or \
2243
                not isinstance(new_values['contact']['id'], int) or \
2244
                new_values['contact']['id'] <= 0:
2245
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2246
                                   description='API.INVALID_CONTACT_ID')
2247
        contact_id = new_values['contact']['id']
2248
2249
        if 'id' not in new_values['cost_center'].keys() or \
2250
                not isinstance(new_values['cost_center']['id'], int) or \
2251
                new_values['cost_center']['id'] <= 0:
2252
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2253
                                   description='API.INVALID_COST_CENTER_ID')
2254
        cost_center_id = new_values['cost_center']['id']
2255
2256
        if 'description' in new_values.keys() and \
2257
                new_values['description'] is not None and \
2258
                len(str(new_values['description'])) > 0:
2259
            description = str.strip(new_values['description'])
2260
        else:
2261
            description = None
2262
2263
        cnx = mysql.connector.connect(**config.myems_system_db)
2264
        cursor = cnx.cursor()
2265
2266
        cursor.execute(" SELECT name "
2267
                       " FROM tbl_stores "
2268
                       " WHERE name = %s ", (name,))
2269
        if cursor.fetchone() is not None:
2270
            cursor.close()
2271
            cnx.close()
2272
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2273
                                   description='API.STORE_NAME_IS_ALREADY_IN_USE')
2274
2275
        cursor.execute(" SELECT name "
2276
                       " FROM tbl_store_types "
2277
                       " WHERE id = %s ",
2278
                       (store_type_id,))
2279
        if cursor.fetchone() is None:
2280
            cursor.close()
2281
            cnx.close()
2282
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2283
                                   description='API.STORE_TYPE_NOT_FOUND')
2284
2285
        cursor.execute(" SELECT name "
2286
                       " FROM tbl_contacts "
2287
                       " WHERE id = %s ",
2288
                       (new_values['contact']['id'],))
2289
        row = cursor.fetchone()
2290
        if row is None:
2291
            cursor.close()
2292
            cnx.close()
2293
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2294
                                   description='API.CONTACT_NOT_FOUND')
2295
2296
        cursor.execute(" SELECT name "
2297
                       " FROM tbl_cost_centers "
2298
                       " WHERE id = %s ",
2299
                       (new_values['cost_center']['id'],))
2300
        row = cursor.fetchone()
2301
        if row is None:
2302
            cursor.close()
2303
            cnx.close()
2304
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2305
                                   description='API.COST_CENTER_NOT_FOUND')
2306
2307
        add_values = (" INSERT INTO tbl_stores "
2308
                      "    (name, uuid, address, latitude, longitude, area, store_type_id, "
2309
                      "     is_input_counted, "
2310
                      "     contact_id, cost_center_id, description) "
2311
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
2312
        cursor.execute(add_values, (name,
2313
                                    str(uuid.uuid4()),
2314
                                    address,
2315
                                    latitude,
2316
                                    longitude,
2317
                                    area,
2318
                                    store_type_id,
2319
                                    is_input_counted,
2320
                                    contact_id,
2321
                                    cost_center_id,
2322
                                    description))
2323
        new_id = cursor.lastrowid
2324
        if new_values['commands'] is not None and len(new_values['commands']) > 0:
2325
            for command in new_values['commands']:
2326
                cursor.execute(" SELECT name "
2327
                               " FROM tbl_commands "
2328
                               " WHERE id = %s ", (command['id'],))
2329
                if cursor.fetchone() is None:
2330
                    cursor.close()
2331
                    cnx.close()
2332
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2333
                                           description='API.COMMAND_NOT_FOUND')
2334
2335
                query = (" SELECT id "
2336
                         " FROM tbl_stores_commands "
2337
                         " WHERE store_id = %s AND command_id = %s")
2338
                cursor.execute(query, (new_id, command['id'],))
2339
                if cursor.fetchone() is not None:
2340
                    cursor.close()
2341
                    cnx.close()
2342
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2343
                                           description='API.STORE_COMMAND_RELATION_EXISTS')
2344
2345
                add_row = (" INSERT INTO tbl_stores_commands (store_id, command_id) "
2346
                           " VALUES (%s, %s) ")
2347
                cursor.execute(add_row, (new_id, command['id'],))
2348
        if new_values['meters'] is not None and len(new_values['meters']) > 0:
2349
            for meter in new_values['meters']:
2350
                cursor.execute(" SELECT name "
2351
                               " FROM tbl_meters "
2352
                               " WHERE id = %s ", (meter['id'],))
2353
                if cursor.fetchone() is None:
2354
                    cursor.close()
2355
                    cnx.close()
2356
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2357
                                           description='API.METER_NOT_FOUND')
2358
2359
                query = (" SELECT id "
2360
                         " FROM tbl_stores_meters "
2361
                         " WHERE store_id = %s AND meter_id = %s")
2362
                cursor.execute(query, (new_id, meter['id'],))
2363
                if cursor.fetchone() is not None:
2364
                    cursor.close()
2365
                    cnx.close()
2366
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2367
                                           description='API.STORE_METER_RELATION_EXISTS')
2368
2369
                add_row = (" INSERT INTO tbl_stores_meters (store_id, meter_id) "
2370
                           " VALUES (%s, %s) ")
2371
                cursor.execute(add_row, (new_id, meter['id'],))
2372
        if new_values['offline_meters'] is not None and len(new_values['offline_meters']) > 0:
2373
            for offline_meter in new_values['offline_meters']:
2374
                cursor.execute(" SELECT name "
2375
                               " FROM tbl_offline_meters "
2376
                               " WHERE id = %s ", (offline_meter['id'],))
2377
                if cursor.fetchone() is None:
2378
                    cursor.close()
2379
                    cnx.close()
2380
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2381
                                           description='API.OFFLINE_METER_NOT_FOUND')
2382
2383
                query = (" SELECT id "
2384
                         " FROM tbl_stores_offline_meters "
2385
                         " WHERE store_id = %s AND offline_meter_id = %s")
2386
                cursor.execute(query, (new_id, offline_meter['id'],))
2387
                if cursor.fetchone() is not None:
2388
                    cursor.close()
2389
                    cnx.close()
2390
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2391
                                           description='API.STORE_OFFLINE_METER_RELATION_EXISTS')
2392
2393
                add_row = (" INSERT INTO tbl_stores_offline_meters (store_id, offline_meter_id) "
2394
                           " VALUES (%s, %s) ")
2395
                cursor.execute(add_row, (new_id, offline_meter['id'],))
2396
        if new_values['virtual_meters'] is not None and len(new_values['virtual_meters']) > 0:
2397
            for virtual_meter in new_values['virtual_meters']:
2398
                cursor.execute(" SELECT name "
2399
                               " FROM tbl_virtual_meters "
2400
                               " WHERE id = %s ", (virtual_meter['id'],))
2401
                if cursor.fetchone() is None:
2402
                    cursor.close()
2403
                    cnx.close()
2404
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2405
                                           description='API.VIRTUAL_METER_NOT_FOUND')
2406
2407
                query = (" SELECT id "
2408
                         " FROM tbl_stores_virtual_meters "
2409
                         " WHERE store_id = %s AND virtual_meter_id = %s")
2410
                cursor.execute(query, (new_id, virtual_meter['id'],))
2411
                if cursor.fetchone() is not None:
2412
                    cursor.close()
2413
                    cnx.close()
2414
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2415
                                           description='API.STORE_VIRTUAL_METER_RELATION_EXISTS')
2416
2417
                add_row = (" INSERT INTO tbl_stores_virtual_meters (store_id, virtual_meter_id) "
2418
                           " VALUES (%s, %s) ")
2419
                cursor.execute(add_row, (new_id, virtual_meter['id'],))
2420
        if new_values['points'] is not None and len(new_values['points']) > 0:
2421
            for point in new_values['points']:
2422
                cursor.execute(" SELECT name "
2423
                               " FROM tbl_points "
2424
                               " WHERE id = %s ", (point['id'],))
2425
                if cursor.fetchone() is None:
2426
                    cursor.close()
2427
                    cnx.close()
2428
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2429
                                           description='API.POINT_NOT_FOUND')
2430
2431
                query = (" SELECT id "
2432
                         " FROM tbl_stores_points "
2433
                         " WHERE store_id = %s AND point_id = %s")
2434
                cursor.execute(query, (new_id, point['id'],))
2435
                if cursor.fetchone() is not None:
2436
                    cursor.close()
2437
                    cnx.close()
2438
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2439
                                           description='API.STORE_POINT_RELATION_EXISTS')
2440
2441
                add_row = (" INSERT INTO tbl_stores_points (store_id, point_id) "
2442
                           " VALUES (%s, %s) ")
2443
                cursor.execute(add_row, (new_id, point['id'],))
2444
        if new_values['sensors'] is not None and len(new_values['sensors']) > 0:
2445
            for sensor in new_values['sensors']:
2446
                cursor.execute(" SELECT name "
2447
                               " FROM tbl_sensors "
2448
                               " WHERE id = %s ", (sensor['id'],))
2449
                if cursor.fetchone() is None:
2450
                    cursor.close()
2451
                    cnx.close()
2452
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2453
                                           description='API.SENSOR_NOT_FOUND')
2454
2455
                query = (" SELECT id "
2456
                         " FROM tbl_stores_sensors "
2457
                         " WHERE store_id = %s AND sensor_id = %s")
2458
                cursor.execute(query, (new_id, sensor['id'],))
2459
                if cursor.fetchone() is not None:
2460
                    cursor.close()
2461
                    cnx.close()
2462
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2463
                                           description='API.STORE_SENSOR_RELATION_EXISTS')
2464
2465
                add_row = (" INSERT INTO tbl_stores_sensors (store_id, sensor_id) "
2466
                           " VALUES (%s, %s) ")
2467
                cursor.execute(add_row, (new_id, sensor['id'],))
2468
        if new_values['working_calendars'] is not None and len(new_values['working_calendars']) > 0:
2469
            for working_calendar in new_values['working_calendars']:
2470
                cursor.execute(" SELECT name "
2471
                               " FROM tbl_working_calendars "
2472
                               " WHERE id = %s ", (working_calendar['id'],))
2473
                if cursor.fetchone() is None:
2474
                    cursor.close()
2475
                    cnx.close()
2476
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2477
                                           description='API.WORKING_CALENDAR_NOT_FOUND')
2478
2479
                query = (" SELECT id "
2480
                         " FROM tbl_stores_working_calendars "
2481
                         " WHERE store_id = %s AND working_calendar_id = %s")
2482
                cursor.execute(query, (new_id, working_calendar['id'],))
2483
                if cursor.fetchone() is not None:
2484
                    cursor.close()
2485
                    cnx.close()
2486
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2487
                                           description='API.STORE_WORKING_CALENDAR_RELATION_EXISTS')
2488
2489
                add_row = (" INSERT INTO tbl_stores_working_calendars (store_id, working_calendar_id) "
2490
                           " VALUES (%s, %s) ")
2491
                cursor.execute(add_row, (new_id, working_calendar['id'],))
2492
        cnx.commit()
2493
        cursor.close()
2494
        cnx.close()
2495
2496
        resp.status = falcon.HTTP_201
2497
        resp.location = '/stores/' + str(new_id)
2498
2499
2500
class StoreClone:
2501
    def __init__(self):
2502
        pass
2503
2504
    @staticmethod
2505
    def on_options(req, resp, id_):
2506
        _ = req
2507
        resp.status = falcon.HTTP_200
2508
        _ = id_
2509
2510
    @staticmethod
2511
    @user_logger
2512
    def on_post(req, resp, id_):
2513
        admin_control(req)
2514
        if not id_.isdigit() or int(id_) <= 0:
2515
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2516
                                   description='API.INVALID_STORE_ID')
2517
2518
        cnx = mysql.connector.connect(**config.myems_system_db)
2519
        cursor = cnx.cursor()
2520
2521
        query = (" SELECT id, name, uuid "
2522
                 " FROM tbl_store_types ")
2523
        cursor.execute(query)
2524
        rows_store_types = cursor.fetchall()
2525
2526
        store_type_dict = dict()
2527
        if rows_store_types is not None and len(rows_store_types) > 0:
2528
            for row in rows_store_types:
2529
                store_type_dict[row[0]] = {"id": row[0],
2530
                                           "name": row[1],
2531
                                           "uuid": row[2]}
2532
2533
        query = (" SELECT id, name, uuid "
2534
                 " FROM tbl_contacts ")
2535
        cursor.execute(query)
2536
        rows_contacts = cursor.fetchall()
2537
2538
        contact_dict = dict()
2539
        if rows_contacts is not None and len(rows_contacts) > 0:
2540
            for row in rows_contacts:
2541
                contact_dict[row[0]] = {"id": row[0],
2542
                                        "name": row[1],
2543
                                        "uuid": row[2]}
2544
2545
        query = (" SELECT id, name, uuid "
2546
                 " FROM tbl_cost_centers ")
2547
        cursor.execute(query)
2548
        rows_cost_centers = cursor.fetchall()
2549
2550
        cost_center_dict = dict()
2551
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
2552
            for row in rows_cost_centers:
2553
                cost_center_dict[row[0]] = {"id": row[0],
2554
                                            "name": row[1],
2555
                                            "uuid": row[2]}
2556
2557
        query = (" SELECT id, name, uuid, "
2558
                 "        address, latitude, longitude, area, store_type_id,"
2559
                 "        is_input_counted, "
2560
                 "        contact_id, cost_center_id, description "
2561
                 " FROM tbl_stores "
2562
                 " WHERE id = %s ")
2563
        cursor.execute(query, (id_,))
2564
        row = cursor.fetchone()
2565
2566
        if row is None:
2567
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2568
                                   description='API.STORE_NOT_FOUND')
2569
        else:
2570
            meta_result = {"id": row[0],
2571
                           "name": row[1],
2572
                           "uuid": row[2],
2573
                           "address": row[3],
2574
                           "latitude": row[4],
2575
                           "longitude": row[5],
2576
                           "area": row[6],
2577
                           "store_type": store_type_dict.get(row[7], None),
2578
                           "is_input_counted": bool(row[8]),
2579
                           "contact": contact_dict.get(row[9], None),
2580
                           "cost_center": cost_center_dict.get(row[10], None),
2581
                           "description": row[11],
2582
                           "commands": None,
2583
                           "meters": None,
2584
                           "offline_meters": None,
2585
                           "virtual_meters": None,
2586
                           "points": None,
2587
                           "sensors": None,
2588
                           "working_calendars": None
2589
                           }
2590
            query = (" SELECT c.id, c.name, c.uuid "
2591
                     " FROM tbl_stores s, tbl_stores_commands sc, tbl_commands c "
2592
                     " WHERE sc.store_id = s.id AND c.id = sc.command_id AND s.id = %s "
2593
                     " ORDER BY c.id ")
2594
            cursor.execute(query, (id_,))
2595
            rows = cursor.fetchall()
2596
2597
            command_result = list()
2598
            if rows is not None and len(rows) > 0:
2599
                for row in rows:
2600
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
2601
                    command_result.append(result)
2602
                meta_result['commands'] = command_result
2603
2604
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
2605
                     " FROM tbl_stores t, tbl_stores_meters tm, tbl_meters m "
2606
                     " WHERE tm.store_id = t.id AND m.id = tm.meter_id AND t.id = %s "
2607
                     " ORDER BY m.id ")
2608
            cursor.execute(query, (id_,))
2609
            rows = cursor.fetchall()
2610
2611
            meter_result = list()
2612
            if rows is not None and len(rows) > 0:
2613
                for row in rows:
2614
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
2615
                    meter_result.append(result)
2616
                meta_result['meters'] = meter_result
2617
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
2618
                     " FROM tbl_stores s, tbl_stores_offline_meters sm, tbl_offline_meters m "
2619
                     " WHERE sm.store_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
2620
                     " ORDER BY m.id ")
2621
            cursor.execute(query, (id_,))
2622
            rows = cursor.fetchall()
2623
2624
            offlinemeter_result = list()
2625
            if rows is not None and len(rows) > 0:
2626
                for row in rows:
2627
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
2628
                    offlinemeter_result.append(result)
2629
                meta_result['offline_meters'] = offlinemeter_result
2630
            query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
2631
                     " FROM tbl_stores t, tbl_stores_virtual_meters tm, tbl_virtual_meters m "
2632
                     " WHERE tm.store_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s "
2633
                     " ORDER BY m.id ")
2634
            cursor.execute(query, (id_,))
2635
            rows = cursor.fetchall()
2636
2637
            virtualmeter_result = list()
2638
            if rows is not None and len(rows) > 0:
2639
                for row in rows:
2640
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
2641
                    virtualmeter_result.append(result)
2642
                meta_result['virtual_meters'] = virtualmeter_result
2643
            query = (" SELECT id, name, uuid "
2644
                     " FROM tbl_data_sources ")
2645
            cursor.execute(query)
2646
            rows_data_sources = cursor.fetchall()
2647
2648
            data_source_dict = dict()
2649
            if rows_data_sources is not None and len(rows_data_sources) > 0:
2650
                for row in rows_data_sources:
2651
                    data_source_dict[row[0]] = {"id": row[0],
2652
                                                "name": row[1],
2653
                                                "uuid": row[2]}
2654
2655
            query = (" SELECT p.id, p.name, p.data_source_id "
2656
                     " FROM tbl_stores t, tbl_stores_points tp, tbl_points p "
2657
                     " WHERE tp.store_id = t.id AND p.id = tp.point_id AND t.id = %s "
2658
                     " ORDER BY p.id ")
2659
            cursor.execute(query, (id_,))
2660
            rows = cursor.fetchall()
2661
2662
            point_result = list()
2663
            if rows is not None and len(rows) > 0:
2664
                for row in rows:
2665
                    result = {"id": row[0], "name": row[1], "data_source": data_source_dict.get(row[2], None)}
2666
                    point_result.append(result)
2667
                meta_result['points'] = point_result
2668
            query = (" SELECT s.id, s.name, s.uuid "
2669
                     " FROM tbl_stores t, tbl_stores_sensors ts, tbl_sensors s "
2670
                     " WHERE ts.store_id = t.id AND s.id = ts.sensor_id AND t.id = %s "
2671
                     " ORDER BY s.id ")
2672
            cursor.execute(query, (id_,))
2673
            rows = cursor.fetchall()
2674
2675
            sensor_result = list()
2676
            if rows is not None and len(rows) > 0:
2677
                for row in rows:
2678
                    result = {"id": row[0], "name": row[1], "uuid": row[2]}
2679
                    sensor_result.append(result)
2680
                meta_result['sensors'] = sensor_result
2681
            query = (" SELECT wc.id, wc.name, wc.description "
2682
                     " FROM tbl_stores s, tbl_stores_working_calendars swc, tbl_working_calendars wc "
2683
                     " WHERE swc.store_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
2684
                     " ORDER BY wc.id ")
2685
            cursor.execute(query, (id_,))
2686
            rows = cursor.fetchall()
2687
2688
            workingcalendar_result = list()
2689
            if rows is not None and len(rows) > 0:
2690
                for row in rows:
2691
                    result = {"id": row[0], "name": row[1], "description": row[2]}
2692
                    workingcalendar_result.append(result)
2693
                meta_result['working_calendar'] = workingcalendar_result
2694
            timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
2695
            if config.utc_offset[0] == '-':
2696
                timezone_offset = -timezone_offset
2697
            new_name = (str.strip(meta_result['name']) +
2698
                        (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds'))
2699
            add_values = (" INSERT INTO tbl_stores "
2700
                          "    (name, uuid, address, latitude, longitude, area, store_type_id, "
2701
                          "     is_input_counted, "
2702
                          "     contact_id, cost_center_id, description) "
2703
                          " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
2704
            cursor.execute(add_values, (new_name,
2705
                                        str(uuid.uuid4()),
2706
                                        meta_result['address'],
2707
                                        meta_result['latitude'],
2708
                                        meta_result['longitude'],
2709
                                        meta_result['area'],
2710
                                        meta_result['store_type']['id'],
2711
                                        meta_result['is_input_counted'],
2712
                                        meta_result['contact']['id'],
2713
                                        meta_result['cost_center']['id'],
2714
                                        meta_result['description']))
2715
            new_id = cursor.lastrowid
2716
            if meta_result['commands'] is not None and len(meta_result['commands']) > 0:
2717
                for command in meta_result['commands']:
2718
                    cursor.execute(" SELECT name "
2719
                                   " FROM tbl_commands "
2720
                                   " WHERE id = %s ", (command['id'],))
2721
                    if cursor.fetchone() is None:
2722
                        cursor.close()
2723
                        cnx.close()
2724
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2725
                                               description='API.COMMAND_NOT_FOUND')
2726
2727
                    query = (" SELECT id "
2728
                             " FROM tbl_stores_commands "
2729
                             " WHERE store_id = %s AND command_id = %s")
2730
                    cursor.execute(query, (new_id, command['id'],))
2731
                    if cursor.fetchone() is not None:
2732
                        cursor.close()
2733
                        cnx.close()
2734
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2735
                                               description='API.STORE_COMMAND_RELATION_EXISTS')
2736
2737
                    add_row = (" INSERT INTO tbl_stores_commands (store_id, command_id) "
2738
                               " VALUES (%s, %s) ")
2739
                    cursor.execute(add_row, (new_id, command['id'],))
2740
            if meta_result['meters'] is not None and len(meta_result['meters']) > 0:
2741
                for meter in meta_result['meters']:
2742
                    cursor.execute(" SELECT name "
2743
                                   " FROM tbl_meters "
2744
                                   " WHERE id = %s ", (meter['id'],))
2745
                    if cursor.fetchone() is None:
2746
                        cursor.close()
2747
                        cnx.close()
2748
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2749
                                               description='API.METER_NOT_FOUND')
2750
2751
                    query = (" SELECT id "
2752
                             " FROM tbl_stores_meters "
2753
                             " WHERE store_id = %s AND meter_id = %s")
2754
                    cursor.execute(query, (new_id, meter['id'],))
2755
                    if cursor.fetchone() is not None:
2756
                        cursor.close()
2757
                        cnx.close()
2758
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2759
                                               description='API.STORE_METER_RELATION_EXISTS')
2760
2761
                    add_row = (" INSERT INTO tbl_stores_meters (store_id, meter_id) "
2762
                               " VALUES (%s, %s) ")
2763
                    cursor.execute(add_row, (new_id, meter['id'],))
2764
            if meta_result['offline_meters'] is not None and len(meta_result['offline_meters']) > 0:
2765
                for offline_meter in meta_result['offline_meters']:
2766
                    cursor.execute(" SELECT name "
2767
                                   " FROM tbl_offline_meters "
2768
                                   " WHERE id = %s ", (offline_meter['id'],))
2769
                    if cursor.fetchone() is None:
2770
                        cursor.close()
2771
                        cnx.close()
2772
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2773
                                               description='API.OFFLINE_METER_NOT_FOUND')
2774
2775
                    query = (" SELECT id "
2776
                             " FROM tbl_stores_offline_meters "
2777
                             " WHERE store_id = %s AND offline_meter_id = %s")
2778
                    cursor.execute(query, (new_id, offline_meter['id'],))
2779
                    if cursor.fetchone() is not None:
2780
                        cursor.close()
2781
                        cnx.close()
2782
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2783
                                               description='API.STORE_OFFLINE_METER_RELATION_EXISTS')
2784
2785
                    add_row = (" INSERT INTO tbl_stores_offline_meters (store_id, offline_meter_id) "
2786
                               " VALUES (%s, %s) ")
2787
                    cursor.execute(add_row, (new_id, offline_meter['id'],))
2788
            if meta_result['virtual_meters'] is not None and len(meta_result['virtual_meters']) > 0:
2789
                for virtual_meter in meta_result['virtual_meters']:
2790
                    cursor.execute(" SELECT name "
2791
                                   " FROM tbl_virtual_meters "
2792
                                   " WHERE id = %s ", (virtual_meter['id'],))
2793
                    if cursor.fetchone() is None:
2794
                        cursor.close()
2795
                        cnx.close()
2796
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2797
                                               description='API.VIRTUAL_METER_NOT_FOUND')
2798
2799
                    query = (" SELECT id "
2800
                             " FROM tbl_stores_virtual_meters "
2801
                             " WHERE store_id = %s AND virtual_meter_id = %s")
2802
                    cursor.execute(query, (new_id, virtual_meter['id'],))
2803
                    if cursor.fetchone() is not None:
2804
                        cursor.close()
2805
                        cnx.close()
2806
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2807
                                               description='API.STORE_VIRTUAL_METER_RELATION_EXISTS')
2808
2809
                    add_row = (" INSERT INTO tbl_stores_virtual_meters (store_id, virtual_meter_id) "
2810
                               " VALUES (%s, %s) ")
2811
                    cursor.execute(add_row, (new_id, virtual_meter['id'],))
2812
            if meta_result['points'] is not None and len(meta_result['points']) > 0:
2813
                for point in meta_result['points']:
2814
                    cursor.execute(" SELECT name "
2815
                                   " FROM tbl_points "
2816
                                   " WHERE id = %s ", (point['id'],))
2817
                    if cursor.fetchone() is None:
2818
                        cursor.close()
2819
                        cnx.close()
2820
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2821
                                               description='API.POINT_NOT_FOUND')
2822
2823
                    query = (" SELECT id "
2824
                             " FROM tbl_stores_points "
2825
                             " WHERE store_id = %s AND point_id = %s")
2826
                    cursor.execute(query, (new_id, point['id'],))
2827
                    if cursor.fetchone() is not None:
2828
                        cursor.close()
2829
                        cnx.close()
2830
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2831
                                               description='API.STORE_POINT_RELATION_EXISTS')
2832
2833
                    add_row = (" INSERT INTO tbl_stores_points (store_id, point_id) "
2834
                               " VALUES (%s, %s) ")
2835
                    cursor.execute(add_row, (new_id, point['id'],))
2836
            if meta_result['sensors'] is not None and len(meta_result['sensors']) > 0:
2837
                for sensor in meta_result['sensors']:
2838
                    cursor.execute(" SELECT name "
2839
                                   " FROM tbl_sensors "
2840
                                   " WHERE id = %s ", (sensor['id'],))
2841
                    if cursor.fetchone() is None:
2842
                        cursor.close()
2843
                        cnx.close()
2844
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2845
                                               description='API.SENSOR_NOT_FOUND')
2846
2847
                    query = (" SELECT id "
2848
                             " FROM tbl_stores_sensors "
2849
                             " WHERE store_id = %s AND sensor_id = %s")
2850
                    cursor.execute(query, (new_id, sensor['id'],))
2851
                    if cursor.fetchone() is not None:
2852
                        cursor.close()
2853
                        cnx.close()
2854
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2855
                                               description='API.STORE_SENSOR_RELATION_EXISTS')
2856
2857
                    add_row = (" INSERT INTO tbl_stores_sensors (store_id, sensor_id) "
2858
                               " VALUES (%s, %s) ")
2859
                    cursor.execute(add_row, (new_id, sensor['id'],))
2860
            if meta_result['working_calendars'] is not None and len(meta_result['working_calendars']) > 0:
2861
                for working_calendar in meta_result['working_calendars']:
2862
                    cursor.execute(" SELECT name "
2863
                                   " FROM tbl_working_calendars "
2864
                                   " WHERE id = %s ", (working_calendar['id'],))
2865
                    if cursor.fetchone() is None:
2866
                        cursor.close()
2867
                        cnx.close()
2868
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2869
                                               description='API.WORKING_CALENDAR_NOT_FOUND')
2870
2871
                    query = (" SELECT id "
2872
                             " FROM tbl_stores_working_calendars "
2873
                             " WHERE store_id = %s AND working_calendar_id = %s")
2874
                    cursor.execute(query, (new_id, working_calendar['id'],))
2875
                    if cursor.fetchone() is not None:
2876
                        cursor.close()
2877
                        cnx.close()
2878
                        raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2879
                                               description='API.STORE_WORKING_CALENDAR_RELATION_EXISTS')
2880
2881
                    add_row = (" INSERT INTO tbl_stores_working_calendars (store_id, working_calendar_id) "
2882
                               " VALUES (%s, %s) ")
2883
                    cursor.execute(add_row, (new_id, working_calendar['id'],))
2884
            cnx.commit()
2885
            cursor.close()
2886
            cnx.close()
2887
2888
            resp.status = falcon.HTTP_201
2889
            resp.location = '/stores/' + str(new_id)
2890