From c25aaad3d0c222e8d24fd4119e5d6cdba464437c Mon Sep 17 00:00:00 2001 From: hyh123a Date: Sat, 16 Apr 2022 20:43:56 +0800 Subject: [PATCH] add the ticket database config --- myems-api/app.py | 5 + myems-api/config.py | 8 ++ myems-api/example.env | 7 + myems-api/reports/ticket.py | 249 ++++++++++++++++++++++++++++++++++++ 4 files changed, 269 insertions(+) create mode 100644 myems-api/reports/ticket.py diff --git a/myems-api/app.py b/myems-api/app.py index 0669b905..9557af8f 100644 --- a/myems-api/app.py +++ b/myems-api/app.py @@ -78,6 +78,7 @@ from reports import tenantload from reports import tenantbatch from reports import tenantsaving from reports import tenantstatistics +from reports import ticket from reports import virtualmeterenergy from reports import virtualmetercarbon from reports import virtualmetercost @@ -99,6 +100,10 @@ cors = CORS(allow_all_origins=True, allow_all_methods=True) api = falcon.App(middleware=[cors.middleware, MultipartMiddleware()]) + +api.add_route('/ticket/types', + ticket.TicketTypeCollection()) + ######################################################################################################################## # Routes for System Core ######################################################################################################################## diff --git a/myems-api/config.py b/myems-api/config.py index 61ff1196..6107c8e9 100644 --- a/myems-api/config.py +++ b/myems-api/config.py @@ -81,6 +81,14 @@ myems_carbon_db = { 'password': config('MYEMS_CARBON_DB_PASSWORD', default=''), } +loonflow = { + 'host': config('LOONFLOW_HOST', default='127.0.0.1'), + 'port': config('LOONFLOW_PORT', default=3306, cast=int), + 'database': config('LOONFLOW_DATABASE', default='loonflow'), + 'user': config('LOONFLOW_USER', default='root'), + 'password': config('LOONFLOW_PASSWORD', default=''), +} + # indicated in how many minutes to calculate meter energy consumption # 30 for half hourly period # 60 for hourly period diff --git a/myems-api/example.env b/myems-api/example.env index 151b7e8d..c6452f6c 100644 --- a/myems-api/example.env +++ b/myems-api/example.env @@ -68,6 +68,13 @@ MYEMS_CARBON_DB_DATABASE=myems_carbon_db MYEMS_CARBON_DB_USER=root MYEMS_CARBON_DB_PASSWORD=!MyEMS1 +# config for loonflow +LOONFLOW_HOST=127.0.0.1 +LOONFLOW_PORT=3306 +LOONFLOW_DATABASE=myems_carbon_db +LOONFLOW_USER=root +LOONFLOW_PASSWORD=!MyEMS1 + # indicated in how many minutes to calculate meter energy consumption # 30 for half hourly period # 60 for hourly period diff --git a/myems-api/reports/ticket.py b/myems-api/reports/ticket.py new file mode 100644 index 00000000..c9b4a712 --- /dev/null +++ b/myems-api/reports/ticket.py @@ -0,0 +1,249 @@ +import falcon +import simplejson as json +import mysql.connector +import config +import uuid +import re +from core.useractivity import user_logger, access_control + + +class TicketTypeCollection: + @staticmethod + def __init__(): + """"Initializes ContactCollection""" + pass + + @staticmethod + def on_options(req, resp): + resp.status = falcon.HTTP_200 + + @staticmethod + def on_get(req, resp): + cnx = mysql.connector.connect(**config.loonflow) + cursor = cnx.cursor() + + query = (" SELECT id, name, uuid, " + " email, phone, description " + " FROM tbl_contacts " + " ORDER BY name ") + cursor.execute(query) + rows = cursor.fetchall() + cursor.close() + cnx.close() + + result = list() + if rows is not None and len(rows) > 0: + for row in rows: + meta_result = {"id": row[0], + "name": row[1], + "uuid": row[2], + "email": row[3], + "phone": row[4], + "description": row[5]} + result.append(meta_result) + + resp.text = json.dumps(result) + + + +class ContactItem: + @staticmethod + def __init__(): + """"Initializes ContactItem""" + pass + + @staticmethod + def on_options(req, resp, id_): + resp.status = falcon.HTTP_200 + + @staticmethod + def on_get(req, resp, id_): + if not id_.isdigit() or int(id_) <= 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_CONTACT_ID') + + cnx = mysql.connector.connect(**config.myems_system_db) + cursor = cnx.cursor() + + query = (" SELECT id, name, uuid, email, phone, description " + " FROM tbl_contacts " + " WHERE id = %s ") + cursor.execute(query, (id_,)) + row = cursor.fetchone() + cursor.close() + cnx.close() + + if row is None: + raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', + description='API.CONTACT_NOT_FOUND') + + result = {"id": row[0], + "name": row[1], + "uuid": row[2], + "email": row[3], + "phone": row[4], + "description": row[5]} + resp.text = json.dumps(result) + + @staticmethod + @user_logger + def on_delete(req, resp, id_): + access_control(req) + if not id_.isdigit() or int(id_) <= 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_CONTACT_ID') + + cnx = mysql.connector.connect(**config.myems_system_db) + cursor = cnx.cursor() + + cursor.execute(" SELECT name " + " FROM tbl_contacts " + " WHERE id = %s ", (id_,)) + if cursor.fetchone() is None: + cursor.close() + cnx.close() + raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', + description='API.CONTACT_NOT_FOUND') + + # check relation with shopfloors + cursor.execute(" SELECT id " + " FROM tbl_shopfloors " + " WHERE contact_id = %s ", (id_,)) + rows_shopfloors = cursor.fetchall() + if rows_shopfloors is not None and len(rows_shopfloors) > 0: + cursor.close() + cnx.close() + raise falcon.HTTPError(falcon.HTTP_400, + title='API.BAD_REQUEST', + description='API.THERE_IS_RELATION_WITH_SHOPFLOORS') + + # check relation with spaces + cursor.execute(" SELECT id " + " FROM tbl_spaces " + " WHERE contact_id = %s ", (id_,)) + rows_spaces = cursor.fetchall() + if rows_spaces is not None and len(rows_spaces) > 0: + cursor.close() + cnx.close() + raise falcon.HTTPError(falcon.HTTP_400, + title='API.BAD_REQUEST', + description='API.THERE_IS_RELATION_WITH_SPACES') + + # check relation with stores + cursor.execute(" SELECT id " + " FROM tbl_stores " + " WHERE contact_id = %s ", (id_,)) + rows_stores = cursor.fetchall() + if rows_stores is not None and len(rows_stores) > 0: + cursor.close() + cnx.close() + raise falcon.HTTPError(falcon.HTTP_400, + title='API.BAD_REQUEST', + description='API.THERE_IS_RELATION_WITH_STORES') + + # check relation with tenants + cursor.execute(" SELECT id " + " FROM tbl_tenants " + " WHERE contact_id = %s ", (id_,)) + rows_tenants = cursor.fetchall() + if rows_tenants is not None and len(rows_tenants) > 0: + cursor.close() + cnx.close() + raise falcon.HTTPError(falcon.HTTP_400, + title='API.BAD_REQUEST', + description='API.THERE_IS_RELATION_WITH_TENANTS') + + cursor.execute(" DELETE FROM tbl_contacts WHERE id = %s ", (id_,)) + cnx.commit() + + cursor.close() + cnx.close() + + resp.status = falcon.HTTP_204 + + @staticmethod + @user_logger + def on_put(req, resp, id_): + """Handles PUT requests""" + access_control(req) + try: + raw_json = req.stream.read().decode('utf-8') + except Exception as ex: + raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) + + if not id_.isdigit() or int(id_) <= 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_CONTACT_ID') + + new_values = json.loads(raw_json) + + if 'name' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['name'], str) or \ + len(str.strip(new_values['data']['name'])) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_CONTACT_NAME') + name = str.strip(new_values['data']['name']) + + if 'email' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['email'], str) or \ + len(str.strip(new_values['data']['email'])) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_EMAIL') + email = str.lower(str.strip(new_values['data']['email'])) + + match = re.match(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email) + if match is None: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_EMAIL') + + if 'phone' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['phone'], str) or \ + len(str.strip(new_values['data']['phone'])) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_USER_PHONE') + phone = str.strip(new_values['data']['phone']) + + if 'description' in new_values['data'].keys() and \ + new_values['data']['description'] is not None and \ + len(str(new_values['data']['description'])) > 0: + description = str.strip(new_values['data']['description']) + else: + description = None + + cnx = mysql.connector.connect(**config.myems_system_db) + cursor = cnx.cursor() + + cursor.execute(" SELECT name " + " FROM tbl_contacts " + " WHERE id = %s ", (id_,)) + if cursor.fetchone() is None: + cursor.close() + cnx.close() + raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', + description='API.CONTACT_NOT_FOUND') + + cursor.execute(" SELECT name " + " FROM tbl_contacts " + " WHERE name = %s AND id != %s ", (name, id_)) + if cursor.fetchone() is not None: + cursor.close() + cnx.close() + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.CONTACT_NAME_IS_ALREADY_IN_USE') + + update_row = (" UPDATE tbl_contacts " + " SET name = %s, email = %s, " + " phone = %s, description = %s " + " WHERE id = %s ") + cursor.execute(update_row, (name, + email, + phone, + description, + id_,)) + cnx.commit() + + cursor.close() + cnx.close() + + resp.status = falcon.HTTP_200 +