def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR,
        UserType.FREE,
        UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    status_filter = event["queryStringParameters"].get("status", "") if event["queryStringParameters"] else ""
    requestor_filter = event["queryStringParameters"].get("requestor", "") if event["queryStringParameters"] else ""
    requestee_filter = event["queryStringParameters"].get("requestee", "") if event["queryStringParameters"] else ""

    session = Session()
    filtered_query = session.query(Connection)
    if status_filter:
        filtered_query = filtered_query.filter(Connection.connection_status == status_filter)
    if requestor_filter:
        filtered_query = filtered_query.filter(Connection.requestor == requestor_filter)
    if requestee_filter:
        filtered_query = filtered_query.filter(Connection.requestee == requestee_filter)

    connections = filtered_query.all()
    session.close()

    return http_status.success(json.dumps({
            "connections": [row2dict(r) for r in connections],
            "count": len(connections)
        }))
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    chatId = event["pathParameters"].get("chatId") if event["pathParameters"] else None
    if not chatId:
        return http_status.bad_request("missing path parameter(s): 'chatId'")

    session = Session()
    chat = session.query(Chat).get(chatId)
    if not chat:
        session.close()
        return http_status.not_found("chat with id '{}' not found".format(chatId))

    admin_update_declared_chats_frequency(chat.senior_executive, -1)
    if chat.chat_status == ChatStatus.PENDING:
        admin_update_remaining_chats_frequency(chat.senior_executive, -1)

    session.delete(chat)
    session.commit()
    session.close()

    return http_status.success()
Exemple #3
0
def handler(event, context):
    authorized_user_types = [
        UserType.ADMIN,
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    body = json.loads(event["body"])
    user_email = body.get('email')
    if not user_email:
        return http_status.bad_request()

    chat_freq = 4
    attributes = {
        "custom:user_type": "MENTOR",
        "custom:declared_chats_freq": str(chat_freq),
        "custom:remaining_chats_freq": str(chat_freq)
    }
    admin_update_user_attributes(user_email, attributes)
    admin_enable_user(user_email)

    session = Session()
    for i in range(chat_freq):
        chat_type = ChatType["ONE_ON_ONE"]
        chat = Chat(chat_type=chat_type,
                    chat_status=ChatStatus.PENDING,
                    senior_executive=user_email)
        session.add(chat)

    session.commit()
    session.close()

    return http_status.success()
def handler(event, context):

    authorized_user_types = [
        UserType.ADMIN, UserType.MENTOR, UserType.PAID, UserType.FREE
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()
    jobId = event["pathParameters"]["jobId"]
    job = session.query(Job).get(jobId)

    if job != None:
        job_apps_id = []
        for app in job.job_applications:
            job_apps_id.append(app.job_application_id)
        jobdict = row2dict(job)
        jobdict['job_applications'] = job_apps_id
        session.close()
        return http_status.success(json.dumps(jobdict))
    else:
        session.close()
        return http_status.not_found()
Exemple #5
0
def handler(event, context):
    authorized_user_types = [UserType.FREE]
    success, user = check_auth(event['headers']['Authorization'],
                               authorized_user_types)
    if not success:
        return http_status.unauthorized()

    user_email = user['email']
    if not user_email:
        return http_status.bad_request()

    success = edit_auth(user, user_email)
    if not success:
        return http_status.unauthorized()

    current_timestamp = int(datetime.now().timestamp())

    attributes = {
        "custom:user_type": "PAID",
        "custom:start_date": str(current_timestamp),
        "custom:end_date":
        str(current_timestamp + 31556952)  # 31556952 is the seconds in a year
    }
    admin_update_user_attributes(user_email, attributes)
    user_credits = 25
    admin_update_credits(user_email, user_credits)
    return http_status.success()
def handler(event, context):

    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR,
        UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()
    jobAppId = event["pathParameters"]["id"]
    jobApp = session.query(JobApplication).get(jobAppId)

    if jobApp == None:
        session.commit()
        session.close()
        return http_status.not_found()
    else:
        delete = session.query(JobApplication).filter(JobApplication.job_application_id == jobAppId).delete()
        session.commit()
        session.close()
        return http_status.success()
Exemple #7
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR
    ]
    success, user = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    chatId = event["pathParameters"].get("chatId") if event["pathParameters"] else None
    if not chatId:
        return http_status.bad_request("missing path parameter(s): 'chatId'")

    session = Session()
    chat = session.query(Chat).get(chatId)
    if not chat:
        session.close()
        return http_status.not_found("chat with id '{}' not found".format(chatId))

    success = edit_auth(user, chat.senior_executive)
    if not success:
        session.close()
        return http_status.unauthorized()
 
    # DONE state can be achieved from RESERVED_CONFIRMED
    if chat.chat_status != ChatStatus.RESERVED_CONFIRMED:
        session.close()
        return http_status.forbidden("cannot mark DONE unconfirmed reservation of chat with id '{}'".format(chatId))

    chat.chat_status = ChatStatus.DONE

    session.commit()
    session.close()
    return http_status.success()
def handler(event, context):
    
    logging.info('Test')

    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR,
        UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()
    
    # # create a new session
    session = Session()
    jobId = event["pathParameters"]["jobId"]
    job = session.query(Job).get(jobId)

    
    if job != None:
        job.job_status = JobStatus.CLOSED
        
        session.commit()
        session.close()

        return http_status.success()
    else:
        session.close()
        return http_status.not_found()
def handler(event, context):

    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR, UserType.PAID]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    # FOR REFERENCE
    # # create a new session
    session = Session()
    jobId = event["pathParameters"]["jobId"]
    job = session.query(Job).get(jobId)
    if job == None:
        return http_status.not_found()
    if len(job.job_applications
           ) != 0:  # when there are job applications associated to a job
        return http_status.forbidden()

    session.query(Job).filter(Job.job_id == jobId).delete()

    # # commit and close session
    session.commit()
    session.close()
    return http_status.success()
