예제 #1
0
def updatingUserInDatabase(validRequest):
    lastAdminId = db.fetch_last_one(USER_TABLE)['admin_id']
    print("last admin id ", lastAdminId)
    dbInsertDocument = {}
    print("Document to be updated in the table", dbInsertDocument)
    proxyResponse = {}
    database = db.getDBConnection()
    print("Finding last user id...")
    currentUserId = int(db.fetch_next_id(USER_TABLE, "_id"))
    # print("previous user id =  ",previousUser)
    print("Document to be updated in the table before data insert in json = ",
          dbInsertDocument)
    # previousUserId = previousUser['user_id']
    # currentUserId = previousUserId + 1
    createdTime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
    if (validRequest['typeOfUser'] == RECRUITER
            and validRequest['userGroup'] == ADMIN):
        dbInsertDocument['organization_id'] = validRequest['organizationId']
        dbInsertDocument['user_group_id'] = 2
    elif (validRequest['userGroup'] == RECRUITER):
        dbInsertDocument['organization_id'] = validRequest['organizationId']
        dbInsertDocument['user_group_id'] = 2
    else:
        dbInsertDocument['user_group_id'] = 1
    # Greating document to insert in database
    dbInsertDocument['admin_id'] = lastAdminId
    dbInsertDocument["_id"] = currentUserId
    dbInsertDocument['user_id'] = currentUserId
    dbInsertDocument['user_name'] = validRequest['username']
    dbInsertDocument['email'] = validRequest['username']
    dbInsertDocument['created_at'] = createdTime
    dbInsertDocument['last_updated_at'] = createdTime
    dbInsertDocument['is_active'] = isActive
    dbInsertDocument['first_name'] = validRequest['firstName']
    dbInsertDocument['last_name'] = validRequest['lastName']
    dbInsertDocument['created_by'] = validRequest['userDBid']
    print("Document to be updated in the table", dbInsertDocument)
    insertResponse = db.insert_data_one(USER_TABLE, dbInsertDocument)
    print("DataBase inserted response = ", insertResponse, " type = ",
          type(insertResponse))
    return insertResponse
예제 #2
0
def lambda_handler(event, context):
    proxyResponse = {}
    response = {}
    proxyResponse['headers'] = {
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Origin": "*"
    }

    validRequest = validateRequest(event)
    print(validRequest)
    if ('error' in validRequest):
        proxyResponse['statusCode'] = validRequest['errorCode']
        proxyResponse['error'] = validRequest['error']
    else:
        '''
        BUSINESS LOGIC STARTS HERE
        '''
        questionTitle = validRequest["questionTitle"]
        questionDescription = validRequest["questionDescription"]
        questionTypeId = validRequest["questionTypeId"]
        if not validRequest["imageList"]:
            containsMedia = False
        else:
            containsMedia = True
        createdTime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
        duration = validRequest["duration"]
        createdBy = validRequest["userId"]
        optionList = validRequest['optionList']
        categoryList = validRequest['categoryList']
        score = validRequest['score']

        if ('questionId' not in validRequest):
            questionId = db_utility.fetch_next_id("question_master",
                                                  "question_id")
            param = {
                "_id": questionId,
                "question_id": questionId,
                "title": questionTitle,
                "description": questionDescription,
                "question_type_id": questionTypeId,
                "contains_media": containsMedia,
                "score": score,
                "is_active": True,
                "last_updated_at": createdTime,
                "created_at": createdTime,
                "created_by": createdBy,
                "duration": duration
            }
            if (validRequest['userGroupId'] == 1):
                param['admin_id'] = validRequest['adminId']
            if (validRequest['userGroupId'] == 2):
                param['organization_id'] = validRequest["organizationId"]
            if (questionTypeId == 1):
                if ('answer_count' in validRequest):
                    param['answer_count'] = validRequest["answer_count"]
            if (containsMedia):
                param['image_list'] = validRequest['imageList']
            data = db_utility.insert_data_one("question_master", param)

            response["question_id"] = questionId
            response["responseCode"] = "200"
            response["message"] = "Question created successfully"

        else:
            questionId = validRequest["questionId"]
            param = {
                "title": questionTitle,
                "description": questionDescription,
                "question_type_id": questionTypeId,
                "contains_media": containsMedia,
                "score": score,
                "last_updated_at": createdTime,
                "created_by": createdBy,
                "duration": duration
            }
            if (questionTypeId == 1):
                if ('answer_count' in validRequest):
                    param['answer_count'] = validRequest["answer_count"]
            if (containsMedia):
                param['image_list'] = validRequest['imageList']
            data = db_utility.update_data_one("question_master",
                                              {"question_id": questionId},
                                              param)
            if (data == "200"):
                response["question_id"] = questionId
                response["responseCode"] = "200"
                response["message"] = "Question updated successfully"
            data = delete_all("question_category", {"question_id": questionId})
            data = delete_all("question_tags", {"question_id": questionId})
            data = delete_all("question_mcq", {"question_id": questionId})

        questionCategoryId = db_utility.fetch_next_id("question_category",
                                                      "question_category_id")
        paramList = []
        for category in categoryList:
            param = {}
            param["_id"] = questionCategoryId
            param["question_category_id"] = questionCategoryId
            param["question_id"] = questionId
            param["category_id"] = category["categoryId"]
            questionCategoryId = questionCategoryId + 1
            paramList.append(param)
        print("Inserting categories")
        data = db_utility.insert_data_many("question_category", paramList)

        if (questionTypeId == 1):
            optionId = db_utility.fetch_next_id("question_mcq", "option_id")
            paramList = []
            for option in optionList:
                param = {}
                param["_id"] = optionId
                param["option_id"] = optionId
                param["question_id"] = questionId
                param["option"] = option["option"]
                param["score"] = option["score"]
                param["is_correct"] = option["isCorrect"]
                optionId = optionId + 1
                paramList.append(param)
            print("Inserting options")
            data = db_utility.insert_data_many("question_mcq", paramList)

        if ('tagList' in validRequest):
            # tagList = db_utility.fetch_where("question_tags",{"question_id":questionId})
            for tag in validRequest['tagList']:
                tagInfo = db_utility.fetch_where("tag",
                                                 {"tag_name": tag['tag_name']})
                if (len(tagInfo) > 0):
                    tagId = tagInfo[0]['tag_id']
                else:
                    tagId = db_utility.fetch_next_id("tag", "tag_id")
                    data = db_utility.insert_data_one(
                        "tag", {
                            "_id": tagId,
                            "tag_id": tagId,
                            "tag_name": tag['tag_name']
                        })
                questionTagId = db_utility.fetch_next_id(
                    "question_tags", "question_tag_id")
                data = db_utility.insert_data_one(
                    "question_tags", {
                        "_id": questionTagId,
                        "question_tag_id": questionTagId,
                        "tag_id": tagId,
                        "question_id": questionId
                    })
        '''
		BUSINESS LOGIC ENDS HERE BY RETURNING RESPONSE JSON
		'''
        proxyResponse['statusCode'] = 200
        proxyResponse['body'] = json.dumps(response)
    print(proxyResponse)
    return proxyResponse
