Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
17 kB
2
Indexable
Never
# ================================================================================================================================================================================
# HOBS MULTI-TENANCY FUNCTIONALITY REQUEST APIS
#   DATE     AUTHOR     VER   CHANGE DESCRIPTION
# --------  ---------  -----  ------------------
# 18.09.23  Ragul(Yaswanth)       1.0    Init version
# ================================================================================================================================================================================

from json import dumps as json_dumps
from json import loads as json_loads
from sys import exc_info as sys_exc_info
from datetime import datetime, timedelta, timezone, date
import ast

from models.hos_event_logs import hos_event_logs
from models.hos_event_logs import *
from models.hos_event_log_by_businesskeys import hos_event_log_by_businesskeys


# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


# define Python user-defined exceptions
class VALIDATION_ERRORS(Error):
    pass


def apilogfile(api):
    import logging
    from os import environ as os_environ
    log_file_path = os_environ.get('ANALYTICSDATASERVICELOGPATH')
    logging.shutdown()
    log_handler = logging.FileHandler(log_file_path + '/logs/' + api + '.log', mode='w+')
    formatter = logging.Formatter(
        fmt='%(asctime)s [Process:%(process)d] [%(levelname)-8s] [%(filename)s - %(module)s] : %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')
    # formatter.converter = time.gmtime  # if you want UTC tGime
    log_handler.setFormatter(formatter)
    LOGGER = logging.getLogger('apilog' + str(uuid.uuid1()))
    if not LOGGER.handlers:
        LOGGER.addHandler(log_handler)
        LOGGER.setLevel(logging.DEBUG)
    LOGGER.info('LOGGER activated for %s' % api)
    return LOGGER


"""
This function is used to fetch cache details based on valueType and key
"""