Exemple #10
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN, UserType.MENTOR, UserType.PAID, UserType.FREE
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    search = event["queryStringParameters"].get(
        "search", "") if event["queryStringParameters"] else ""
    fuzzy = event["queryStringParameters"].get(
        "fuzzy", "") if event["queryStringParameters"] else ""

    session = Session()
    if fuzzy.lower() == "true":
        industry_tags = session.query(IndustryTag).filter(
            IndustryTag.tag.ilike("%{}%".format(search))).all()
    else:
        industry_tags = session.query(IndustryTag).filter(
            IndustryTag.tag.ilike("{}%".format(search))).all()
    session.close()

    return http_status.success(
        json.dumps({
            "industry_tags": [row2dict(r) for r in industry_tags],
            "count": len(industry_tags)
        }))
Exemple #11
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN, UserType.MENTOR, UserType.FREE, UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    connectId = event["pathParameters"].get(
        "connectId") if event["pathParameters"] else None
    if not connectId:
        return http_status.bad_request(
            "missing path parameter(s): 'connectId'")

    session = Session()
    connection = session.query(Connection).get(connectId)
    if not connection:
        session.close()
        return http_status.not_found()

    session.delete(connection)
    session.commit()
    session.close()

    return http_status.success()
def handler(event, context):

    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR, UserType.PAID]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()
    info = json.loads(event["body"])
    jobAppId = event["pathParameters"]["id"]
    jobApp = session.query(JobApplication).get(jobAppId)

    if jobApp != None:
        keys = info.keys()
        for key in keys:
            setattr(jobApp, key, info[key])

        session.commit()
        session.close()

        return http_status.success(json.dumps(info))
    else:
        return http_status.not_found()