예제 #3
0
def lambda_handler(event, context):
    proxyResponse = {}
    response = {}
    proxyResponse['headers'] = {
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Origin": "*"
    }

    validRequest = validateRequest(event)
    print(validRequest)
    if ('error' in validRequest):
        proxyResponse['statusCode'] = validRequest['errorCode']
        proxyResponse['error'] = validRequest['error']
    else:
        '''
        BUSINESS LOGIC STARTS HERE
        '''
        if ('sampleQuestionSetId' in validRequest):
            sampleQuestionSetId = validRequest['sampleQuestionSetId']
        if ('expireAt' in validRequest):
            expireAt = validRequest['expireAt']
        if ('organizationId' in validRequest):
            organizationId = validRequest['organizationId']

        isActive = validRequest['isActive']
        questionSetName = validRequest['questionSetName']
        questionList = validRequest['questionList']
        isSampleSet = validRequest['isSampleSet']
        duration = validRequest['duration']
        isPartialCompleteAllowed = validRequest['isPartialCompleteAllowed']
        isRandomOrder = validRequest['isRandomOrder']
        createdBy = validRequest['userId']
        currentTime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
        param = {}

        if ((validRequest['userGroupId']) == 1):
            if ('questionSetId' in validRequest):
                param['question_set_name'] = questionSetName
                param['question_list'] = questionList
                param['is_sample_set'] = isSampleSet
                param['duration'] = duration
                param['is_active'] = isActive
                param['is_partial_complete_allowed'] = isPartialCompleteAllowed
                param['last_updated_at'] = currentTime
                param['is_random_order'] = isRandomOrder
                # param['created_by'] = createdBy

                print("Updating question bank")
                questionSetId = validRequest['questionSetId']
                if ('expireAt' in validRequest):
                    param['expire_at'] = expireAt
                if ('sampleQuestionSetId' in validRequest):
                    param['sample_question_set_id'] = sampleQuestionSetId

                print(param)
                data = db_utility.update_data_one(
                    "question_set", {"question_set_id": questionSetId}, param)
                response["questionSetId"] = questionSetId
            else:
                questionSetId = db_utility.fetch_next_id(
                    "question_set", "question_set_id")

                param['_id'] = questionSetId
                param['question_set_id'] = questionSetId
                param['question_set_name'] = questionSetName
                param['question_list'] = questionList
                param['is_sample_set'] = isSampleSet
                param['is_question_bank'] = True
                param['duration'] = duration
                param['is_active'] = isActive
                param['is_partial_complete_allowed'] = isPartialCompleteAllowed
                param['last_updated_at'] = currentTime
                param['is_random_order'] = isRandomOrder
                param['created_at'] = currentTime
                param['created_by'] = createdBy
                param['is_show'] = True

                print("Creating question bank")

                if ('expireAt' in validRequest):
                    param['expire_at'] = expireAt
                if ('sampleQuestionSetId' in validRequest):
                    param['sample_question_set_id'] = sampleQuestionSetId

                print(param)
                data = db_utility.insert_data_one("question_set", param)
                response["questionSetId"] = questionSetId
        else:
            if ('questionSetId' in validRequest):
                questionSetId = validRequest['questionSetId']
                print("Updating question set")
                param['question_set_name'] = questionSetName
                param['question_list'] = questionList
                param['is_sample_set'] = isSampleSet
                param['duration'] = duration
                param['is_active'] = isActive
                param['is_partial_complete_allowed'] = isPartialCompleteAllowed
                param['last_updated_at'] = currentTime
                param['is_random_order'] = isRandomOrder
                # param['created_by'] = createdBy

                if ('organizationId' in validRequest):
                    param['organization_id'] = organizationId
                if ('expireAt' in validRequest):
                    param['expire_at'] = expireAt
                if ('sampleQuestionSetId' in validRequest):
                    param['sample_question_set_id'] = sampleQuestionSetId

                print(param)
                data = db_utility.update_data_one(
                    "question_set", {"question_set_id": questionSetId}, param)
                response["questionSetId"] = questionSetId

            else:
                print("Creating question set")
                questionSetId = db_utility.fetch_next_id(
                    "question_set", "question_set_id")
                param['_id'] = questionSetId
                param['question_set_id'] = questionSetId
                param['question_set_name'] = questionSetName
                param['question_list'] = questionList
                param['is_sample_set'] = isSampleSet
                param['is_question_bank'] = False
                param['duration'] = duration
                param['is_active'] = isActive
                param['is_partial_complete_allowed'] = isPartialCompleteAllowed
                param['last_updated_at'] = currentTime
                param['is_random_order'] = isRandomOrder
                param['created_at'] = currentTime
                param['created_by'] = createdBy
                param['is_show'] = True

                if ('organizationId' in validRequest):
                    param['organization_id'] = organizationId
                if ('expireAt' in validRequest):
                    param['expire_at'] = expireAt
                if ('sampleQuestionSetId' in validRequest):
                    param['sample_question_set_id'] = sampleQuestionSetId

                print(param)
                data = db_utility.insert_data_one("question_set", param)
                response["questionSetId"] = questionSetId
        '''
		BUSINESS LOGIC ENDS HERE BY RETURNING RESPONSE JSON
		'''
        proxyResponse['statusCode'] = 200
        proxyResponse['body'] = json.dumps(response)
    print(proxyResponse)
    return proxyResponse
