Esempio n. 1
0
class Connections(object, metaclass=Singleton):
    def __init__(self):
        ''' 
            Description:    Initialization internal method, called internally
            usage:          Called internally
            Return:         N/A
        '''
        self.env = Environment()
        self.util = Utility()
        self.mongo = MongoDB()
        self.dbutil = DBUtility()
        self.globaL = Global()
        self.activity = Activity()
        self.member = Member()

        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)

    def __AddAConnection(self, argRequestDict):
        ''' This mehtod is for building a fresh new connection
            usage:          <__AddMember2MemberConnection(<argReqJsonDict>)
                            MainArg['MemberId','ConnectMemberId','Auth']
            Return:         Success/UnSuccess
        '''
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))
            ''' declaring/initializing variables '''
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isReqConnectionAdded = self.globaL._Global__False
            isInvConnectionAdded = self.globaL._Global__False
            isCleanUpDone = self.globaL._Global__False
            myArgKey = ['_id', 'Type', 'ConnectionId', 'ConnectionType']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' validating Requestor entity
            must be a valid id and its connection can not be same '''
            if myMainArgData['Type'] == self.globaL._Global__member:
                #validating
                if myMainArgData['_id'] == myMainArgData['ConnectionId']:
                    raise com.uconnect.core.error.MissingArgumentValues(
                        'Arg validation error, Member [{member}] and it\'s Connection[{connect}] can not be same'
                        .format(member=myMainArgData['_id'],
                                connect=myMainArgData['ConnectMemberId']))
                #fi
                myMemberValidationData = {
                    '_id': myMainArgData['ConnectionId'],
                    'ResponseMode': self.globaL._Global__InternalRequest
                }
                if (not self.member._Member__isAValidMember(
                        myMemberValidationData)):
                    raise com.uconnect.core.error.MissingArgumentValues(
                        'Arg validation error, Invalid MemberId [{member}]'.
                        format(member=myMainArgData['ConnectionId']))
                #fi
                myRequestorCollection = self.globaL._Global__memberColl
                # requestor is Member and it has been validated, preparing Invitee (revese)connection which will be a member
                # connection
                myInviteeCriteria = {'_id': myMainArgData['ConnectionId']}
                myInviteeConn = self.util.getConnTemplateCopy(
                    self.globaL._Global__member)
                myInviteeConn['Id'] = myMainArgData['_id']
                myInviteeConn['Status'] = self.util.getConnStatus4Action(
                    'New Connection', 'Invitee')
                myInviteeConnData = {'Connections': myInviteeConn}

                self.myModuleLogger.debug(
                    'Invitee [{invitee}] connection document [{doc}] prepared'.
                    format(invitee=myMainArgData['ConnectionId'],
                           doc=myInviteeConn))

            elif myMainArgData['Type'] == 'Agent':
                pass
            #fi

            #validating connection id
            if myMainArgData['ConnectionType'] == self.globaL._Global__member:
                # this is a member 2 member connection
                myMemberValidationData = {
                    '_id': myMainArgData['ConnectionId'],
                    'ResponseMode': self.globaL._Global__InternalRequest
                }
                if (not self.member._Member__isAValidMember(
                        myMemberValidationData)):
                    raise com.uconnect.core.error.MissingArgumentValues(\
                        'Arg validation error, Invalid Connect MemberId [{member}]'.format(member=myMainArgData['ConnectionId'] ))
                #fi
                myInviteeCollection = self.globaL._Global__memberColl
                # Preparing Requestor connection
                myRequestorCriteria = {'_id': myMainArgData['_id']}
                myRequestorConn = self.util.getConnTemplateCopy(
                    self.globaL._Global__member)
                myRequestorConn['Id'] = myMainArgData['ConnectionId']
                myRequestorConn['Status'] = self.util.getConnStatus4Action(
                    'New Connection', 'Requestor')
                myRequestorConnData = {'Connections': myRequestorConn}

                self.myModuleLogger.debug(
                    'Requestor [{requestor}] connection document [{doc}] prepared'
                    .format(requestor=myMainArgData['_id'],
                            doc=myRequestorConn))

            elif myMainArgData['ConnectionType'] == 'Agent':
                pass
            #fi

            #persisiting requestor connection data
            myReqConnectionResult = self.mongo.UpdateDoc(
                myRequestorCollection, myRequestorCriteria,
                myRequestorConnData, 'addToSet', False)
            if self.util.getUpdateStatus(
                    myReqConnectionResult) == self.globaL._Global__Success:
                # Requestor connection created successfully
                self.myModuleLogger.debug('Requestor connection [{conn}] created successfully, result [{result}]'.
                    format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + myMainArgData['ConnectionType']\
                            + ' ' + str(myMainArgData['ConnectionId']), result=myReqConnectionResult))

                isReqConnectionAdded = self.globaL._Global__True

                #building invitee connection (revese of requestor)
                myInvConnectionResult = self.mongo.UpdateDoc(
                    myInviteeCollection, myInviteeCriteria, myInviteeConnData,
                    'addToSet', False)
                if self.util.getUpdateStatus(
                        myInvConnectionResult) == self.globaL._Global__Success:
                    #invitee connection created successful
                    isInvConnectionAdded = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)

                    # recording this successful activity; requestor
                    self.activity._Activity__logActivity(self.util.buildActivityArg( \
                        myMainArgData['_id'], myRequestorCollection,self.globaL._Global__Internal,\
                        'Requestor Connection [{conn}] created successfully'.format(conn=myMainArgData['Type'] + ' ' + \
                        str(myMainArgData['_id']) + ' --> ' + myMainArgData['ConnectionType'] + ' ' + \
                        str(myMainArgData['ConnectionId'])) ))
                    #recording this successful activity; invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg(\
                        myMainArgData['_id'],myInviteeCollection,self.globaL._Global__Internal,\
                        'Invitee Connection [{conn}] created successfully'.format(conn=myMainArgData['ConnectionType'] + ' ' + \
                        str(myMainArgData['ConnectionId']) + ' --> ' + myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])) ))
                else:
                    ''' invitee connection is not successful, remvoving requestor connection to maintain the data integrity '''
                    self.myModuleLogger.debug('Invitee connection [{conn}] creation unsuccessful, result [{result}]'.
                        format(conn = myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])  + ' -> ' + \
                                myMainArgData['Type'] + ' ' + str(myMainArgData['_id']), result=myInvConnectionResult))
                    ''' rolling back previous Requestor connection'''
                    self.mongo.UpdateDoc(myInviteeCollection,
                                         myRequestorCriteria,
                                         myRequestorConnData, 'pull', False)
                    isCleanUpDone = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__UnSuccess,
                        'Could not build Invitee [{inv}] while performing "Add Connection" task'
                        .format(inv=myMainArgData['ConnectionId']))
                #fi
            else:
                self.myModuleLogger.debug('Requestor connection [{conn}] creation unsuccesful, result [{result}]'.
                    format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + myMainArgData['ConnectionType']\
                            + ' ' + str(myMainArgData['ConnectionId']), result=myReqConnectionResult))
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__UnSuccess,
                    'Could not build Requestor [{req}] while performing "Add Connection" task'
                    .format(req=myMainArgData['_id']))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            if isReqConnectionAdded and (not isInvConnectionAdded) and (
                    not isCleanUpDone):
                #print(isReqConnectionAdded,isInvConnectionAdded,isCleanUpDone)
                self.mongo.UpdateDoc(self.globaL._Global__memberColl,
                                     myRequestorCriteria, myRequestorConnData,
                                     'pull', False)
            #fi
            return myRequestStatus

    #__AddMember2MemberConnection Ends here

    def __acceptInvitation(self, argRequestDict):
        ''' This method is invoked by Invitee; update the status of connection status in each other (Requestor/Invitee)'s connection list 
            usage:          <__AcceptInvitation(<argReqJsonDict>)
                            MainArg['_id','Type','ConnectionId','ConnectionType','Auth']
            Return:         Success/UnSuccess
        '''
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))
            ''' declaring/initializing variables '''
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isReqConnectionAdded = self.globaL._Global__False
            isInvConnectionAdded = self.globaL._Global__False
            isCleanUpDone = self.globaL._Global__False

            if myMainArgData['Type'] == self.globaL._Global__member:
                myInviteeCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myInviteeCollection = self.globaL._Global__agentColl
            #fi

            if myMainArgData['ConnectionType'] == self.globaL._Global__member:
                myRequestorCollection = self.globaL._Global__memberColl
            elif myMainArgData['ConnectionType'] == self.globaL._Global__agent:
                myRequestorCollection = self.globaL._Global__agentColl
            #fi
            ''' validating arguments '''
            myArgKey = ['_id', 'Type', 'ConnectionId', 'ConnectionType']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' Validate auth key for this request (we dont need auth val since it has been already performed by BPS process,
            we need to ensure that any call to this process is from BPS process '''
            ''' we need to check if this is a valid request; is this invitation pending for this id (id is invitee)'''
            myInviValCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'],\
                                'Connections.Type': myMainArgData['ConnectionType'],\
                                'Connections.Status':self.util.getConnStatus4Action('New Connection','Invitee')}
            #print('Invitee validation',myInviValCriteria)
            if self.mongo.findTotDocuments(myInviteeCollection,
                                           myInviValCriteria) == 0:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Invalid Request, Invitee [{invitee}] does not have any connection pending from [{requestor}]'.\
                            format( invitee=myMainArgData['Type'] + str(myMainArgData['_id']),\
                                    requestor= myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) ))
            #fi
            # need to validate if this connectin is in wait state
            ''' Building Invitee connection data'''
            myInviteeCriteria = {
                '_id': myMainArgData['_id'],
                'Connections.Id': myMainArgData['ConnectionId']
            }
            #                     'Connections.Type': myMainArgData['ConnectionType'],\
            #                     'Connections.Status': self.util.getConnStatus4Action('New Connection','Invitee')}
            myInviteeConnData = {
                'Connections.$.Status':
                self.util.getConnStatus4Action('Accept Connection', 'Invitee')
            }
            ''' Building Requestor connection data '''
            myRequestorCriteria = {
                '_id': myMainArgData['ConnectionId'],
                'Connections.Id': myMainArgData['_id']
            }
            #                       'Connections.Type':myMainArgData['Type'],\
            #                       'Connections.Status': self.util.getConnStatus4Action('New Connection','Requestor')}
            myRequestorConnData = {
                'Connections.$.Status':
                self.util.getConnStatus4Action('Accept Connection',
                                               'Requestor')
            }
            ''' persisitng changes in database, Updating invitee's connection status '''
            myConnectionResult = self.mongo.UpdateDoc(myInviteeCollection,
                                                      myInviteeCriteria,
                                                      myInviteeConnData, 'set',
                                                      False)
            self.myModuleLogger.debug('Invitee connection status updated, [{conn}], result [{result}] '.
                format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                              myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                              result=myConnectionResult))

            if self.util.getUpdateStatus(
                    myConnectionResult) == self.globaL._Global__Success:
                # Invitee connection update is successful, persisiting Requestor's connection status update
                isInvConnStatusUpdated = self.globaL._Global__True
                myConnectionResult = self.mongo.UpdateDoc(
                    myRequestorCollection, myRequestorCriteria,
                    myRequestorConnData, 'set', False)
                self.myModuleLogger.debug('Requestor connection status updated, [{conn}], result [{result}] '.
                format(conn = myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])  + ' -> ' + \
                              myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),\
                              result=myConnectionResult))

                if self.util.getUpdateStatus(
                        myConnectionResult) == self.globaL._Global__Success:
                    ''' Requestor connection update is successful, undo Invitee connection change '''
                    isInvConnStatusUpdated = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)
                    # recording this successful activity; Invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg( \
                        myMainArgData['_id'], myRequestorCollection,self.globaL._Global__Internal,\
                        'Invitee accepted connection [{conn}] '.format(conn=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']) + \
                        ' --> ' + myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])) ))
                    #recording this successful activity; invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg(\
                        myMainArgData['_id'],myInviteeCollection,self.globaL._Global__Internal,\
                        'Requestor connection [{conn}] status updated'.format(conn=myMainArgData['ConnectionType'] + ' ' + \
                        str(myMainArgData['ConnectionId']) + ' --> ' + myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])) ))

                else:
                    ''' Requestor connection update is not successful, undo Invitee connection change '''
                    self.myModuleLogger.debug(
                        'Requestor [{req}] connection update unsuccessful, results [{result}]'
                        .format(req=myMainArgData['Connectiontype'] + ' ' +
                                str(myMainArgData['ConnectionId']),
                                result=myReqConnResults))

                    myInviteeConnData = {
                        'Connections.$.Status':
                        self.util.getConnStatus4Action('New Connection',
                                                       'Invitee')
                    }
                    self.mongo.UpdateDoc(myInviteeCollection,
                                         myInviteeCriteria, myInviteeConnData,
                                         'set', False)
                    isCleanUpDone = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                        'Requestor [{req}] connection status [{status}] update unsuccessful'.\
                        format(req=myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']), \
                               status=self.globaL._Global__Accepted_Req_ConnectionStatus))
                    self.myModuleLogger.debug('undo changes to Invitee\'s connection successful, result [{result}]'.\
                        format(result=myReqConnResults))
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    'Invitee [{inv}] connection status [{status}] update unsuccessful'. \
                    format(inv= myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),
                            status=self.globaL._Global__Accepted_Inv_ConnectionStatus))
            #fi
            return myRequestStatus
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            ''' we need to ensure if cleanup is required should there be an issue during failure of Invitee connection '''
            if isInvConnStatusUpdated and (not isReqConnStatusUpdated) and (
                    not isCleanUpDone):
                myInviteeConnData = {
                    'Connections.$.Status':
                    self.util.getConnStatus4Action('New Connection', 'Invitee')
                }
                self.mongo.UpdateDoc(myInviteeCollection, myInviteeCriteria,
                                     myInviteeConnData, 'set', False)
            #fi
            return myRequestStatus

    #__AcceptInvitation Ends here

    def __rejectInvitation(self, argRequestDict):
        ''' This method is invoked by Invitee; remove the connection from each other (Requestor/Invitee)'s connection list 
            usage:          <__rejectInvitation(<argReqJsonDict>)
                            MainArg['_id','Type','ConnectionId','ConnectionType','Auth']
            Return:         Success/UnSuccess
        '''
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))
            ''' declaring/initializing variables '''
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isInvConnStatusRemoved = self.globaL._Global__False
            isCleanUpDone = self.globaL._Global__False

            if myMainArgData['Type'] == self.globaL._Global__member:
                myInviteeCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myInviteeCollection = self.globaL._Global__agentColl
            #fi

            if myMainArgData['ConnectionType'] == self.globaL._Global__member:
                myRequestorCollection = self.globaL._Global__memberColl
            elif myMainArgData['ConnectionType'] == self.globaL._Global__agent:
                myRequestorCollection = self.globaL._Global__agentColl
            #fi
            ''' validating arguments '''
            myArgKey = ['_id', 'Type', 'ConnectionId', 'ConnectionType']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' Validate auth key for this request (we dont need auth val since it has been already performed by BPS process,
            we need to ensure that any call to this process is from BPS process '''
            ''' we need to check if this is a valid request; is this invitation pending for this id (id is invitee)'''
            myInviValCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'],\
                                'Connections.Type': myMainArgData['ConnectionType'],\
                                'Connections.Status':self.util.getConnStatus4Action('New Connection','Invitee')}

            #print('Invitee validation',myInviValCriteria)
            if self.mongo.findTotDocuments(myInviteeCollection,
                                           myInviValCriteria) == 0:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Invalid Request, Invitee [{invitee}] does not have pending connection from [{requestor}]'.\
                            format( invitee=myMainArgData['Type'] + str(myMainArgData['_id']),\
                                    requestor= myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) ))
            #fi
            ''' Building Invitee connection data to be removed'''
            myInviteeCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'], \
                                 'Connections.Type': myMainArgData['ConnectionType'],\
                                 'Connections.Status': self.util.getConnStatus4Action('New Connection','Invitee')}
            myInviteeConnData = {'Connections':{'Id': myMainArgData['ConnectionId'],'Type': myMainArgData['ConnectionType'],\
                                                'Status' : self.util.getConnStatus4Action('New Connection','Invitee')}}
            ''' Building Requestor connection data to be removed'''
            myRequestorCriteria = {'_id':myMainArgData['ConnectionId'], 'Connections.Id':myMainArgData['_id'],\
                                   'Connections.Type':myMainArgData['Type'],\
                                   'Connections.Status': self.util.getConnStatus4Action('New Connection','Requestor')}
            myRequestorConnData = {'Connections':\
                                        {'Id': myMainArgData['_id'],'Type': myMainArgData['Type'],\
                                         'Status' : self.util.getConnStatus4Action('New Connection','Requestor')}}
            ''' building backup data '''
            myInviteeConnBkupData = self.util.extr1stDocFromResultSets(\
                self.mongo.findDocument(myInviteeCollection,myInviteeCriteria,{'_id':1,'Connections':1},True))
            myRequestorConnBkupData = self.util.extr1stDocFromResultSets(\
                self.mongo.findDocument(myRequestorCollection,myRequestorCriteria,{'_id':1,'Connections':1},True))
            ''' persisitng changes in database, removing invitee's connection '''
            myConnectionResult = self.mongo.UpdateDoc(myInviteeCollection,
                                                      myInviteeCriteria,
                                                      myInviteeConnData,
                                                      'pull', False)

            self.myModuleLogger.debug('Invitee rejected request, connection [{conn}] removed, result [{result}] '.
                format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                          myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                          result=myConnectionResult))

            if self.util.getUpdateStatus(
                    myConnectionResult) == self.globaL._Global__Success:

                # Invitee's connection removed.  removing Requestor's connection
                isInvConnStatusRemoved = self.globaL._Global__True
                myConnectionResult = self.mongo.UpdateDoc(
                    myRequestorCollection, myRequestorCriteria,
                    myRequestorConnData, 'pull', False)
                self.myModuleLogger.debug('Invitee rejected request, Requestor connection [{conn}] removed, result [{result}] '.
                    format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                              myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                              result=myConnectionResult))

                if self.util.getUpdateStatus(
                        myConnectionResult) == self.globaL._Global__Success:

                    # Requestor connection update is successful, undo Invitee connection change
                    isInvConnStatusRemoved = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)

                    # recording this successful activity; Invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg( \
                        myMainArgData['_id'], myRequestorCollection,self.globaL._Global__Internal,\
                        'Invitee rejected connection [{conn}], removing this connection '.format(conn=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']) + \
                        ' --> ' + myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])) ))

                    #recording this successful activity; invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg(\
                        myMainArgData['_id'],myInviteeCollection,self.globaL._Global__Internal,\
                        'Invitee rejected connection [{conn}], removing this connection'.format(conn=myMainArgData['ConnectionType'] + ' ' + \
                        str(myMainArgData['ConnectionId']) + ' --> ' + myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])) ))
                else:
                    ''' Requestor connection update is not successful, undo Invitee connection change '''
                    self.myModuleLogger.debug(
                        'Requestor [{req}] connection update unsuccessful, results [{result}]'
                        .format(req=myMainArgData['Connectiontype'] + ' ' +
                                str(myMainArgData['ConnectionId']),
                                result=myReqConnResults))

                    self.mongo.UpdateDoc(myInviteeCollection, myInviteeCriteria, \
                        {'Connections':{myInviteeConnBkupData['Connections'][0]}}, 'addToSet',False)

                    isCleanUpDone = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                        'Requestor [{req}] connection restored'.format(req=myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']) ))

                    self.myModuleLogger.debug('undo changes to Invitee\'s connection successful, result [{result}]'.\
                        format(result=myReqConnResults))
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    'Invitee [{inv}] connection status [{status}] update unsuccessful'. \
                    format(inv= myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),
                            status=self.globaL._Global__Accepted_Inv_ConnectionStatus ))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            ''' we need to ensure if cleanup is required should there be an issue during failure of Invitee connection '''
            if isInvConnStatusRemoved and (not isReqConnStatusUpdated) and (
                    not isCleanUpDone):
                myInviteeConnData = {
                    'Connections.$.Status':
                    self.util.getConnStatus4Action('New Connection', 'Invitee')
                }
                self.mongo.UpdateDoc(myInviteeCollection, myInviteeCriteria,
                                     myInviteeConnData, 'set', False)
            #fi
            return myRequestStatus

    #__rejectInvitation end here

    def __removeConnection(self, argRequestDict):
        ''' Removes the connection from each other (Requestor/Requestee)'s connection list 
            usage:          <__rejectInvitation(<argReqJsonDict>)
                            MainArg['_id','Type','ConnectionId','ConnectionType','Auth']
            Return:         Success/UnSuccess
            Requestor   --> who initiated the removal of a connection
            Requestee   --> whose connection to be removed from requestor
            Connection will be removed from Requestor/Requstee's conneciton list for each other 
        '''
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))
            ''' declaring/initializing variables '''
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isRequestorConnRemoved = self.globaL._Global__False
            isRequesteeConnRemoved = self.globaL._Global__False
            isCleanUpDone = self.globaL._Global__False

            if myMainArgData['Type'] == self.globaL._Global__member:
                myRequestorCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myRequestorCollection = self.globaL._Global__agentColl
            #fi

            if myMainArgData['ConnectionType'] == self.globaL._Global__member:
                myRequesteeCollection = self.globaL._Global__memberColl
            elif myMainArgData['ConnectionType'] == self.globaL._Global__agent:
                myRequesteeCollection = self.globaL._Global__agentColl
            #fi
            ''' validating arguments '''
            myArgKey = ['_id', 'Type', 'ConnectionId', 'ConnectionType']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' Validate auth key for this request (we dont need auth val since it has been already performed by BPS process,
            we need to ensure that any call to this process is from BPS process '''
            ''' we need to check if this is a valid request; is this invitation pending for this id (id is invitee)'''
            myRequestorValCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'],\
                                'Connections.Type': myMainArgData['ConnectionType']}

            if self.mongo.findTotDocuments(myRequestorCollection,
                                           myRequestorValCriteria) == 0:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Invalid Request, Requestor [{requestor}] does not have any connection from [{requestee}] to be removed'.\
                            format( requestor=myMainArgData['Type'] + str(myMainArgData['_id']),\
                                    requestee= myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) ))
            #fi
            ''' Building Invitee connection data to be removed'''
            myRequestorCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'], \
                                 'Connections.Type': myMainArgData['ConnectionType']}
            myRequestorConnData = {
                'Connections': {
                    'Id': myMainArgData['ConnectionId'],
                    'Type': myMainArgData['ConnectionType']
                }
            }
            ''' Building Requestor connection data to be removed'''
            myRequesteeCriteria = {'_id':myMainArgData['ConnectionId'], 'Connections.Id':myMainArgData['_id'],\
                                   'Connections.Type':myMainArgData['Type']}
            myRequesteeConnData = {
                'Connections': {
                    'Id': myMainArgData['_id'],
                    'Type': myMainArgData['Type']
                }
            }
            ''' building backup data '''
            myRequestorConnBkupData = self.util.extr1stDocFromResultSets(\
                self.mongo.findDocument(myRequestorCollection,myRequestorCriteria,{'_id':1,'Connections':1},True))
            myRequesteeConnBkupData = self.util.extr1stDocFromResultSets(\
                self.mongo.findDocument(myRequesteeCollection,myRequesteeCriteria,{'_id':1,'Connections':1},True))
            ''' persisitng changes in database, removing invitee's connection '''
            myConnectionResult = self.mongo.UpdateDoc(myRequestorCollection,
                                                      myRequestorCriteria,
                                                      myRequestorConnData,
                                                      'pull', False)

            self.myModuleLogger.debug('Requestor connection [{conn}] removed, result [{result}] '.
                format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                          myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                          result=myConnectionResult))

            if self.util.getUpdateStatus(
                    myConnectionResult) == self.globaL._Global__Success:

                # Requestor's connection removed.  removing Requestor's connection
                isRequestorConnRemoved = self.globaL._Global__True
                myConnectionResult = self.mongo.UpdateDoc(
                    myRequesteeCollection, myRequesteeCriteria,
                    myRequesteeConnData, 'pull', False)

                self.myModuleLogger.debug('Requestee connection [{conn}] removed, result [{result}] '.
                    format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                              myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                              result=myConnectionResult))

                if self.util.getUpdateStatus(
                        myConnectionResult) == self.globaL._Global__Success:
                    ''' Requestor connection update is successful, undo Requestor connection change '''
                    isRequesteeConnRemoved = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)

                    # recording this successful activity; Requestor
                    self.activity._Activity__logActivity(self.util.buildActivityArg( \
                        myMainArgData['_id'], myRequestorCollection,self.globaL._Global__Internal,\
                        'Requestor [{req}] removed connection [{conn}]'.\
                            format(req=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),\
                                    conn=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']) + ' --> ' + \
                                    myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])) ))

                    #recording this successful activity; Requestee
                    self.activity._Activity__logActivity(self.util.buildActivityArg(\
                        myMainArgData['_id'],myRequesteeCollection,self.globaL._Global__Internal,\
                        'Requestor [{req}] removed connection, removing connection [{conn}] from requestee'.\
                            format(req=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']), \
                                conn=myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']) + ' --> ' + \
                                myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])) ))
                else:
                    ''' Requestee connection update is not successful, undo Requestor connection change '''
                    self.myModuleLogger.debug(
                        'Requestee [{req}] connection update unsuccessful, results [{result}]'
                        .format(req=myMainArgData['Connectiontype'] + ' ' +
                                str(myMainArgData['ConnectionId']),
                                result=myReqConnResults))

                    self.mongo.UpdateDoc(myRequestorCollection, myRequestorCriteria, \
                        {'Connections':{myRequestorConnBkupData['Connections'][0]}}, 'addToSet',False)

                    isCleanUpDone = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                        'Requestor [{req}] connection restored'.format(req=myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']) ))
                    self.myModuleLogger.debug('undo changes to Requestor\'s connection successful, result [{result}]'.\
                        format(result=myReqConnResults))
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    'Requestor [{req}] connection status [{status}] update unsuccessful'. \
                    format(req= myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),
                            status=self.globaL._Global__Accepted_Inv_ConnectionStatus ))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            ''' we need to ensure if cleanup is required should there be an issue during failure of Invitee connection '''
            if isRequestorConnRemoved and (not isRequesteeConnRemoved) and (
                    not isCleanUpDone):
                self.mongo.UpdateDoc(myRequestorCollection, myRequestorCriteria, \
                    {'Connections':{myRequestorConnBkupData['Connections'][0]}}, 'addToSet',False)
            #fi
            return myRequestStatus
        #__reoveConnection Ends here

    def __favoriteConnection(self, argRequestDict):
        ''' 
            Description:    Change favorite of a connection
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
            usage:          <__MarkConnectionFavorite(<argReqJsonDict>)
                            MainArg{'_id','Type','ConnectionId','ConnectionType','Favorite'}
            Return:         Json object
        '''
        try:
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            # validating arguments
            myArgKey = [
                '_id', 'Type', 'ConnectionId', 'ConnectionType', 'Favorite'
            ]
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            myArgValidationResults = self.util.valRequiredArg(
                myMainArgData, myArgKey)

            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            if myMainArgData['Favorite'] not in ["0", "1"]:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Expecting favorite value in ["0","1"], got [{favorite}]'.format(favorite=myMainArgData['Favorite']))
            #fi

            if myMainArgData['Type'] == self.globaL._Global__member:
                myCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myCollection = self.globaL._Global__agentColl
            #fi

            # validating this connection
            myValidConnectionArg = {'_id':myMainArgData['_id'], 'Connections.Id':myMainArgData['ConnectionId'], \
                                    'Connections.Type': myMainArgData['ConnectionType'],\
                                    'Connections.Status' :{'$in':['Accepted','Valid']}}
            if self.mongo.findTotDocuments(myCollection,
                                           myValidConnectionArg) == 0:
                raise com.uconnect.core.error.MissingArgumentValues('No connection found for this request [{request}]'.\
                    format( request=myMainArgData['Type'] + str(myMainArgData['_id']) + ': Connection(' + \
                        myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) + ')' ))
            #fi
            ''' Preparing document:    '''
            #myCriteria = {'_id':myMainArgData['_id'],'Connections.Id': myMainArgData['ConnectionId'], \
            #                'Connections.Type':myMainArgData['ConnectionType']}
            myCriteria = {
                '_id': myMainArgData['_id'],
                'Connections.Id': myMainArgData['ConnectionId']
            }
            myFavoriteData = {
                "Connections.$.Favorite": int(myMainArgData['Favorite'])
            }

            ##db.Member.update({'_id':313848,'LinkedBy.MemberId':313850},{ $set : {'LinkedBy.$.Favorite':1}})
            myMarkFavoriteStatus = self.mongo.UpdateDoc(
                myCollection, myCriteria, myFavoriteData, 'set', False)
            #print('Favorite Status:',myMarkFavoriteStatus)
            if self.util.getUpdateStatus(
                    myMarkFavoriteStatus) == self.globaL._Global__Success:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__Success)
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    myMarkFavoriteStatus.get('Message'))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus
            #fi
        #__favoriteConnection Ends here

    def __blockConnection(self, argRequestDict):
        ''' 
            Description:    Change block of a connection
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
            usage:          <__blockConnection(<argReqJsonDict>)
                            MainArg{'_id','Type','ConnectionId','ConnectionType','Favorite'}
            Return:         Json object
        '''
        try:
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            # validating arguments
            myArgKey = [
                '_id', 'Type', 'ConnectionId', 'ConnectionType', 'Blocked'
            ]
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)

            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            if myMainArgData['Blocked'] not in ["0", "1"]:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Expecting blocked value in ["0","1"], got [{block}]'.format(block=myMainArgData['Blocked']))
            #fi

            if myMainArgData['Type'] == self.globaL._Global__member:
                myCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myCollection = self.globaL._Global__agentColl
            #fi

            # validating this connection
            myValidConnectionArg = {'_id':myMainArgData['_id'], 'Connections.Id':myMainArgData['ConnectionId'], \
                                    'Connections.Type': myMainArgData['ConnectionType'],\
                                    'Connections.Status' :{'$in':['Accepted','Valid']}}

            if self.mongo.findTotDocuments(myCollection,
                                           myValidConnectionArg) == 0:
                raise com.uconnect.core.error.MissingArgumentValues('No connection found for this request [{request}]'.\
                    format( request=myMainArgData['Type'] + str(myMainArgData['_id']) + ': Connection(' + \
                        myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) + ')' ))
            #fi
            ''' Preparing document:    '''
            myCriteria = {
                '_id': myMainArgData['_id'],
                'Connections.Id': myMainArgData['ConnectionId']
            }
            myFavoriteData = {
                "Connections.$.Blocked": int(myMainArgData['Blocked'])
            }

            ##db.Member.update({'_id':313848,'LinkedBy.MemberId':313850},{ $set : {'LinkedBy.$.Favorite':1}})
            myBlockedStatus = self.mongo.UpdateDoc(myCollection, myCriteria,
                                                   myFavoriteData, 'set',
                                                   False)
            #print('Blocked Status:',myBlockedStatus)
            if self.util.getUpdateStatus(
                    myBlockedStatus) == self.globaL._Global__Success:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__Success)
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    myBlockStatus.get('Message'))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus
Esempio n. 2
0
class Group(object, metaclass=Singleton):
    def __init__(self):
        ''' 
            Description:    Initialization internal method, called internally
            usage:          Called internally
            Return:         N/A
        '''
        self.util = Utility()
        self.mongo = MongoDB()
        self.globaL = Global()
        self.member = Member()
        self.activity = Activity()

        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)

    def __buildInitGroupData(self, argRequestDict):

        #argMainDict,argAddressDict,argContactDict
        try:
            # Preparing document:

            #self.myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            myMainArgData = self.util.getCopy(argRequestDict)
            ''' validating arguments '''
            myArgKey = ['GroupName', 'OwnerMemberId']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myInitGroupData = self.util.getTemplateCopy(
                self.globaL._Global__group)
            myInitGroupData['Main']['GroupName'] = myMainArgData['GroupName']
            myInitGroupData['Main']['OwnerMemberId'] = myMainArgData[
                'OwnerMemberId']
            myGroupId = self.mongo.genKeyForCollection(
                self.globaL._Global__groupColl)
            myInitGroupData['_id'] = myGroupId
            ''' build initial history data '''
            myInitGroupData[
                self.globaL.
                _Global__HistoryColumn] = self.util.buildInitHistData()
            self.myModuleLogger.info(
                'Data [{arg}] returned'.format(arg=myInitGroupData))

            return myInitGroupData

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    #__buildInitGroupData Ends here

    def __buildGetAllGroupMemberPipeline(self, argRequestDict):
        #argMemberId, argConnectionType
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            myMainArgData = self.util.getCopy(argRequestDict)
            myArgKey = ['GroupId']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)

            myGroupId = myMainArgData['GroupId']

            self.myModuleLogger.debug(
                'Building pipeline for aggregate function, for retrieving group member information'
            )

            myFromCollection = self.globaL._Global__memberColl
            myPipeLine = [{
                "$match": {
                    "_id": myGroupId
                }
            }, {
                "$unwind": {
                    "path": "$Participants",
                    "preserveNullAndEmptyArrays": True
                }
            }, {
                "$lookup": {
                    "from": "Member",
                    "localField": "Participants.MemberId",
                    "foreignField": "_id",
                    "as": "Participants"
                }
            }, {
                "$project": {
                    "_id": 1,
                    "Main": 1,
                    "Participants._id": 1,
                    "Participants.Main": 1
                }
            }, {
                "$sort": {
                    "Participants.Main.LastName": 1
                }
            }]
            #fi
            myRequestStatus = self.util.getRequestStatus(
                self.globaL._Global__Success)
            myRequestStatus.update({'Data': myPipeLine})
            #print(myRequestStatus)
            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    #__buildGetAllConnPipeline Ends here

    def __formatParticipantsData(self, argRequestDict):
        try:

            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict['MainArg'])
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)

            myAllParticipantsData = []
            for myParticipant in myMainArgData:
                # we need to make sure Participants array is not empty
                if len(myParticipant['Participants']) > 0:
                    myAllParticipantsData.append(\
                        {'MemberId':myParticipant['Participants'][0]['_id'],'Main':myParticipant['Participants'][0]['Main']})
                #fi
            myResponse = {
                '_id': myMainArgData[0]['_id'],
                'Main': myMainArgData[0]['Main'],
                'Participants': myAllParticipantsData
            }
            return myResponse
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            # we would return error in main
            return {'Main': myRequestStatus}

    def __isValidGroupForMember(self, argRequestDict):
        try:

            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict['MainArg'])
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)

            myArgKey = ['MemberId', 'GroupId']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            myCriteria = {
                '_id': myMainArgData['GroupId'],
                'Main.OwnerMemberId': myMainArgData['MemberId']
            }
            myGroupCount = self.mongo.findTotDocuments(
                self.globaL._Global__groupColl, myCriteria)
            if myGroupCount == 0:
                return self.globaL._Global__False
            else:
                return self.globaL._Global__True
            return myResponse
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            # we would return error in main
            return self.globaL._Global__Error

    def __createAMemGroup(self, argRequestDict):
        ''' 
            Description:    Create a Member's group
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'MainArg': {'GroupName':'<GroupName>','MeberId':'<owner of group>'}}
            usage:          <createAMemGroup(<argRequestDict>)
            Return:         Json object
            Collection:     Group: Insert a record in Group collection
        '''
        try:

            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict['MainArg'])
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            ''' validating arguments '''
            myArgKey = ['Main']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myArgKey = ['GroupName', 'OwnerMemberId']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData['Main'], myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            # validating memberid (owner of this group)
            myMemberValArg = {
                '_id': myMainArgData['Main']['OwnerMemberId'],
                'ResponseMode': self.globaL._Global__InternalRequest
            }
            self.myModuleLogger.debug(myMemberValArg)
            if not (self.member._Member__isAValidMember(myMemberValArg)):
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Invalid member [{member}]'.format(member=myParticipant['_id']))

            # validating group name, if its already in use by this member
            myGroupNameValArg = myMainArgData['Main']
            if self.__isAMemberGroupInUse(myGroupNameValArg):
                raise com.uconnect.core.error.DuplicateGroup('Duplicate group [{group}]'.\
                    format(group=myMainArgData['Main']['GroupName']))
            #fi

            # Preparing document:
            myGroupData = self.__buildInitGroupData(myMainArgData['Main'])
            self.myModuleLogger.info(
                'Creating new Group, data [{doc}]'.format(doc=myGroupData))

            #persisting group data
            #print(myGroupData)
            myDbResult = self.mongo.InsertOneDoc(
                self.globaL._Global__groupColl, myGroupData)
            myGroupId = myDbResult['_id']
            myGroupResultStatus = self.util.getCreateStatus(myDbResult)
            self.myModuleLogger.debug(
                'Group id [{id}] created, status[{status}] '.format(
                    id=myGroupId, status=myGroupResultStatus))

            # we need to add owner of this group as a 1st participant
            if myGroupResultStatus == self.globaL._Global__Success:
                myParticipantArgData = \
                    {'_id': myGroupId, 'ResponseMode': self.globaL._Global__InternalRequest,\
                     'Participants':[{'MemberId': myMainArgData['Main']['OwnerMemberId'], 'Action': 'Add'}]}
                myDbStatus = self.__updateGroupParticipants(
                    myParticipantArgData)
                #print('Db Status',myDbStatus, myDbStatus)
                if myDbStatus['Status'] == self.globaL._Global__Success:
                    #print('Status is Success')
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)
                    myRequestStatus['Data'] = {'_id': myGroupId}
                else:
                    # removing newly created group
                    self.mongo.DeleteDoc(self.globaL._Global__groupColl,
                                         {'_id': myGroupId}, False)
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__UnSuccess,
                        myDbStatus.get('Message'))
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__UnSuccess)
            #fi

            return myRequestStatus
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    #end

    def __updateGroupMain(self, argRequestDict):
        '''
            Update Group attribute; only Group Name can be changed
        '''
        try:
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict['MainArg'])
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))

            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            myArgKey = ['_id', 'GroupName']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            myCriteria = {'_id': myMainArgData['_id']}
            myGroupData = {'Main.GroupName': myMainArgData['GroupName']}
            myDbResult = self.mongo.UpdateDoc(self.globaL._Global__groupColl,
                                              myCriteria, myGroupData, 'set',
                                              False)
            if self.util.getUpdateStatus(
                    myDbResult) == self.globaL._Global__Success:
                myRequestStatus = self.util.getUpdateStatus(
                    self.globaL._Global__Success)
            else:
                myRequestStatus = self.util.getUpdateStatus(self.globaL._Global__UnSuccess,\
                    ' DB result [{result}]'.format(result=myDbResult))
            #fi
            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    def __updateGroupParticipants(self, argRequestDict):
        ''' 
            Description:    updating Group participants (Add/Remove)
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'_id':'','Participants':['MemberId']}}
            usage:          <createAMemGroup(<argRequestDict>)
            Return:         Json object
            Collection:     Group: add a participant to group
        '''
        try:

            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict['MainArg'])
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            myArgKey = ['_id', 'Participants']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            # Participants validation and adding to group
            if self.util.isList(myMainArgData['Participants']):
                myAllParticipantsList = myMainArgData['Participants']
            else:
                myAllParticipantsList = [myMainArgData['Participants']]
            #fi

            # adding participant to group
            myArgKey = ['MemberId', 'Action']
            myCriteria = {'_id': myMainArgData['_id']}
            # need to get the group owner information to ensure group owner is not removed from participants

            myGrouResult = self.mongo.findDocument(\
                self.globaL._Global__groupColl, myCriteria, {'Main.OwnerMemberId':1,'_id':0}, False)

            myGroupOwnerId = self.util.extr1stDocFromResultSets(
                myGrouResult)['Main']['OwnerMemberId']

            #print(myAllParticipantsList)

            for myParticipant in myAllParticipantsList:
                ''' validating Participant arguments '''
                myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                    myParticipant, myArgKey)
                if not (myArgValidation):
                    raise com.uconnect.core.error.MissingArgumentValues(
                        myArgValMessage)
                #fi
                myParticipantsData = {
                    'Participants': {
                        'MemberId': myParticipant['MemberId']
                    }
                }
                myMemberValidationArg = {
                    '_id': myParticipant['MemberId'],
                    'ResponseMode': self.globaL._Global__InternalRequest
                }
                myExecuteOperation = False

                if (myParticipant['Action']
                        == 'Add') and (self.member._Member__isAValidMember(
                            myMemberValidationArg)):
                    myOperation = 'addToSet'
                    myIncrementValue = 1
                    myExecuteOperation = True
                elif (myParticipant['Action'] == 'Remove') and (
                        not (myParticipant['MemberId'] == myGroupOwnerId)):
                    myOperation = 'pull'
                    myIncrementValue = -1
                    myExecuteOperation = True
                #fi
                if myExecuteOperation:
                    myDbResult = self.mongo.UpdateDoc(
                        self.globaL._Global__groupColl, myCriteria,
                        myParticipantsData, myOperation, False)
                    if self.util.getUpdateStatus(
                            myDbResult) == self.globaL._Global__Success:
                        self.mongo.UpdateDoc(
                            self.globaL._Global__groupColl, myCriteria,
                            {'Main.TotalParticipants': myIncrementValue},
                            'inc', False)
                    #
                #
            #end for

            #building response
            myRequestStatus = self.util.getRequestStatus(
                self.globaL._Global__Success)
            return myRequestStatus
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    #end

    def __isAMemberGroupInUse(self, argRequestDict):
        ''' check if the group name is already in use for this member'''
        try:
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isGroupNameInUse = self.globaL._Global__False

            # validating arguments
            myArgKey = ['GroupName', 'OwnerMemberId']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myCriteria = {
                'Main.GroupName': myMainArgData['GroupName'],
                'Main.OwnerMemberId': myMainArgData['OwnerMemberId']
            }

            if self.mongo.findTotDocuments(self.globaL._Global__groupColl,
                                           myCriteria) > 0:
                #print('group found',self.globaL._Global__groupColl,myCriteria)
                return self.globaL._Global__True
            else:
                return self.globaL._Global__False
            #fi

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise
Esempio n. 3
0
class Member(object, metaclass=Singleton):
    def __init__(self):
        ''' 
            Description:    Initialization internal method, called internally
            usage:          Called internally
            Return:         N/A
        '''
        self.env = Environment()
        self.util = Utility()
        self.mongo = MongoDB()
        self.dbutil = DBUtility()
        self.globaL = Global()
        self.sec = Security()

        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)

    def __buildArg4IsAValidMember(self, argMemberId, argAuthKey, argEntityId,
                                  argEntityType):

        return {
            'MemberId': argMemberId,
            'EntityId': argEntityId,
            'EntityType': argEntityType,
            'AuthKey': argAuthKey
        }

    def __updateMemberTag(self, argRequestDict):
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)

            myMainArgData = self.util.getCopy(argRequestDict)
            myArgKey = ['_id']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' preparing pipeline for aggregate function '''
            myAggregateColl = self.globaL._Global__memberColl
            #myPipeLine=[{"$match":{"_id":myMainArgData['_id']}},{"$unwind":"$Contact"},{"$addFields": { "Tag": { "$concat":["$Main.LastName", " , ", "$Main.FirstName"," , ","$Address.City"," ", "$Address.State", " , ", "$Contact.Value"] }}},{"$project": { "Tag":1, "_id":0 }}]
            # tag filed is Main.LastName, Main.FirstName, Address.City/State, Contact.Email
            myPipeLine = [{
                "$match": {
                    "_id": myMainArgData['_id']
                }
            }, {
                "$addFields": {
                    "Tag": {
                        "$concat": [
                            "$Main.LastName", " , ", "$Main.FirstName", " , ",
                            "$Address.City", " ", "$Address.State", " , ",
                            "$Contact.Email"
                        ]
                    }
                }
            }, {
                "$project": {
                    "Tag": 1,
                    "_id": 0
                }
            }]
            myAggregateCommand = {
                "aggregate": myAggregateColl,
                "pipeline": myPipeLine
            }

            self.myModuleLogger.debug(
                'pipeline [{pipeline}] will be used to build Tag for member [{member}]'
                .format(pipeline=myPipeLine, member=myMainArgData['_id']))
            ''' executing aggregate command to get Tag information '''
            myTagResult = self.mongo.ExecCommand(myAggregateCommand)

            self.myModuleLogger.debug(
                'Tag [{tag}] built'.format(tag=myTagResult))
            #print('tag result:',myTagResult)

            if 'result' in myTagResult:
                myTagData = [
                    tag.upper() for tag in [myTagResult['result'][0]['Tag']]
                ]
                #print('tag:',myTagData[0],tuple(myTagData))
                myTagUpdateData = {'Tag': myTagData}
                myTagUpdateResult = self.mongo.UpdateDoc(
                    self.globaL._Global__memberColl, myMainArgData,
                    myTagUpdateData, 'set')
                if self.util.getUpdateStatus(
                        myTagUpdateResult) == self.globaL._Global__Success:
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)
                else:
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__UnSuccess)
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__UnSuccess)
                self.myModuleLogger.exception(
                    'Could not build tag for this member, Error [{myerror}]'.
                    format(myerror='result key is missing' + myTagResult))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    def __buildInitMembderData(self, argRequestDict):

        #argMainDict,argAddressDict,argContactDict
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            myMainArgData = self.util.getCopy(argRequestDict)
            myArgKey = ['Main', 'Address', 'Contact']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myMainDict = myMainArgData['Main']
            myAddressDict = myMainArgData['Address']
            myContactDict = myMainArgData['Contact']

            myZipCode = myAddressDict['ZipCode']
            myCityNState = self.util.getAddressCityState(myZipCode)
            myCity = myCityNState[0]
            myState = myCityNState[1]
            myMemberTag = []
            myInitMemberData = self.util.getTemplateCopy(
                self.globaL._Global__member)
            #myModuleLogger.debug('Member template [{template}]'.format(template=myInitMemberData))
            ''' Main '''
            if ('LastName' in myMainDict):
                myInitMemberData['Main']['LastName'] = myMainDict['LastName']
                myMemberTag.append(myMainDict['LastName'])
            #fi
            if ('FirstName' in myMainDict):
                myInitMemberData['Main']['FirstName'] = myMainDict['FirstName']
                myMemberTag.append(myMainDict['FirstName'])
            #fi
            if ('NickName' in myMainDict):
                myInitMemberData['Main']['NickName'] = myMainDict['NickName']
                myMemberTag.append(myMainDict['NickName'])
            #fi
            if ('Type' in myMainDict):
                myInitMemberData['Main']['Type'] = myMainDict['Type']
            else:
                myInitMemberData['Main'][
                    'Type'] = self.globaL._Global__Participant
            #fi
            ''' Address '''
            if ('Street' in myAddressDict):
                myInitMemberData['Address']['Street'] = myAddressDict['Street']
                #myMemberTag.append(myAddressDict['Street'])
            #fi
            if (not (myCity == None)) and (not (myState == None)):
                myInitMemberData['Address']['City'] = myCity
                myInitMemberData['Address']['State'] = myState
                myInitMemberData['Address']['ZipCode'] = myZipCode
                #myMemberTag.extend([myCity,myState])
            else:
                myInitMemberData['Address']['ZipCode'] = myZipCode
            #fi
            ''' Contact, '''
            if ('Mobile' in myContactDict):
                ''' commenting following code, will go back to original way to store the contact data 
                myInitMemberData['Contact'].append({'Method':'Mobile','Value': myContactDict['Mobile']})
                '''
                myInitMemberData['Contact']['Mobile'] = myContactDict['Mobile']
                #myMemberTag.append(myContactDict['Mobile'])
            #fi
            if ('Email' in myContactDict):
                ''' commenting following code, will go back to original way to store the contact data 
                myInitMemberData['Contact'].append({'Method':'Email','Value': myContactDict['Email']})
                '''
                myInitMemberData['Contact']['Email'] = myContactDict['Email']
                #myMemberTag.append(myContactDict['Email'])
            #fi

            # building tag
            #myMemberTag = self.util.removeEmptyValueFromList(myMemberTag)
            #myInitMemberData['Tag'].extend(myMemberTag)
            ''' lets get the memberid for this member '''
            myMemberId = self.mongo.genKeyForCollection(
                self.globaL._Global__memberColl)
            myInitMemberData['_id'] = myMemberId
            ''' build initial history data '''
            myInitMemberData[
                self.globaL.
                _Global__HistoryColumn] = self.util.buildInitHistData()
            self.myModuleLogger.info(
                'Data [{arg}] returned'.format(arg=myInitMemberData))

            return myInitMemberData

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    #__buildInitMembderData Ends here

    def __createAMember(self, argRequestDict):
        ''' 
            Description:    Create a member
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'Request': 
                                {'Header':{ScreenId':'','ActionId':'',Page:},
                                {'MainArg': {<Member data 'Main','Address','Contact'>}}
                            }
                            We will add 'BusyHours', BusyDays' block from default value
            usage:          <createAMember(<argReqJsonDict>)
            Return:         Json object

            Collection:     Member: Insert a record in Member collection
        '''
        try:
            ## we need to check who called this function, must be from register
            #print(self.util.whoAmi())
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)

            myMainArgData = self.util.getCopy(argRequestDict)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            myArgKey = ['Main', 'Address', 'Contact']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' Preparing value to create a new member build initial data '''
            myMemberData = self.__buildInitMembderData({
                'Main':
                myMainArgData['Main'],
                'Address':
                myMainArgData['Address'],
                'Contact':
                myMainArgData['Contact']
            })
            myMemberId = myMemberData['_id']
            ''' Creating a member '''
            self.myModuleLogger.info(
                'Creating new member, data [{doc}]'.format(doc=myMemberData))

            myMemberResult = self.mongo.InsertOneDoc(
                self.globaL._Global__memberColl, myMemberData)
            myTagUpdateResult = self.__updateMemberTag({'_id': myMemberId})

            self.myModuleLogger.info(
                'Member [{id}] created, result[{result}]'.format(
                    id=myMemberId, result=myMemberResult))
            self.myModuleLogger.info('Tag updated, result[{result}]'.format(
                result=myTagUpdateResult))
            ''' Building response data, we can not retrieve member information because we dont have Auth ket yet, will return member id created'''
            '''
            myRequestDict = self.util.builInternalRequestDict({'Data':{'_id':myMemberId}})
            myRequestDict = self.getAMemberDetail(myResponseDataDict)
            myResponse = self.util.buildResponseData(self.globaL._Global__InternalRequest,myMemberResult,'Insert',myResponseData)
            '''
            myResponse = myMemberResult['_id']

            return myResponse

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    def __buildGetAllConnPipeline(self, argRequestDict):
        #argMemberId, argConnectionType
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            myMainArgData = self.util.getCopy(argRequestDict)
            myArgKey = ['MemberId', 'ConnectionType']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myConnectionType = myMainArgData['ConnectionType']
            myMemberId = myMainArgData['MemberId']

            self.myModuleLogger.debug(
                'Building pipeline for aggregate function')

            if myConnectionType == self.globaL._Global__memberColl:
                myFromCollection = self.globaL._Global__memberColl
                myPipeLine = [{
                    "$match": {
                        "_id": myMemberId
                    }
                }, {
                    "$unwind": {
                        "path": "$Connections",
                        "preserveNullAndEmptyArrays": True
                    }
                }, {
                    "$match": {
                        "$and": [{
                            "Connections.Type": myConnectionType
                        }]
                    }
                }, {
                    "$lookup": {
                        "from": myFromCollection,
                        "localField": "Connections.Id",
                        "foreignField": "_id",
                        "as": "MyMemberConnections"
                    }
                }, {
                    "$project": {
                        "_id": 1,
                        "Connections": 1,
                        "MyMemberConnections.Id": 1,
                        "MyMemberConnections.Main": 1,
                        "MyMemberConnections.Address": 1,
                        "MyMemberConnections.Contact": 1
                    }
                }, {
                    "$sort": {
                        "MyMemberConnections.Main.LastName": 1
                    }
                }]
            #fi
            return myPipeLine

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    #__buildGetAllConnPipeline Ends here

    def __buildMyConnection(self, argRequestDict):
        #argConnectionType, argConnectionRawData):

        #argMemberId, argConnectionType
        try:
            #self.myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            #self.myModuleLogger.debug('Argument [{arg}] received'.format(arg=argRequestDict))

            myMainArgData = self.util.getCopy(argRequestDict)
            myArgKey = ['ConnectionType', 'ConnectionRawData']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myConnectionType = myMainArgData['ConnectionType']
            myConnectionRawData = myMainArgData['ConnectionRawData']

            self.myModuleLogger.debug(
                'Building [{conn}] Connection '.format(conn=myConnectionType))

            if myConnectionType == self.globaL._Global__memberColl:
                myResultStatus = {"Success": myConnectionRawData['ok']}
                myMemberConnRawData = myConnectionRawData['result']
                if (myMemberConnRawData):
                    myMemberConnections = {
                        "_id": myMemberConnRawData[0]['_id']
                    }

                    myMemberConnections['Connections'] = []
                    for x in myMemberConnRawData:
                        x['MyMemberConnections'][0].update(
                            {'Favorite': x['Connections']['Favorite']})
                        x['MyMemberConnections'][0].update(
                            {'Blocked': x['Connections']['Blocked']})
                        x['MyMemberConnections'][0].update(
                            {'Id': x['Connections']['Id']})
                        x['MyMemberConnections'][0].update(
                            {'Type': x['Connections']['Type']})
                        x['MyMemberConnections'][0].update(
                            {'Status': x['Connections']['Status']})
                        myMemberConnections['Connections'].append(
                            x['MyMemberConnections'][0])

                    # sorting now
                    #myConnection = json.dumps(myMemberConnections, sort_keys=True)
                    myConnection = myMemberConnections
                else:
                    myConnection = {}
                #fi

                #print json.dumps(myMemberConnections, sort_keys=True)
                #print myMemberConnections

            return myConnection

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    #__buildMyConnection Ends here

    def __getMemberConnectionInfo(self, argRequestDict):
        '''
        Returns current Member connection status
        MemberId, ConnectMemberId, Auth
        '''
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            myMainArgData = self.util.getCopy(argRequestDict)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            myArgKey = ['MemberId', 'ConnectMemberId', 'Auth']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' Validate auth key for this request'''
            if not (self.sec._Security__isValAuthKeyInternal(
                    myMainArgData['Auth'])):
                raise com.uconnect.core.error.InvalidAuthKey(
                    'Invalid Auth Key [{auth}] for this request [{me}]'.format(
                        auth=myMainArgData['Auth'], me=self.util.whoAmI()))
            #fi
            ''' Preparing '''
            myCriteria = {
                '_id': myMainArgData['MemberId'],
                'Connections.Id': myMainArgData['ConnectMemberId'],
                'Connections.Type': 'Member'
            }
            myProjection = {'_id': 1, 'Connections': 1}

            #print(myCriteria,myProjection)
            ''' Finding document '''
            myResult = self.mongo.findDocument(self.globaL._Global__memberColl,
                                               myCriteria, myProjection, True)
            #print(myResult)
            myMemberConnection = self.util.extr1stDocFromResultSets(myResult)

            return myMemberConnection

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    #__getMemberConnectionInfo Ends here

    def __updateMemberMain(self, argRequestDict):
        ''' 
            We need to combine all update of a Member
            Description:    Update Member's Main information (LastName,FirstName,NickName,Sex)
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'Request': 
                                {'Header':{ScreenId':'','ActionId':'',Page:},
                                {'MainArg': {'MemberId':'','Main':[{'Key':'Value'},...]
                            }
            usage:          <addMember2Favorite(<argReqJsonDict>)
                            MainArg{'MemberId':'','Main':[{Key':'', 'Value':''}]}
            Return:         Json object
        '''

        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            ''' validating arguments '''
            myArgKey = ['Auth', 'Main']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            # validating security, this has already been validated by BPS process ???
            '''
            if not (self.sec._Security__isValAuthKeyInternal(myMainArgData['Auth'])):
                raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth Key [{auth}] for this request [{me}]'.
                    format(auth=myMainArgData['Auth'], me=self.util.whoAmI()))
            #fi
            '''
            ''' Preparing document:    '''
            # removing key(s) if it has any empty values
            myMainUpdateData = self.util.removeEmptyValueKeyFromDict(
                {'Main': myMainArgData['Main']})

            # building update data, find all key informarion which need to be changed
            myAllMainKey = self.util.getAllKeysFromDict(
                myMainUpdateData['Main'])
            myMainUpdateData = {}
            for key in myAllMainKey:
                myMainUpdateData.update(
                    {'Main.' + key: myMainArgData['Main'][key]})
            #

            myMemberId = myMainArgData['Auth']['EntityId']
            myCriteria = {'_id': myMemberId}
            self.myModuleLogger.info(
                'Updating Member [{member}]\'s [{main}]'.format(
                    member=myMemberId, main=myMainUpdateData))
            ''' Executing document update '''
            myResult = self.mongo.UpdateDoc(self.globaL._Global__memberColl,
                                            myCriteria, myMainUpdateData,
                                            'set', False)
            ''' build response data '''
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Update',
                myResult)
            #return myResponse

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Error')
            return myResponse

    def __updateMemberAddress(self, argRequestDict):
        ''' 
            Description:    Update Member's Address
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'Request': 
                                {'Header':{ScreenId':'','ActionId':'',Page:},
                                {'MainArg': {'MemberId':'','Address':[{'Key':'Value'},...]
                            }
            usage:          <addMember2Favorite(<argReqJsonDict>)
                            MainArg{'MemberId':'','Contact':[{Key':'', 'Value':''}]}
            Return:         Json object
        '''

        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            ''' validating arguments '''
            myArgKey = ['Auth', 'Address']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' preparing document '''
            myMemberId = myMainArgData['Auth']['EntityId']
            myCriteria = {'_id': myMemberId}
            myAddressUpdateData = {}

            # removing key(s) if it has any empty values
            myAddressData = self.util.removeEmptyValueKeyFromDict(
                {'Address': myMainArgData['Address']})
            #print('AddressData',myAddressData)
            # building update data, find all key informarion which need to be changed
            myAllAddressKey = self.util.getAllKeysFromDict(
                myAddressData['Address'])

            # would not change city/state, this shold be change by changing the ZipCode
            if 'City' in myAllAddressKey:
                myAllAddressKey.remove('City')
            #fi
            if 'State' in myAllAddressKey:
                myAllAddressKey.remove('State')
            #fi
            #print('Removed City/State,addressData:',myAddressData, myAllAddressKey)
            for key in myAllAddressKey:
                myAddressUpdateData.update(
                    {'Address.' + key: myAddressData['Address'][key]})
            #
            #print('Created address update data', myAddressUpdateData)
            # will add matching the City/State, if ZipCode is passed
            if 'ZipCode' in myAllAddressKey:
                myCityNState = self.util.getAddressCityState(
                    myAddressData['Address']['ZipCode'])
                myAddressUpdateData.update({'Address.City': myCityNState[0]})
                myAddressUpdateData.update({'Address.State': myCityNState[1]})
            #fi

            self.myModuleLogger.info(
                'Updating Member [{member}]\'s address [{address}]'.format(
                    member=myMemberId, address=myAddressUpdateData))
            ''' Executing document update '''
            myResult = self.mongo.UpdateDoc(self.globaL._Global__memberColl,
                                            myCriteria, myAddressUpdateData,
                                            'set', False)
            ''' build response data '''
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Update',
                myResult)
            #return myResponse

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Error')
            return myResponse

    def __updateMemberContact(self, argRequestDict):
        ''' 
            Description:    Update Member's contact 
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'Request': 
                                {'Header':{ScreenId':'','ActionId':'',Page:},
                                {'MainArg': {'MemberId':'','Contact':[{'Key':'Value'},...]
                            }
            usage:          <addMember2Favorite(<argReqJsonDict>)
                            MainArg{'MemberId':'','Contact':[{Key':'', 'Value':''}]}
            Return:         Json object
        '''
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            ''' validating arguments '''
            myArgKey = ['Auth', 'Contact']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' preparing document '''
            # removing key(s) if it has any empty values
            myContactData = self.util.removeEmptyValueKeyFromDict(
                {'Contact': myMainArgData['Contact']})
            myMemberId = myMainArgData['Auth']['EntityId']
            myCriteria = {'_id': myMemberId}

            # building update data, find all key informarion which need to be changed
            myAllContactKey = self.util.getAllKeysFromDict(
                myContactData['Contact'])
            myContactUpdateData = {}
            for key in myAllContactKey:
                myContactUpdateData.update(
                    {'Contact.' + key: myMainArgData['Contact'][key]})
            #
            self.myModuleLogger.info(
                'Updating Member [{member}]\'s Contact [{contact}]'.format(
                    member=myMemberId, contact=myContactUpdateData))
            ''' Executing document update '''
            myResult = self.mongo.UpdateDoc(self.globaL._Global__memberColl,
                                            myCriteria, myContactUpdateData,
                                            'set', False)
            ''' build response data '''
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Update',
                myResult)
            #return myResponse

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Error')
            return myResponse
            #fi

    def __getAMemberConnections(self, argRequestDict):
        ''' 
            Description:    Find a member's all connections
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'_id':'','ResponseMode':''}
            usage:          <__getAMemberConnections(<argReqJsonDict>)
            Return:         Json object
        '''
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            ''' validating arguments '''
            myArgKey = ['MemberId', 'ConnectionType', 'ResponseMode']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' build aggregate pipeline '''
            myAggregatePipeLine = self.__buildGetAllConnPipeline(\
                {'MemberId':myMainArgData['MemberId'],'ConnectionType':myMainArgData['ConnectionType']})

            self.myModuleLogger.debug(
                "Pipeline [{pipeline}] will be used to execute the aggregate function"
            )

            # execute aggregate pipeline
            myAggregateDict = {
                "aggregate": self.globaL._Global__memberColl,
                "pipeline": myAggregatePipeLine,
                "allowDiskUse": True
            }
            myConnectionRawData = self.mongo.ExecCommand(myAggregateDict)

            if self.util.isAllArgumentsValid(myConnectionRawData):
                myMemberConnection = {
                    "Data":
                    self.__buildMyConnection({
                        'ConnectionType':
                        self.globaL._Global__member,
                        'ConnectionRawData':
                        myConnectionRawData
                    })
                }
            else:
                myMemberConnection = {}
            #fi

            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Find',
                myMemberConnection)
            return myResponse

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Error')
            return myResponse

    def __isAValidMember(self, argRequestDict):
        ''' 
            Description:    Find a member details
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'_id':'','ResponseMode':''}
            usage:          <__isAValidMember(<argReqJsonDict>)
            Return:         Json object
        '''
        try:
            #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            if 'MainArg' in argRequestDict:
                myMainArgData = self.util.getCopy(argRequestDict)['MainArg']
            else:
                myMainArgData = self.util.getCopy(argRequestDict)
            #fi

            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))

            isValidMember = self.globaL._Global__False
            #myArgKey = ['Member','Auth']
            ''' validating arguments '''
            myArgKey = ['_id', 'ResponseMode']
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myCriteria = {
                '_id': myMainArgData['_id'],
                'Main.Type': self.globaL._Global__member
            }
            myMemberDataCount = self.mongo.findTotDocuments(
                self.globaL._Global__memberColl, myCriteria)

            #print(myCriteria,myProjection,myMemberData)
            if myMemberDataCount > 0:
                isValidMember = self.globaL._Global__True
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__Success)
            else:
                isValidMember = self.globaL._Global__False
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__UnSuccess,
                    'MemberID [{member}] does not exist'.format(
                        member=str(myMainArgData['_id'])))
            #fi
            ''' build response data '''
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Find',
                isValidMember)
            return myResponse

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            myResponse = self.util.buildResponseData(
                myMainArgData['ResponseMode'], myRequestStatus, 'Error',
                isValidMember)
            return myResponse