def handler(event, context):
    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR, UserType.PAID]
    success, user = check_auth(event['headers']['Authorization'],
                               authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()
    jobId = event["pathParameters"]["jobId"]
    job = session.query(Job).get(jobId)

    if job == None:
        session.close()
        return http_status.not_found()

    user_credits = int(get_users(filter_=("email", user['email']), \
        attributes_filter=["custom:credits"])[0]['attributes'].get('custom:credits'))
    email = user['email']
    if job.can_contact:
        applied = False
        for job_app in job.job_applications:
            if job_app.applicant_id == email:
                applied = True
        if not applied:
            session.close()
            return http_status.forbidden(
                "You need to apply to the job before requesting contact-information"
            )

        if job.people_contacted >= 4:
            session.close()
            return http_status.forbidden(
                "Limit of contact information requests has been exceeded")

        if user_credits < 5:
            session.close()
            return http_status.forbidden(
                "You do not have enough credits to request contact information"
            )

        admin_update_credits(
            email, -5)  # deducting credits for requesting contact_info
        job.people_contacted = job.people_contacted + 1
        session.commit()
        return http_status.success(
            json.dumps({
                "contact_details": {
                    "email": job.posted_by,
                    "given_name": job.poster_given_name,
                    "family_name": job.poster_family_name
                }
            }))
    else:
        session.close()
        return http_status.success(
            json.dumps(
                {"message": "Hiring manager does not want to be contacted"}))
def handler(event, context):
    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR, UserType.PAID]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    # # create a new session
    session = Session()
    jobId = event["pathParameters"]["jobId"]
    job = session.query(Job).get(jobId)
    info = json.loads(event["body"])

    if job != None:  #if it was a valid jobid, and the job was found
        keys = info.keys()
        for key in keys:
            value = info[key]
            logger.info('key is ' + str(key) + ' and value is ' + str(value))
            if key == 'salary':
                if value is None or value == '':
                    value = 0
                else:
                    value = int(value)
            elif key == 'deadline':
                value = datetime.fromtimestamp(value).replace(hour=0,
                                                              minute=0,
                                                              second=0,
                                                              microsecond=0)
            elif key == 'tags':
                value = []

            if key == 'job_applications':
                continue

            setattr(job, key, value)

        session.commit()
        session.close()

        if "job_status" in keys and info["job_status"] is "ACTIVE":
            job_title = job.title
            today = datetime.today().strftime("%Y-%m-%d")
            hiring_manager = job.posted_by
            subject = "[MAX Aspire] Your job is now active!"
            body = f"Salaam!\r\n\nWe are delighted to confirm that the job posting {job_title} is successfully posted on MAX Aspire job board on {today}. You will frequently be notified about the job applications as and when received. Keep an eye on your member portal/email.\r\n\nWe appreciate you putting your trust in MAX Aspire. We wish you luck in hiring the best possible candidate form our talented pool of aspiring professionals.\r\n\nBest regards,\nTeam MAX Aspire\r\n"
            send_email(to_addresses=hiring_manager,
                       subject=subject,
                       body_text=body)

        return http_status.success()
    else:
        return http_status.not_found()