def lambda_handler(event, context):
    proxyResponse = {}
    response = {}
    proxyResponse['headers'] = {
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Origin": "*"
    }

    validRequest = validateRequest(event)
    if ('error' in validRequest):
        proxyResponse['statusCode'] = validRequest['errorCode']
        proxyResponse['error'] = validRequest['error']
    else:
        '''
		BUSINESS LOGIC STARTS HERE
		'''
        userName = validRequest['userId']
        userDetail = db_utility.fetch_where("user_master",
                                            {"user_name": userName})[0]
        param = {}
        # for i in requiredParams:
        # 	param[i]=validRequest[i]

        userGroup = userDetail['user_group_id']
        # print(userGroup)
        if userGroup == 2 and validRequest['copy_question_set']:
            existing_param = db_utility.fetch_where(
                'question_set',
                {'question_set_id': validRequest['question_set_id']})[0]
            print(existing_param)
            param = {}
            param['question_set_id'] = db_utility.fetch_next_id(
                'question_set', 'question_set_id')
            param['_id'] = param['question_set_id']
            param['question_set_name'] = existing_param['question_set_name']
            param['question_list'] = existing_param['question_list']
            param['is_sample_set'] = existing_param['is_sample_set']
            param['is_question_bank'] = False
            if 'expire_at' in existing_param:
                param['expire_at'] = existing_param['expire_at']
            param['duration'] = existing_param['duration']
            param['is_active'] = existing_param['is_active']
            param['is_partial_complete_allowed'] = existing_param[
                'is_partial_complete_allowed']
            param['last_updated_at'] = datetime.datetime.now().strftime(
                "%Y-%m-%dT%H:%M:%S")
            param['is_active'] = existing_param['is_active']
            param['is_random_order'] = existing_param['is_random_order']
            param['is_show'] = True
            param['created_at'] = datetime.datetime.now().strftime(
                "%Y-%m-%dT%H:%M:%S")
            param['created_by'] = userDetail['user_id']
            param['organization_id'] = userDetail['organization_id']
            data = db_utility.insert_data_one("question_set", param)
            param['message'] = "Question set copied successfully"

        if (not validRequest['copy_question_set']):
            questionSetId = validRequest['question_set_id']
            status = False

            data = db_utility.update_data_one(
                "question_set", {"question_set_id": questionSetId},
                {"is_show": status})
            param['message'] = "Question set deleted successfully"

        else:
            param["statusCode"] = 404
            param['Error'] = UNAUTHENTICATION_ERROR_MSG

        if data == "200":
            print("Data Updated")
        else:
            param['statusCode'] = 400
            param['Error'] = DATABASE_CONNECTION_ERROR
        response = param
        '''
		BUSINESS LOGIC ENDS HERE BY RETURNING RESPONSE JSON
		'''
        proxyResponse['statusCode'] = 200
        # response={}
        # print(response)
        proxyResponse['body'] = json.dumps(response)
    print(proxyResponse)
    return proxyResponse