def getData(api, payLoad, configProperties):
    statusCode = '200'
    statusMessage = 'Successfully completed the process'
    response = {}
    batchId = None

    try:
        # Received parameters
        args_keys = payLoad.copy()

        # Initialize logger
        apilogger = apilogfile(api)
        apilogger.debug("args_keys ####   : %s" % type(json_dumps(args_keys)))
        apilogger.debug("args_keys/payLoad: %s" % json_dumps(args_keys))

        # Validation: Configuration
        if not configProperties.has_section('apiconfiguration'):
            raise VALIDATION_ERRORS("Configuration for validation not properly set.")

        validkeys = json_loads(
            configProperties.get('apiconfiguration', 'validkeys', raw=True)) if configProperties.has_option(
            'apiconfiguration', 'validkeys') else []
        columnMapping = json_loads(
            configProperties.get('apiconfiguration', 'columnMapping', raw=True)) if configProperties.has_option(
            'apiconfiguration', 'columnMapping') else {}
        validColumns = json_loads(
            configProperties.get('apiconfiguration', 'ValidColumns', raw=True)) if configProperties.has_option(
            'apiconfiguration', 'ValidColumns') else []

        # VALIDATION: parent keys
        apilogger.debug("args_keys: %s" % type(args_keys))
        apilogger.debug(args_keys)
        apilogger.debug("validkeys: %s" % type(validkeys))
        apilogger.debug(validkeys)
        """
        if args_keys == None or not isinstance(args_keys, dict) or len(args_keys) == 0:
            statusCode = "422"
            return VALIDATION_ERRORS("Missing required attribute in payLoad. " + ','.join(validkeys) + ".")
        
        
        if (set(list(args_keys.keys()))) != set(validkeys):
            #raise VALIDATION_ERRORS("Validation failed on parent keys. '%s'" % ("','".join([v for v in list(args_keys.keys()) if v not in validkeys]+list(set(validkeys)-set(list(args_keys.keys()))))))
            statusCode = "422"
            t1 = list(set(validkeys)-(set(list(args_keys.keys()))))
            apilogger.debug("t1: %s" % t1)
            if len(t1)>0:
                raise VALIDATION_ERRORS("Validation failed on parent keys. '%s'" % ("','".join(t1)))
            t2 = list(set(list(args_keys.keys()))-set(validkeys))
            apilogger.debug("t2: %s" % t2)
            if len(t2)>0:
                raise VALIDATION_ERRORS("Unprocessable parent keys found. '%s'" % ("','".join(t2)))
        """
        if not (set(list(args_keys.keys()))).issubset(set(validkeys)):
            statusCode = "422"
            raise VALIDATION_ERRORS("Arguments are not matching with validKey")

        if len(args_keys) == 0:

            query = "global hosEventLogRecords;hosEventLogRecords=hos_event_log_by_businesskeys.objects().filter(hosel_event_value='" + 'deleteUser' + "').allow_filtering();"
            apilogger.debug("query  : %s" % query)
            exec(query)
            apilogger.debug(("hosEventLogRecords: %s" % hosEventLogRecords))
            hosEventLogResult = [row.__json__() for row in hosEventLogRecords]
            
            apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
        ##with id
        if 'id' in args_keys.keys():
            apilogger.debug("batchId  : %s" % args_keys['id'])

            query = "global hosEventLogRecords;hosEventLogRecords=hos_event_log_by_businesskeys.objects().filter(hosel_event_value='" + 'deleteUser' + "').allow_filtering();"
            apilogger.debug("query  : %s" % query)
            exec(query)
            apilogger.debug(("hosEventLogRecords: %s" % hosEventLogRecords))
            hosEventLogResult = [row.__json__() for row in hosEventLogRecords.filter(hosel_event_seq=args_keys['id'])]
            apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            apilogger.debug("type of hosEventLogResult: %s" % type(hosEventLogResult))
        ##with Date
        if 'date' in args_keys.keys():
            apilogger.debug("Date  : %s" % args_keys['date'])
            query = "global hosEventLogRecords;hosEventLogRecords=hos_event_logs.objects().filter(hosel_date='" + \
                    args_keys['date'] + "',hosel_event_type='deleteUser').allow_filtering();"
            apilogger.debug("query  : %s" % query)
            exec(query)
            apilogger.debug(("hosEventLogRecords: %s" % hosEventLogRecords))
            hosEventLogResult = [row.__json__() for row in hosEventLogRecords]

            apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            apilogger.debug("type of hosEventLogResult: %s" % type(hosEventLogResult))
        ##with startDate and endDate
        if 'startDate' in args_keys.keys() and not 'endDate' in args_keys.keys():
                statusCode = "422"
                raise VALIDATION_ERRORS("endDate is missing")
        if 'endDate' in args_keys.keys() and not 'startDate' in args_keys.keys() :
                statusCode = "422"
                raise VALIDATION_ERRORS("startDate is missing")
            
            
        if 'startDate' in args_keys.keys() and 'endDate' in args_keys.keys():
            
            apilogger.debug("startDate  : %s" % args_keys['startDate'])
            apilogger.debug("endDate  : %s" % args_keys['endDate'])
            startDate = datetime.strptime(args_keys['startDate'], '%Y-%m-%d')
            endDate = datetime.strptime(args_keys['endDate'], '%Y-%m-%d')
            if endDate < startDate:
                statusCode = "422"
                raise VALIDATION_ERRORS("endDate is greater than startDate")
            ##__gte and __lte to perform greater than and equal , less than and equal operation 
            query = "global hosEventLogRecords;hosEventLogRecords=hos_event_logs.objects().filter(hosel_date__gte ='" + \
                    args_keys['startDate'] + "',hosel_date__lte= '" + args_keys['endDate'] + "',hosel_event_type='deleteUser').allow_filtering();"
            apilogger.debug("query  : %s" % query)
            exec(query)
            apilogger.debug(("hosEventLogRecords: %s" % hosEventLogRecords))
            hosEventLogResult = [row.__json__() for row in hosEventLogRecords]

            apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            apilogger.debug("type of hosEventLogResult: %s" % type(hosEventLogResult))
        ## with name
        if 'userID' in args_keys.keys():
            apilogger.debug('userID   :%s' % args_keys['userID'])
            query = "global hosEventLogRecords;hosEventLogRecords=hos_event_log_by_businesskeys.objects().filter(hosel_event_value='" + 'deleteUser' + "').allow_filtering();"
            apilogger.debug("query  : %s" % query)
            exec(query)
            apilogger.debug(("hosEventLogRecords: %s" % hosEventLogRecords))
            hosEventLogResult = [row.__json__() for row in hosEventLogRecords]
            apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            hosEventLogResult = [ v for v in hosEventLogResult if v['hosel_enriched_data']['userID'] == args_keys['userID']]
            apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            apilogger.debug("type of hosEventLogResult: %s" % type(hosEventLogResult))
        ##with emailID
        if 'emailID' in args_keys.keys():
            apilogger.debug('emailID   :%s' % args_keys['emailID'])
            query = "global hosEventLogRecords;hosEventLogRecords=hos_event_log_by_businesskeys.objects().filter(hosel_event_value='" + 'deleteUser' + "').allow_filtering();"
            apilogger.debug("query  : %s" % query)
            exec(query)
            #apilogger.debug(("hosEventLogRecords: %s" % hosEventLogRecords))
            #hosEventLogResult = [row.__json__() for row in hosEventLogRecords]
            #apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            #hosEventLogResult = [ v for v in hosEventLogResult if v['hosel_enriched_data']['email'] == args_keys['emailID']]
            #apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            #apilogger.debug("type of hosEventLogResult: %s" % type(hosEventLogResult))
            LogResult = [row.__json__() for row in hosEventLogRecords]
            hosEventLogResult =[]
            apilogger.debug("LogResult: %s" % LogResult)
            for v in LogResult:
                i = json_loads(v['hosel_event_data'])
                apilogger.debug("i: %s" % i)
                if "contactMedium" in i:
                    for j in i['contactMedium']:
                        if j.get("characteristic") == args_keys("emailID") and i.get('mediumType')=='email':
                            hosEventLogResult.append(v)
                            break
        ##with contactno
        if 'contactNo' in args_keys.keys():
            apilogger.debug('contact   :%s' % args_keys['contactNo'])
            query = "global hosEventLogRecords;hosEventLogRecords=hos_event_log_by_businesskeys.objects().filter(hosel_event_value='" + 'deleteUser' + "').allow_filtering();"
            apilogger.debug("query  : %s" % query)
            exec(query)
            #hosEventLogResult = [row.__json__() for row in hosEventLogRecords]
            #hosEventLogResult = [ v for v in hosEventLogResult if v['hosel_enriched_data']['contact'] == args_keys['contactNo']]
            #apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            #apilogger.debug("type of hosEventLogResult: %s" % type(hosEventLogResult))
            LogResult = [row.__json__() for row in hosEventLogRecords]
            hosEventLogResult =[]
            apilogger.debug("LogResult: %s" % LogResult)
            for v in LogResult:
                i = json_loads(v['hosel_event_data'])
                if "contactMedium" in i:
                    for j in i['contactMedium']:
                        if j.get("characteristic") == args_keys("contactNo") and i.get('mediumType')=='contact':
                            hosEventLogResult.append(v)
                            break
        ##with postcode
        if 'postcode' in args_keys.keys():
            
            apilogger.debug('postcode   :%s' % args_keys['postcode'])
            query = "global hosEventLogRecords;hosEventLogRecords=hos_event_log_by_businesskeys.objects().filter(hosel_event_value='" + 'deleteUser' + "').allow_filtering();"
            apilogger.debug("query  : %s" % query)
            exec(query)
            LogResult = [row.__json__() for row in hosEventLogRecords]
            #hosEventLogResult = [ v for v in hosEventLogResult if json_loads(v['hosel_enriched_data']['postalAddress'].replace("''",'"')).get("'postcode'") == args_keys['postcode']]
            #hosEventLogResult = [v for v in hosEventLogResult['hosel_event_data']['contactMedium'] for i in v['characteristic'] if isinstance(i,dict) if i['postcode'] == args_keys['postcode']]
            hosEventLogResult =[]
            #LogResult = json_loads(LogResult['hosel_event_data'])
            apilogger.debug("LogResult: %s" % LogResult)
            for v in LogResult:
                i = json_loads(v['hosel_event_data'])
                apilogger.debug("i: %s" % i)
                if "contactMedium" in i:
                    for j in i['contactMedium']:
                        for k in j['characteristic']:
                            if isinstance(k,dict):
                                if k['postcode'] == args_keys['postcode']:
                                    hosEventLogResult.append(v)
                                    break
                
            apilogger.debug("hosEventLogResult: %s" % hosEventLogResult)
            
            apilogger.debug("type of hosEventLogResult: %s" % type(hosEventLogResult))
            
        #return ((statusCode, {"overallStatus": "success","details": [{"validation": "success"},{"scheduler": "success"},{"userCreation": "success"},{"tenantCreation": "success"}]}))
        #result = [{'status':v['hosel_event_status']['overallStatus'],'details':v['hosel_event_status']['details'],'request':json_loads(v['hosel_event_data'])} for v in hosEventLogResult]
        result = []
        for v in hosEventLogResult:
            temp = {}
            temp['status'] = v['hosel_event_status']['overallStatus']
            # Original 
            # temp['details'] = v['hosel_event_status']['details'].replace('(','').replace(')','')
            # Test Code - Start
            try:
                apilogger.debug("v['hosel_event_status']['details'] : %s" % v['hosel_event_status']['details'])
                apilogger.debug("v['hosel_event_status']['details'] : %s" % type(v['hosel_event_status']['details']))
                temp['details'] = json_loads(v['hosel_event_status']['details'].replace('(','').replace(')','').replace('""',''))#.replace('"errorDesc": ["{"','"errorDesc": [{"').replace('"}}}"]}]','"}}}]}]').replace('"MySQL server','MySQL server').replace('"Connection reset by peer','Connection reset by peer'))
                apilogger.debug("temp['details'][AFTER] : %s" % temp['details'])
            except Exception as tmperr:
                apilogger.debug("Error - {%s} . Line No - {%s} " % (str(tmperr), str(sys_exc_info()[-1].tb_lineno)))
                temp['details'] = v['hosel_event_status']['details'].replace('(','').replace(')','').replace('""','')
            # Test Code - End
            temp['request'] = json_loads(v['hosel_event_data'])
            apilogger.debug("details: %s" % temp['details'])
            
            apilogger.debug("Type of details: %s" % type(temp['details']))
            result.append(temp)
        if len(result)>1:
            result = [{'status':v['hosel_event_status'],
                       "href":"http://172.16.177.58:11395/multitenancy/getDeleteUserDetails?id="+v['hosel_event_seq']
                       }for v in hosEventLogResult]
        statusMessage = result
        apilogger.debug(result)
        apilogger.info("statusCode   : %s" % statusCode)
        apilogger.info("statusMessage: %s" % statusMessage)


    except VALIDATION_ERRORS as cupverr:
        statusMessage = str(cupverr)
    except Exception as cupexp:
        statusCode = "500"
        statusMessage = "Error - {%s} . Line No - {%s} " % (str(cupexp), str(sys_exc_info()[-1].tb_lineno))
        apilogger.error(statusMessage)

        apilogger.info("statusCode   : %s" % statusCode)
        apilogger.info("statusMessage: %s" % statusMessage)

    if statusCode == "200":
        response = result
    else:
        response.update({"statusMessage": statusMessage})

    return ((statusCode, response))
Leave a Comment