Exemple #15
0
def handler(event, context):
    authorized_user_types = [
        UserType.ADMIN, UserType.MENTOR, UserType.PAID, UserType.FREE
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()
    applicantId = ""
    jobId = ""

    if event["queryStringParameters"] != None:
        if event["queryStringParameters"].get('jobId') != None:
            jobId = event["queryStringParameters"].get('jobId')
        if event["queryStringParameters"].get('userId') != None:
            applicantId = event["queryStringParameters"].get('userId')

    if (applicantId != None and applicantId != "" and jobId != None
            and jobId != ""):
        jobApps = session.query(JobApplication).filter(
            JobApplication.applicant_id == applicantId,
            JobApplication.job_id == jobId).all()
    elif (jobId != None and jobId != ""):
        jobApps = session.query(JobApplication).filter(
            JobApplication.job_id == jobId).all()
    elif (applicantId != None and applicantId != ""):
        jobApps = session.query(JobApplication).filter(
            JobApplication.applicant_id == applicantId).all()
    else:
        jobApps = session.query(JobApplication).all()

    session.close()

    jobAppsList = []

    for jobApp in jobApps:
        jobApp_json = {
            "job_application_id": jobApp.job_application_id,
            "job_id": jobApp.job_id,
            "applicant_id": jobApp.applicant_id,
            "resumes": jobApp.resumes,
            "cover_letters": jobApp.cover_letters,
            "job_application_status": jobApp.job_application_status.name,
            "created_on": jobApp.created_on.timestamp(),
            "updated_on": jobApp.updated_on.timestamp()
        }
        jobAppsList.append(jobApp_json)
    return http_status.success(json.dumps(jobAppsList))
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.forbidden()

    # validate body
    body = json.loads(event["body"])
    senior_executive = body.get('senior_executive')
    chats_new = body.get('chats')
    if not senior_executive or not chats_new:
        return http_status.bad_request("invalid parameter(s): 'senior_executive, chats'")

    session = Session()
    for chat_new in chats_new:
        if not chat_new.get('chat_type') or chat_new['chat_type'] not in ChatType.__members__:
            session.close()
            return http_status.bad_request("invalid parameter(s): 'chat_type'")

        chat_type = ChatType[chat_new['chat_type']]
        description = chat_new.get('description')
        tags = chat_new.get('tags')
        fixed_date = chat_new.get('fixed_date')
        if chat_type in mandatory_date and not fixed_date:
            session.rollback()
            session.close()
            return http_status.bad_request("missing body attribute { fixed_date } with chat_type { %s }" % (chat_type.name))

        chat = Chat(
            chat_type=chat_type, description=description,
            chat_status=ChatStatus.PENDING, tags=tags,
            senior_executive=senior_executive
        )

        admin_update_declared_chats_frequency(senior_executive, 1)
        if fixed_date:
            chat.fixed_date = datetime.fromtimestamp(fixed_date).replace(hour=0, minute=0,second=0, microsecond=0)
            chat.chat_status = ChatStatus.ACTIVE
        else:
            admin_update_remaining_chats_frequency(senior_executive, 1)
        session.add(chat)

    session.commit()
    session.close()

    return http_status.success()
Exemple #17
0
def handler(event, context):
    authorized_user_types = [UserType.ADMIN]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    body = json.loads(event["body"])
    user_email = body.get('email')
    if not user_email:
        return http_status.bad_request()

    admin_disable_user(user_email)
    # TODO: should we remove the user's chats/jobs etc...?
    return http_status.success()
Exemple #18
0
def handler(event, context):
    authorized_user_types = [
        UserType.ADMIN
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    # validate body
    body = json.loads(event["body"])
    user_email = body.get('email')
    if not user_email:
        return http_status.bad_request()

    admin_enable_user(user_email)
    return http_status.success()
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN, UserType.MENTOR, UserType.FREE, UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    connectId = event["pathParameters"].get(
        "connectId") if event["pathParameters"] else None
    if not connectId:
        return http_status.bad_request(
            "missing path parameter(s): 'connectId'")

    session = Session()
    connection = session.query(Connection).get(connectId)
    if not connection:
        session.close()
        return http_status.not_found()

    body = json.loads(event["body"])
    new_connection_status = body.get('connect_status')
    if new_connection_status and new_connection_status not in ConnectionStatus.__members__:
        session.close()
        return http_status.bad_request(
            "invalid parameter(s): 'connect_status'")

    if new_connection_status:
        if connection.connection_status == ConnectionStatus.PENDING and new_connection_status == 'ACCEPTED':
            # TODO: dynamic user_email
            # TODO: update email subject/body
            user_email = "*****@*****.**"
            email_subject = "Your Senior Executive connection request was accepted"
            email_body = "<name> has accepted your connection request!"
            send_email(to_addresses=user_email,
                       subject=email_subject,
                       body_text=email_body)

        connection.connection_status = ConnectionStatus[new_connection_status]

    session.commit()
    session.refresh(connection)
    session.close()

    return http_status.success(json.dumps(row2dict(connection)))
def handler(event, context):
    authorized_user_types = [UserType.ADMIN, UserType.PAID, UserType.FREE]
    success, user = check_auth(event['headers']['Authorization'],
                               authorized_user_types)
    if not success:
        return http_status.unauthorized()

    body = json.loads(event["body"])
    user_email = body.get('email')
    user_credits = body.get('credits')
    if not user_email or not credits or not isinstance(user_credits, int):
        return http_status.bad_request()

    success = edit_auth(user, user_email)
    if not success:
        return http_status.unauthorized()

    admin_update_credits(user_email, user_credits)
    return http_status.success()
def handler(event, context):
    # check authorization
    authorized_user_types = [UserType.ADMIN]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    industryTagId = event["pathParameters"].get("industryTagId") if event["pathParameters"] else None
    if not industryTagId:
        return http_status.bad_request("missing path parameter(s): 'industryTagId'")

    session = Session()
    industry_tag = session.query(IndustryTag).get(industryTagId.lower())
    if not industry_tag:
        session.close()
        return http_status.not_found()

    session.delete(industry_tag)
    session.commit()
    session.close()

    return http_status.success()
def handler(event, context):
    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR]
    success, user = check_auth(event['headers']['Authorization'],
                               authorized_user_types)
    if not success:
        return http_status.unauthorized()

    chatId = event["pathParameters"].get(
        "chatId") if event["pathParameters"] else None
    if not chatId:
        return http_status.bad_request("missing path parameter(s): 'chatId'")

    session = Session()
    chat = session.query(Chat).get(chatId)
    if not chat:
        session.close()
        return http_status.not_found(
            "chat with id '{}' not found".format(chatId))

    success = edit_auth(user, chat.senior_executive)
    if not success:
        session.close()
        return http_status.unauthorized()

    # TODO: allow updating description, tags and fixed_date?
    # if fixed_date => what if it's active or pending with expiry_date specified?
    body = json.loads(event["body"])
    description_new = body.get('description')
    tags_new = body.get('tags')
    fixed_date_new = body.get('fixed_date')

    session.commit()
    session.refresh(chat)
    session.close()

    return http_status.success(json.dumps(row2dict(chat)))
def handler(event, context):
    # check authorization
    authorized_user_types = [UserType.ADMIN]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    status_filter = event["queryStringParameters"].get(
        "status", "") if event["queryStringParameters"] else ""
    type_filter = event["queryStringParameters"].get(
        "type", "") if event["queryStringParameters"] else ""
    senior_executive_filter = event["queryStringParameters"].get(
        "senior_executive", "") if event["queryStringParameters"] else ""

    session = Session()
    filtered_query = session.query(Chat)
    if status_filter and status_filter in ChatStatus.__members__:
        filtered_query = filtered_query.filter(
            Chat.chat_status == ChatStatus[status_filter])
    if type_filter and type_filter in ChatType.__members__:
        filtered_query = filtered_query.filter(
            Chat.chat_type == ChatType[type_filter])
    if senior_executive_filter:
        filtered_query = filtered_query.filter(
            Chat.senior_executive == senior_executive_filter)

    chats = filtered_query.all()
    for chat in chats:
        admin_update_declared_chats_frequency(chat.senior_executive, -1)
        if chat.chat_status == ChatStatus.PENDING:
            admin_update_remaining_chats_frequency(chat.senior_executive, -1)
        session.delete(chat)

    session.commit()
    session.close()
    return http_status.success()
def handler(event, context):
    authorized_user_types = [
        UserType.MENTOR,
        UserType.PAID,
        UserType.FREE
    ]
    success, user = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    userId = event["pathParameters"].get("userId") if event["pathParameters"] else None
    if not userId:
        return http_status.bad_request()

    user_edit, _ = get_users(filter_=('email', userId))
    if not user_edit:
        return http_status.not_found()
    user_attributes = user_edit['attributes']
    success = edit_auth(user, user_attributes.pop('email'))
    if not success:
        return http_status.unauthorized()

    body = json.loads(event["body"])

    user_type = user['custom:user_type']
    if user_type == 'MENTOR':
        body['custom:resume'] = 'https://aspire-user-profile.s3.amazonaws.com/blank_resume.pdf'

    new_attrs = {}
    for key in body:
        if key not in standard_attributes:
            key = 'custom:' + key
        new_attrs[key] = body[key]

    admin_update_user_attributes(user['email'], new_attrs)
    return http_status.success(json.dumps(user))
def handler(event, context):
    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR]
    success, user = check_auth(event['headers']['Authorization'],
                               authorized_user_types)
    if not success:
        return http_status.unauthorized()

    chatId = event["pathParameters"].get(
        "chatId") if event["pathParameters"] else None
    if not chatId:
        return http_status.bad_request("missing path parameter(s): 'chatId'")

    session = Session()
    chat = session.query(Chat).get(chatId)
    if not chat:
        session.close()
        return http_status.not_found(
            "chat with id '{}' not found".format(chatId))

    success = edit_auth(user, chat.senior_executive)
    if not success:
        session.close()
        return http_status.unauthorized()

    # CANCELED state can be achieved from PENDING, ACTIVE, RESERVED_PARTIAL, RESERVED or RESERVED_CONFIRMED
    #
    # if chat to be canceled is dated (i.e. cannot be rescheduled):
    #   - if PENDING    => N/A
    #   - else          => set to CANCELED, refund APs
    #
    # if chat to be canceled is undated (i.e. can be rescheduled):
    #   - set to CANCELED
    #   - refund APs
    #   - create a new PENDING chat to be rescheduled
    #   - if not PENDING
    #       - increment remaining chat frequency in Cognito
    # TODO: send email notification to SEs and APs
    if chat.chat_status == ChatStatus.DONE or chat.chat_status == ChatStatus.CANCELED or chat.chat_status == ChatStatus.EXPIRED:
        session.close()
        return http_status.forbidden(
            "cannot cancel DONE, CANCELED or EXPIRED chat with id '{}'".format(
                chatId))

    for ap in chat.aspiring_professionals:
        admin_update_credits(ap, credit_mapping[chat.chat_type])

    if not chat.fixed_date:
        chat_new = Chat(chat_type=chat.chat_type,
                        description=chat.description,
                        chat_status=ChatStatus.PENDING,
                        tags=chat.tags,
                        senior_executive=chat.senior_executive)
        session.add(chat_new)

        if chat.chat_status != ChatStatus.PENDING:
            admin_update_remaining_chats_frequency(chat.senior_executive, 1)
    chat.chat_status = ChatStatus.CANCELED

    session.commit()
    session.close()
    return http_status.success()