def lambda_handler(event, context):
    print(event['body'])
    Bucket = event['body']['Bucket']
    # Bucket="workonic-media-files"
    # key="mainCSV/6_Sample.csv"
    key = event['body']['Key']
    print(key)
    s3 = boto3.client('s3')
    obj = s3.get_object(Bucket=Bucket, Key=key)
    emailcontent = obj['Body'].read().decode('utf-8')
    print("YES")
    TESTDATA = StringIO(emailcontent)
    df = pd.read_csv(TESTDATA, sep=",")
    print(df)
    event['body']['csv'] = df

    # for bucket in s3.buckets.all():
    #     print(bucket.name)
    proxyResponse = {}
    response = {}
    proxyResponse['headers'] = {
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Origin": "*"
    }

    validRequest = validateRequest(event)
    if ('error' in validRequest):
        proxyResponse['statusCode'] = validRequest['errorCode']
        proxyResponse['error'] = validRequest['error']
    else:
        '''
        BUSINESS LOGIC STARTS HERE
        '''
        userName = validRequest['userId']
        userDetail = db_utility.fetch_where("user_master",
                                            {"user_name": userName})[0]
        # print(userDetail)
        csvFile = validRequest['csv']
        insertionFailed = []
        for i in range(csvFile.shape[0]):
            # print(csvFile.loc[i])
            candidate_param = {}
            test_param = {}
            tracker_param = {}
            invitation_param = {}
            param = {}
            firstName = csvFile.loc[i, 'firstName']
            email = csvFile.loc[i, 'email']
            print(email)
            candidate_param['candidate_id'] = db_utility.fetch_next_id(
                "candidate", "candidate_id")
            candidate_param["_id"] = candidate_param["candidate_id"]
            candidate_param['first_name'] = firstName
            if (not pd.isnull(csvFile.loc[i, 'lastName'])):
                lastName = csvFile.loc[i, 'lastName']
                candidate_param['last_name'] = lastName
            candidate_param['email'] = email
            candidate_param['is_active'] = True
            candidate_param['created_at'] = datetime.datetime.now().strftime(
                "%Y-%m-%dT%H:%M:%S")
            candidate_param['organization_id'] = userDetail['organization_id']
            candidate_param['created_by'] = userDetail['user_id']

            questionSetDetail = db_utility.fetch_where(
                "question_set",
                {"question_set_id": validRequest['question_set_id']})[0]

            test_param['test_id'] = db_utility.fetch_next_id("test", "test_id")
            test_param["_id"] = test_param["test_id"]
            test_param['candidate_id'] = candidate_param["candidate_id"]
            test_param['created_at'] = datetime.datetime.now().strftime(
                "%Y-%m-%dT%H:%M:%S")
            test_param['question_set_id'] = validRequest['question_set_id']
            test_param['is_active'] = True
            test_param['created_at'] = datetime.datetime.now().strftime(
                "%Y-%m-%dT%H:%M:%S")
            test_param['organization_id'] = userDetail['organization_id']
            test_param['created_by'] = userDetail['user_id']
            test_param['expire_at'] = questionSetDetail['expire_at']
            while True:
                token = ''.join(
                    random.choice(string.ascii_lowercase) for i in range(10))
                # print(token)
                tokenValidation = db_utility.is_exist("test", {"token": token})
                if (not tokenValidation):
                    test_param['token'] = token
                    break
                else:
                    continue

            tracker_param = {}
            tracker_param['tracker_id'] = db_utility.fetch_next_id(
                "log_tracker", "tracker_id")
            tracker_param["_id"] = tracker_param['tracker_id']
            tracker_param['test_id'] = test_param['test_id']
            tracker_param['activity_type_id'] = "000"
            tracker_param['activity_time'] = datetime.datetime.now().strftime(
                "%Y-%m-%dT%H:%M:%S")

            candidate_data = db_utility.insert_data_one(
                "candidate", candidate_param)
            test_data = db_utility.insert_data_one("test", test_param)
            tracker_data = db_utility.insert_data_one("log_tracker",
                                                      tracker_param)

            if candidate_data == "200" and tracker_data == "200" and test_data == "200":
                print("Data Inserted")
                param = tracker_param
                orgDetail = db_utility.fetch_where(
                    "organization_details",
                    {"organization_id": userDetail['organization_id']})[0]

                organisation_name = orgDetail['organization_name']
                test_name = questionSetDetail['question_set_name']
                first_name = firstName
                recruiter_name = orgDetail['organization_name']
                recruiter_phone = orgDetail['contact_number']
                test_url = environ.get('TESTURL') + '/#/token/' + token
                # test_url = 'localhost:4200/token/'+token
                recruiter_email = orgDetail['contact_email']
                test_duration = questionSetDetail['duration']
                test_expire = questionSetDetail['expire_at']

                inviteParam = {
                    'organisation_name': organisation_name,
                    'test_name': test_name,
                    'first_name': first_name,
                    'recruiter_name': recruiter_name,
                    'test_url': test_url,
                    'recruiter_phone': recruiter_phone,
                    'recruiter_email': recruiter_email,
                    'test_duration': test_duration,
                    'test_expire': test_expire
                }

                request = {
                    "to": [email],
                    "parameters": inviteParam,
                    'templateName': 'test_invite',
                    'candidateToken': token
                }
                client = boto3.client('lambda', region_name=environ['Region'])
                response = client.invoke(FunctionName='WO-' +
                                         environ['stage'] + '-SendEmail',
                                         InvocationType='RequestResponse',
                                         Payload=json.dumps({'body': request}))
                # response=json.loads(response['Payload'].read().decode("utf-8"))
                # print(response)
                response = "200"
                if response == "200":
                    print("Test Invitation Sent")
                    invitation_param['tracker_id'] = db_utility.fetch_next_id(
                        "log_tracker", "tracker_id")
                    invitation_param["_id"] = invitation_param['tracker_id']
                    invitation_param['test_id'] = test_param['test_id']
                    invitation_param['activity_type_id'] = "001"
                    invitation_param['activity_time'] = datetime.datetime.now(
                    ).strftime("%Y-%m-%dT%H:%M:%S")
                    invitation_data = db_utility.insert_data_one(
                        "log_tracker", invitation_param)
                else:
                    param['statusCode'] = 400
                    param['Error'] = DATABASE_CONNECTION_ERROR
                    param['erroMessage'] = "Sending Inivitation Failed"
                    invitation_data = "0"
                if invitation_data == "200":
                    print("Invitation Data Inserted")
                    param['statusCode'] = 200
                    param['Message'] = "All User Inserted"
                else:
                    param['statusCode'] = 400
                    param['Error'] = DATABASE_CONNECTION_ERROR
                    insertionFailed.append(i)
                    param["insertionFailedFor"] = insertionFailed
            else:
                param['statusCode'] = 400
                param['Error'] = DATABASE_CONNECTION_ERROR
                insertionFailed.append(i)
                param["insertionFailedFor"] = insertionFailed
            response = param
    '''
		BUSINESS LOGIC ENDS HERE BY RETURNING RESPONSE JSON
		'''
    proxyResponse['statusCode'] = 200
    # response={}
    # print(response)
    proxyResponse['body'] = json.dumps(response)
    print(proxyResponse)
    return proxyResponse
