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()
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): 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): # 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): 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 ] 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()
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): userId = event["pathParameters"].get( "userId") if event["pathParameters"] else None if not userId: return http_status.bad_request() user, _ = get_users(filter_=('email', userId)) if not user: return http_status.not_found() return http_status.success(json.dumps(user))
def handler(event, context): session = Session() try: default_num_activate = 25 current_date = datetime.strptime(datetime.now().strftime("%d/%m/%Y"), "%d/%m/%Y") scheduling_period = 7 if event.get("queryStringParameters"): if event["queryStringParameters"].get("num_activate"): default_num_activate = int( event["queryStringParameters"]["num_activate"]) if event["queryStringParameters"].get("current_date"): current_date = datetime.strptime( event["queryStringParameters"]["current_date"], "%d/%m/%Y") if event["queryStringParameters"].get("scheduling_period"): scheduling_period = int( event["queryStringParameters"]["scheduling_period"]) next_date = current_date + timedelta(days=scheduling_period) logger.info("num_activate={}, current_date={}, next_date={}"\ .format(default_num_activate, current_date.strftime("%d/%m/%Y"), next_date.strftime("%d/%m/%Y"))) users, _ = get_users(user_type='MENTOR') num_carry_over = 0 total_unbooked = 0 total_expiring_activated = 0 for id in users: user = users[id] num_unbooked, num_expiring_activated = schedule_user( session, user['attributes'], current_date, next_date) total_unbooked += num_unbooked total_expiring_activated += num_expiring_activated logger.info("Carry Forward={}".format(num_carry_over)) logger.info("Number of Unbooked Chats (previous cycle)={}".format( total_unbooked)) logger.info("Number of Activated Expiring Chats={}".format( total_expiring_activated)) schedule_activate(session, default_num_activate, num_carry_over) except Exception as e: session.rollback() session.close() import traceback traceback.print_exc() return http_status.bad_request( "exception caught while running scheduler {}".format(e)) session.commit() session.close() return http_status.success( json.dumps({"next_date": next_date.strftime("%d/%m/%Y")}))
def handler(event, context): try: req_body = json.loads(event["body"]) if "payment_method_id" in req_body and "amount" in req_body and "email" in req_body: _amount = int(float(req_body["amount"]) * 100) _email = req_body["email"] intent = stripe.PaymentIntent.create( payment_method=req_body["payment_method_id"], amount=_amount, currency='cad', confirmation_method='automatic', confirm=True, payment_method_types=["card"], receipt_email=_email) return generate_response(intent) else: return http_status.bad_request( 'Missing required attributes: payment_method_id, amount, email' ) except Exception as e: return http_status.bad_request('Payment failed. ' + str(e))
def handler(event, context): 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) session.close() if not chat: return http_status.not_found("chat with id '{}' not found".format(chatId)) return http_status.success(json.dumps( row2dict(chat) ))
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()
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): 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): 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, 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): 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()
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))
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): # 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 generate_response(intent): if intent.status == 'succeeded': return http_status.success() else: return http_status.bad_request( 'Payment failed. Invalid payment status')