def handler(event, context):
    authorized_user_types = [UserType.FREE, UserType.PAID]
    success, user = check_auth(event['headers']['Authorization'],
                               authorized_user_types)

    if not success:
        return http_status.unauthorized(
            "Thank-you so kindly for being a MAX Aspire member. To support our operational costs, this specific feature is available if you sign up for a paid plan or purchase credits"
        )

    chatId = event["pathParameters"].get(
        "chatId") if event["pathParameters"] else None
    if not chatId:
        return http_status.bad_request("missing path parameter(s): 'chatId'")

    session = Session()
    chat = session.query(Chat).get(chatId)
    if not chat:
        session.close()
        return http_status.not_found(
            "chat with id '{}' not found".format(chatId))

    # ACTIVE Chats are available for booking
    # User must not have booked this Chat and must have sufficient funds
    if chat.chat_status != ChatStatus.ACTIVE:
        session.close()
        return http_status.forbidden("Chat is not available for booking")

    if chat.aspiring_professionals and user[
            'email'] in chat.aspiring_professionals:
        session.close()
        return http_status.forbidden(
            "user '{}' already reserved chat with id '{}'".format(
                user['email'], chatId))

    user_credits = int(get_users(filter_=("email", user['email']), \
        attributes_filter=["custom:credits"])[0]['attributes'].get('custom:credits'))
    if user_credits < credit_mapping[chat.chat_type]:
        session.close()
        return http_status.forbidden(
            "Thank-you so kindly for being a MAX Aspire member. To support our operational costs, this specific feature is available if you sign up for a paid plan or purchase credits"
        )

    chat.aspiring_professionals = [user['email']]
    chat.chat_status = ChatStatus.RESERVED

    try:
        prepare_and_send_emails(chat)
    except ClientError as e:
        session.rollback()
        session.close()
        logging.info(e)
        if int(e.response['ResponseMetadata']['HTTPStatusCode']) >= 500:
            return http_status.server_error()
        else:
            return http_status.bad_request()
    else:
        admin_update_credits(user['email'], (-credit_mapping[chat.chat_type]))

        session.commit()
        session.close()
        return http_status.success()