예제 #6
0
def lambda_handler(event, context):
    proxyResponse = {}
    response = {}
    proxyResponse['headers'] = {
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Origin": "*"
    }

    validRequest = validateRequest(event)
    if ('error' in validRequest):
        proxyResponse['statusCode'] = validRequest['errorCode']
        proxyResponse['error'] = validRequest['error']
    else:
        '''
        BUSINESS LOGIC STARTS HERE
        '''
        userName = validRequest['userId']
        userDetail = db_utility.fetch_where("user_master",
                                            {"user_name": userName})[0]
        print(userDetail)
        candidate_param = {}
        test_param = {}
        tracker_param = {}
        invitation_param = {}
        param = {}

        # for i in requiredParams:
        # 	candidate_param[i]=validRequest[i]

        candidate_param['candidate_id'] = db_utility.fetch_next_id(
            "candidate", "candidate_id")
        candidate_param["_id"] = candidate_param["candidate_id"]
        candidate_param['first_name'] = validRequest['first_name']
        if 'last_name' in validRequest:
            candidate_param['last_name'] = validRequest['last_name']
        if 'mobile_number' in validRequest:
            candidate_param['mobile_number'] = validRequest['mobile_number']
        candidate_param['email'] = validRequest['email']
        candidate_param['is_active'] = True
        candidate_param['created_at'] = datetime.datetime.now().strftime(
            "%Y-%m-%dT%H:%M:%S")
        candidate_param['organization_id'] = userDetail['organization_id']
        candidate_param['created_by'] = userDetail['user_id']

        questionSetDetail = db_utility.fetch_where(
            "question_set",
            {"question_set_id": validRequest['question_set_id']})[0]
        # print(questionSetDetail)
        test_param['test_id'] = db_utility.fetch_next_id("test", "test_id")
        test_param["_id"] = test_param["test_id"]
        test_param['candidate_id'] = candidate_param["candidate_id"]
        test_param['created_at'] = datetime.datetime.now().strftime(
            "%Y-%m-%dT%H:%M:%S")
        test_param['question_set_id'] = validRequest['question_set_id']
        test_param['is_active'] = True
        test_param['created_at'] = datetime.datetime.now().strftime(
            "%Y-%m-%dT%H:%M:%S")
        test_param['organization_id'] = userDetail['organization_id']
        test_param['created_by'] = userDetail['user_id']
        test_param['expire_at'] = questionSetDetail['expire_at']
        while True:
            token = ''.join(
                random.choice(string.ascii_lowercase) for i in range(10))
            # print(token)
            tokenValidation = db_utility.is_exist("test", {"token": token})
            if (not tokenValidation):
                test_param['token'] = token
                break
            else:
                continue

        tracker_param = {}
        tracker_param['tracker_id'] = db_utility.fetch_next_id(
            "log_tracker", "tracker_id")
        tracker_param["_id"] = tracker_param['tracker_id']
        tracker_param['test_id'] = test_param['test_id']
        tracker_param['activity_type_id'] = "000"
        tracker_param['activity_time'] = datetime.datetime.now().strftime(
            "%Y-%m-%dT%H:%M:%S")

        candidate_data = db_utility.insert_data_one("candidate",
                                                    candidate_param)
        test_data = db_utility.insert_data_one("test", test_param)
        tracker_data = db_utility.insert_data_one("log_tracker", tracker_param)

        if candidate_data == "200" and tracker_data == "200" and test_data == "200":
            print("Data Inserted")
            param = tracker_param
            orgDetail = db_utility.fetch_where(
                "organization_details",
                {"organization_id": userDetail['organization_id']})[0]

            organisation_name = orgDetail['organization_name']
            test_name = questionSetDetail['question_set_name']
            first_name = validRequest['first_name']
            recruiter_name = orgDetail['organization_name']
            recruiter_phone = orgDetail['contact_number']
            test_url = environ.get('TESTURL') + '/#/token/' + token
            recruiter_email = orgDetail['contact_email']
            test_duration = questionSetDetail['duration']
            test_expire = questionSetDetail['expire_at']

            inviteParam = {
                'organisation_name': organisation_name,
                'test_name': test_name,
                'first_name': first_name,
                'recruiter_name': recruiter_name,
                'test_url': test_url,
                'recruiter_phone': recruiter_phone,
                'recruiter_email': recruiter_email,
                'test_duration': test_duration,
                'test_expire': test_expire
            }

            request = {
                "to": [validRequest['email']],
                "parameters": inviteParam,
                'templateName': 'test_invite',
                'candidateToken': token
            }

            client = boto3.client('lambda', region_name=environ['Region'])
            response = client.invoke(FunctionName='WO-' + environ['stage'] +
                                     '-SendEmail',
                                     InvocationType='RequestResponse',
                                     Payload=json.dumps({'body': request}))

            response = "200"
            if response == "200":
                print("Test Invitation Sent")
                invitation_param['tracker_id'] = db_utility.fetch_next_id(
                    "log_tracker", "tracker_id")
                invitation_param["_id"] = invitation_param['tracker_id']
                invitation_param['test_id'] = test_param['test_id']
                invitation_param['activity_type_id'] = "001"
                invitation_param['activity_time'] = datetime.datetime.now(
                ).strftime("%Y-%m-%dT%H:%M:%S")
                invitation_data = db_utility.insert_data_one(
                    "log_tracker", invitation_param)
            else:
                param['statusCode'] = 400
                param['Error'] = DATABASE_CONNECTION_ERROR
                param['erroMessage'] = "Sending Inivitation Failed"
                invitation_data = "0"
            if invitation_data == "200":
                print("Invitation Data Inserted")
                param = invitation_param
            else:
                param['statusCode'] = 400
                param['Error'] = DATABASE_CONNECTION_ERROR
        else:
            param['statusCode'] = 400
            param['Error'] = DATABASE_CONNECTION_ERROR
        response = param
    '''
		BUSINESS LOGIC ENDS HERE BY RETURNING RESPONSE JSON
		'''
    proxyResponse['statusCode'] = 200
    # response={}
    # print(response)
    proxyResponse['body'] = json.dumps(response)
    print(proxyResponse)
    return proxyResponse