Exemple #27
0
def handler(event, context):
    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR, UserType.PAID]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()

    info = json.loads(event["body"])

    tags = []
    salary = 0

    tag = info.get('job_tags')
    job_title = info.get('title')
    company = info.get('company')
    region = info.get('region')
    city = info.get('city')
    country = info.get('country')
    job_type = info.get('job_type')
    description = info.get('description')
    requirements = info.get('requirements')
    posted_by = info.get('posted_by')
    poster_family_name = info.get('poster_family_name')
    poster_given_name = info.get('poster_given_name')
    salary = str(info.get('salary'))
    deadline = info.get('deadline')
    can_contact = str(info.get('can_contact'))

    if salary is None or salary == '':
        salary = "0"

    #Validate body
    if not (job_title and company and region and city and country and job_type
            and description and requirements and posted_by
            and poster_family_name and poster_given_name and salary
            and deadline and can_contact):
        return http_status.bad_request("missing parameter(s)")
    else:
        # If no attributes are missing, cast types as required.
        try:
            salary = int(salary)
            deadline = datetime.fromtimestamp(deadline).replace(hour=0,
                                                                minute=0,
                                                                second=0,
                                                                microsecond=0)

            if can_contact.lower() == 'true':
                can_contact = True
            elif can_contact.lower() == 'false':
                can_contact = False
            else:
                raise ValueError

            job_type = JobType[job_type]
            for tag in info["job_tags"]:
                tags.append(JobTags[tag])
        except:
            return http_status.bad_request(
                "invalid parameter(s): 'salary must be an integer, deadline must be a datetime, can_contact must be a bool, and JobType & JobTags must be from their enum types'"
            )

    Job_row = Job(title=job_title,
                  company=company,
                  region=region,
                  city=city,
                  country=country,
                  job_type=job_type,
                  description=description,
                  requirements=requirements,
                  posted_by=posted_by,
                  poster_family_name=poster_family_name,
                  poster_given_name=poster_given_name,
                  job_status='UNDER_REVIEW',
                  job_tags=tags,
                  salary=salary,
                  deadline=deadline,
                  can_contact=can_contact)

    session.add(Job_row)
    session.commit()
    res = row2dict(Job_row)
    session.close()

    ##email hiring manager
    job_title = info["title"]
    today = datetime.today().strftime("%Y-%m-%d")
    hiring_manager = str(info["posted_by"])

    # The send_email_templated function requires JSON Formatted Data with " strings "
    template_data = {"job_title": str(job_title), "today": str(today)}
    template_data = json.dumps(template_data)
    recipients = [hiring_manager]
    send_templated_email(recipients, "Job-Creation", template_data)

    return http_status.success(json.dumps(res))
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR,
        UserType.FREE,
        UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    body = json.loads(event["body"])
    try:
        requestor = body['requestor']
        requestee = body['requestee'] 
    except:
        return http_status.bad_request("missing body attribute(s): 'requestor' or 'requestee'")

    try:
        requestor_email = requestor['email']
        requestor_type = requestor['user_type']
        requestor_name = requestor['name']
        requestee_email = requestee['email']
        requestee_type = requestee['user_type']
        requestee_name = requestee['name']
    except:
        return http_status.bad_request("missing body attribute(s): 'user_type', 'email' or 'name'")

    session = Session()
    connections = session.query(Connection).all()
    create_conn = True
    for connection in connections:
        if (connection.requestor == requestor_email and connection.requestee == requestee_email) \
            or (connection.requestor == requestee_email and connection.requestee == requestor_email):
            if connection.connection_status == ConnectionStatus.PENDING:
                if connection.requestor == requestee_email and connection.requestee == requestor_email:
                    connection.connection_status = ConnectionStatus.ACCEPTED

                    template_data = {
                        "requestee_name": str(requestee_name),
                        "requestor_name": str(requestor_name)
                    }
                    template_data = json.dumps(template_data)
                    recipients = [requestor_email,requestee_email]
                    send_templated_email(recipients, "Connection-Confirmation-SEtoSE", template_data)    

                    create_conn = False
                    break

                session.close()
                return http_status.bad_request("connections request already sent")
            elif connection.connection_status == ConnectionStatus.ACCEPTED:
                session.close()
                return http_status.bad_request("connections request already established")

    if create_conn:
        if requestee_type == "MENTOR" and requestor_type == "MENTOR":
            new_connection = Connection(requestor=requestor_email, requestee=requestee_email, connection_status=ConnectionStatus.PENDING)
            session.add(new_connection)

            template_data = {
                "requestee_name": str(requestee_name),
                "requestor_name": str(requestor_name)
            }
            template_data = json.dumps(template_data)
            recipients = [requestee_email]
            send_templated_email(recipients, "Connection-Initiation-SEtoSE", template_data)    



        elif requestee_type == "MENTEE" and requestor_type == "MENTOR":
            new_connection = Connection(requestor=requestor_email, requestee=requestee_email, connection_status=ConnectionStatus.ACCEPTED)
            session.add(new_connection)

            # The send_templated_email function requires JSON Formatted Data with " strings "
            template_data = {
                "requestee_name": str(requestee_name),
                "requestor_name": str(requestor_name)
            }
            template_data = json.dumps(template_data)
            recipients = [requestor_email, requestee_email]
            send_templated_email(recipients, "Connection-Initiation-SEtoAP", template_data)           

        else:
            return http_status.bad_request("A connection can only be initiated by a mentor")

    session.commit()
    session.close()

    return http_status.success()