예제 #7
0
def lambda_handler(event,context):
	proxyResponse = {}
	response = {}
	proxyResponse['headers'] =  {"Access-Control-Allow-Methods":"*", "Access-Control-Allow-Headers":"*", "Access-Control-Allow-Origin":"*"}

	validRequest = validateRequest(event)
	if('error' in validRequest):
		proxyResponse['statusCode'] = validRequest['errorCode']
		proxyResponse['error'] = validRequest['error']
	else:
		'''
		BUSINESS LOGIC STARTS HERE
		'''	
		# print(validRequest)
		candidateToken=validRequest['candidateToken']
		testDetail=db_utility.fetch_where("test",{"token":candidateToken})[0]
		testId=testDetail['test_id']
		# questionSetDetail=db_utility.fetch_where("question_set",{"question_set_id":testDetail['question_set_id']})[0]
		# sampleQuestionSetDetails=db_utility.fetch_where("question_set",{"question_set_id":questionSetDetail['sample_question_set_id']})[0]
		# print(sampleQuestionSetDetails['question_list'])
		questionId=validRequest['questionId']
		questionDetail=db_utility.fetch_where('question_master',{'question_id':questionId})[0]
		answer=validRequest['answer']
		print(answer)
		if questionDetail['question_type_id']==1:
			param={}
			param['response_id']=db_utility.fetch_next_id("test_response","response_id")
			param["_id"]=param['response_id']
			param['question_id']=validRequest['questionId']
			param['test_id']=testId
			param['answer_mcq']=answer['mcq']
			param['submitted_at']=datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
		elif questionDetail['question_type_id']==2:
			param={}
			param['response_id']=db_utility.fetch_next_id("test_response","response_id")
			param["_id"]=param['response_id']
			param['question_id']=validRequest['questionId']
			param['test_id']=testId
			if 'videoUrl' in answer:
				param['video_url']=answer['videoUrl']
			if 'textUrl' in answer:
				param['text_url']=answer['textUrl']
			param['submitted_at']=datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
		data=db_utility.insert_data_one('test_response',param)
		# print("1")
		# print(data)
		if data=="200":
			testQuestionTracker=db_utility.fetch_where_and('test_question_tracker',[{'test_id':testId,'question_id':questionId}])[0]
			param={}
			currentSortOrder=testQuestionTracker['sort_order']
			print(currentSortOrder)
			param=testQuestionTracker
			param['submit_status']=True
			trackerData=db_utility.update_data_one('test_question_tracker',{"question_tracker_id":testQuestionTracker['question_tracker_id']},param)
			# print(data)
		if trackerData=="200":
			param={}
			param['tracker_id']=db_utility.fetch_next_id("log_tracker","tracker_id")
			param['_id']=param['tracker_id']
			param['test_id']=testId
			param['activity_type_id']="004"
			param['activity_time']=datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
			# logData=db_utility.insert_data_one('log_tracker',param)
			logData="200"
		if logData=="200":
			print("Data Inserted")
			# sortOrder=0
			sortOrder=currentSortOrder+1
			print(sortOrder)
			while True:
				nextQuestionId=db_utility.fetch_where('test_question_tracker',{'sort_order':sortOrder,'test_id':testId})				
				if (len(nextQuestionId)>0 and not nextQuestionId[0]['submit_status']):
					nextQuestionId=nextQuestionId[0]['question_id']
					break
				elif (len(nextQuestionId)>0 and nextQuestionId[0]['submit_status'] and sortOrder!=currentSortOrder):
					sortOrder=sortOrder+1
				elif (len(nextQuestionId)==0 and sortOrder!=currentSortOrder):
					sortOrder=1
				elif (len(nextQuestionId)>0 and sortOrder==currentSortOrder):
					nextQuestionId=0
					break
				else:
					nextQuestionId=0
					break
		if nextQuestionId==0:
			param={}
			param['test_ended']=True
		else:
			client = boto3.client('lambda',region_name = environ['Region'])
			# print("Invoking AkriValidateToken micro service to validate token")
			nextQuestion = client.invoke(
			FunctionName='WO-'+environ['stage']+'-LookupQuestion',
			InvocationType='RequestResponse',
			Payload=json.dumps({"body":{'questionId': nextQuestionId,"candidateToken":candidateToken}})
			)
			
			nextQuestion= json.loads(nextQuestion['Payload'].read().decode("utf-8"))
			param={}
			param=nextQuestion['body']
			param=json.loads(param)
			param['sort_order']=sortOrder
			param['test_ended']=False
			print(param)
				
			if len(param)>0:
				print("Data Fetched")
				# param=questionDetail['body']
			else:
				param['statusCode']=400
				param['Error']=DATABASE_CONNECTION_ERROR
		response=param
		'''
		BUSINESS LOGIC ENDS HERE BY RETURNING RESPONSE JSON
		'''	
		proxyResponse['statusCode'] = 200
		# response={}
		# print(response)
		proxyResponse['body'] = json.dumps(response)
	print(proxyResponse)
	return proxyResponse