def handler(event, context):

    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR, UserType.PAID]
    success, user = check_auth(event['headers']['Authorization'],
                               authorized_user_types)
    if not success:
        return http_status.unauthorized(
            "You have to be a paid member to be able to apply to jobs")

    email = user['email']
    candidate_name = user["given_name"] + " " + user["family_name"]

    session = Session()
    info = json.loads(event["body"])
    job_id = info.get('job_id')
    resumes = info.get('resumes')
    cover_letters = info.get('cover_letters')

    #Validate Body
    if not (job_id and resumes and cover_letters):
        return http_status.bad_request(
            "missing parameter(s): 'job_id, resumes, cover_letters'")
    else:
        try:
            job_id = int(job_id)
        except ValueError:
            return http_status.bad_request(
                "invalid parameter: 'job_id must be an integer'")

    job = session.query(Job).get(job_id)
    hiring_manager = job.posted_by
    if hiring_manager == email:
        return http_status.forbidden("Hiring manager cannot apply to the job")

    existing_job_application = session.query(JobApplication).filter(
        JobApplication.applicant_id == email).filter(
            JobApplication.job_id == job_id).all()
    if len(existing_job_application) > 0:
        return http_status.forbidden("You have already applied to this job")

    job_rs = JobApplication(job_id=job_id,
                            applicant_id=email,
                            job_application_status=JobApplicationStatus.SUBMIT,
                            resumes=resumes,
                            cover_letters=cover_letters)
    session.add(job_rs)
    session.commit()

    job_title = job.title
    today = datetime.today().strftime("%Y-%m-%d")
    hiring_manager = str(job.posted_by)

    # The send_email_templated function requires JSON Formatted Data with " strings "
    template_data = {
        "candidate_name": str(candidate_name),
        "job_title": str(job_title),
        "today": str(today)
    }
    template_data = json.dumps(template_data)
    recipients = [hiring_manager]
    send_templated_email(recipients, "JobApplication-Creation-HiringManager",
                         template_data)

    template_data = {"job_title": str(job_title), "today": str(today)}
    template_data = json.dumps(template_data)
    recipients = [email]
    send_templated_email(recipients, "JobApplication-Creation-Applicant",
                         template_data)

    resp = row2dict(job_rs)
    session.close()

    return http_status.success(json.dumps(resp))