예제 #8
0
def lambda_handler(event, context):
    print("event body", event['body'])
    proxyResponse = {}
    response = {}
    proxyResponse['headers'] = {
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Origin": "*"
    }
    validRequest = validateRequest(event)
    if ('error' in validRequest):
        proxyResponse['statusCode'] = validRequest['errorCode']
        proxyResponse['error'] = validRequest['error']
        return proxyResponse
    else:
        '''
		BUSINESS LOGIC STARTS HERE
		'''
        print("Validated request = ", validRequest)
        #Fetching last organization id

        try:

            if 'organizationId' in validRequest:
                print("Inside organization update")
                updatedDataResponse = updateOrganizationDetails(validRequest)
                print("updated response from the db = ", updatedDataResponse)
                if (updatedDataResponse == 402):
                    print("Organization =not= updated successfully")
                    proxyResponse['statusCode'] = 402
                    proxyResponse['error'] = "Specified organization not found"
                    return proxyResponse
                else:
                    print("Organization  updated successfully")
                    proxyResponse['statusCode'] = 200
                    proxyResponse[
                        'body'] = "Specified organization updated successfully"
                    return proxyResponse
            else:
                if 'userName' not in validRequest and 'password' not in validRequest and 'firstName' not in validRequest and 'lastName' not in validRequest:
                    print(MISSING_ERROR_MSG)
                    response = {"error": MISSING_ERROR_MSG, "errorCode": 402}
                    return response
            print("Adding user to the cognito pool and updating the database")
            organizationCount = db.fetch_count(ORGANIZATION_TABLE)
            if (organizationCount == 0):
                generatedOrganizationId = 1
            else:
                generatedOrganizationId = db.fetch_next_id(
                    ORGANIZATION_TABLE, 'organization_id')
                # generatedOrganizationId = previousOrganizationId + 1
            event['body'] = {
                "username": validRequest['userName'],
                "password": validRequest['password'],
                "typeOfUser": RECRUITER,
                "organizationId": generatedOrganizationId,
                "firstName": validRequest['firstName'],
                "lastName": validRequest['lastName']
            }
            #Invoking ADDUSER lambda to create new user
            createUserResponse = creatingNewUserForOrganization(event)
            print("Created user response from lambda ", createUserResponse)
            #Decoding response from lambda
            decodedCreateUserResponse = json.loads(
                createUserResponse['Payload'].read().decode("utf-8"))
            print("decoded Created user response from lambda",
                  decodedCreateUserResponse)
            if (decodedCreateUserResponse['statusCode'] != 200):
                print("error", decodedCreateUserResponse['error'])
                proxyResponse['error'] = decodedCreateUserResponse['error']
                proxyResponse['statusCode'] = 402
                return proxyResponse
            print("User Successfully created in cognito")
            updatingOrganizationResponse = addingOrganizationToDatabase(
                validRequest, generatedOrganizationId)
            if (updatingOrganizationResponse == 401):
                deleteUserResponse = deleteUser(validRequest['userName'])
                print("User delted response = ", deleteUserResponse)
                reponse = "organization creation failed"
                proxyResponse['statusCode'] = 400
                proxyResponse['error'] = reponse
                return proxyResponse
            response = "organization created Successfully"
        except Exception as e:
            # deleteUserResponse =  deleteUser(validRequest['userName'])
            print("error", e)
            proxyResponse['error'] = e
            proxyResponse['statusCode'] = 402
            return proxyResponse
        response = "Organization created successfully"
        '''
		BUSINESS LOGIC ENDS HERE BY RETURNING RESPONSE JSON
		'''
        proxyResponse['statusCode'] = 200
        proxyResponse['body'] = json.dumps(response)
    print(proxyResponse)
    return proxyResponse
def lambda_handler(event, context):
    proxyResponse = {}
    response = {}
    proxyResponse['headers'] = {
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Origin": "*"
    }
    validRequest = {}
    # validRequest = validateRequest(event)
    if ('error' in validRequest):
        proxyResponse['statusCode'] = validRequest['errorCode']
        proxyResponse['error'] = validRequest['error']
    else:
        '''
		BUSINESS LOGIC STARTS HERE
		'''
        # userName=validRequest['userId']
        # userDetail=db_utility.fetch_where("user_master",{"user_name":userName})[0]
        # param={}
        # userGroup=userDetail['user_group_id']
        # print("UserGroup " +str(userGroup))
        # if userGroup==1:
        # 	activeTest=db_utility.fetch_all("test")
        # elif userGroup==2:
        # 	orgId=userDetail['organization_id']
        # 	activeTest=db_utility.fetch_where("test",{'organization_id':orgId})
        activeTest = db_utility.fetch_all("test")
        if len(activeTest) > 0:
            currentTime = datetime.datetime.now()
            print(currentTime)
            timeDiffAllowed = 30
            for i in range(len(activeTest)):
                activeTestId = activeTest[i]['test_id']
                # logs=db_utility.fetch_where("log_tracker",{"test_id":activeTestId})
                # param = sorted(logs, key=lambda  k: k['tracker_id'])[-1]
                param = fetch_last_log(activeTestId)[0]
                if param['activity_type_id'] == "003" or param[
                        'activity_type_id'] == "004" or param[
                            'activity_type_id'] == "008":
                    testId = param['test_id']
                    data = db_utility.fetch_where("last_user_time",
                                                  {"test_id": testId})
                    if len(data) > 0:
                        Time = data[0]['log_time']
                        testTime = datetime.datetime.strptime(
                            str(Time),
                            "%Y-%m-%dT%H:%M:%S") + datetime.timedelta(
                                seconds=timeDiffAllowed)
                        # print(testTime)
                    else:
                        testTime = currentTime - datetime.timedelta(
                            seconds=timeDiffAllowed)
                        # testTime=datetime.datetime.strptime(str(Time),"%Y-%m-%dT%H:%M:%S")
                        # print(testTime)
                    if currentTime > testTime:
                        print(testId)
                        param = {}
                        param['tracker_id'] = db_utility.fetch_next_id(
                            "log_tracker", "tracker_id")
                        param['_id'] = param['tracker_id']
                        param['test_id'] = testId
                        param['activity_type_id'] = "444"
                        param['activity_time'] = datetime.datetime.now(
                        ).strftime("%Y-%m-%dT%H:%M:%S")
                        print(param)
                        data = db_utility.insert_data_one("log_tracker", param)
                        # timeDiff=currentTime-testTime
                        # print(timeDiff)
                    else:
                        data = "200"
                else:
                    data = "0"
        if data == "200":
            param = {}
            param['statusCode'] = "200"
            param['message'] = "Dropped Test Moved To Dropped Category"
        else:
            param = {}
            param['statusCode'] = "200"
            param['message'] = "No Dropped To Test"
        '''
		BUSINESS LOGIC ENDS HERE BY RETURNING RESPONSE JSON
		'''
        proxyResponse['statusCode'] = 200
        response = param
        print(response)
        proxyResponse['body'] = json.dumps(response)
        # print(proxyResponse)
    return proxyResponse