def post(self): data = request.get_json() print(data.get('code')) if not data or not data.get("code"): return res.badRequestError(message="No authorizen token provided.") accessReq = requests.post('https://api.intra.42.fr/oauth/token', data= { 'grant_type' : 'authorization_code', 'client_id' : app.config['CLIENT_ID'], 'client_secret' : app.config['CLIENT_SECRET'], 'code' : data.get('code'), 'redirect_uri' : "http://localhost:8080/auth" }).json() if not accessReq or 'error' in accessReq: return res.badRequestError(message=accessReq['error_description']) LoggedUser = requests.get('https://api.intra.42.fr/v2/me', headers= { 'Authorization' : 'Bearer {}'.format(accessReq['access_token'])}).json() queryUser = User.query.filter_by(id_user42=LoggedUser['id']).first() err = None # Registers user if record doesn't exist in Sensei database if not queryUser: data, err = registerUser(LoggedUser) if err: return res.internalServiceError(err) else: queryUser.last_seen = datetime.datetime.now() db.session.commit() #print(LoggedUser) return res.postSuccess(data={'access': accessReq, 'user': LoggedUser, 'error': err})
def delete(self, appointmentId): # Checks appointment record exists appointment = Appointment.query.filter_by(id=appointmentId).first() # Add sommething ca if not appointment: return res.resourceMissing( "Appointment {} not found".format(appointmentId)) # Verifies appointment status is 'Pending' if appointment.status == Status['Finished']: return res.badRequestError( "Appoint has already been marked as finished.") if appointment.status == Status['Cancelled']: return res.badRequestError("Appointment already cancelled.") mentorStat = getattr(getattr(appointment, 'mentor'), 'mentorstat') mentorStat.cancelledappointments += 1 # Cancel appointment by setting status = 3 appointment.status = Status['Cancelled'] db.session.commit() return res.putSuccess( "Appointment {} cancelled.".format(appointmentId), appointment_schema.dump(appointment).data)
def put(self, appointmentId): data = request.get_json() if not data: return res.badRequestError("No data provided") # Checks appointment record exists appointment = Appointment.query.filter_by(id=appointmentId).first() if not appointment: return res.resourceMissing( "Appointment {} not found".format(appointmentId)) if 'feedback' in data: if len((data.get('feedback')).strip()) <= 4: return res.badRequestError('Feedback needs to be longer.') appointment.feedback = data.get('feedback') if 'status' in data: if data.get('status') != Status['Cancelled']: appointment.status = data.get('status') mentor = getattr(appointment, 'mentor') if 'rating' in data: if type(data.get('rating')) is not int or data.get( 'rating') < 1 or data.get('rating') > 5: return res.badRequestError( "Rating '{}' not supported. Please see Sensei documentation for Rating used" .format(data.get('rating'))) appointment.rating = data.get('rating') # Updating mentor mentor.last_appointment = datetime.datetime.now() # Updating mentor stats mentorStat = getattr(mentor, 'mentorstat') mentorStat.totalappointments += 1 mentorStat.rating = mentorStat.rating + ( (data.get('rating') - mentorStat.rating) / mentorStat.totalappointments) # Updating global user stats userRecord = getattr(mentor, 'user') userRecord.totalappointments += 1 userRecord.rating = userRecord.rating + ( (data.get('rating') - userRecord.rating) / userRecord.totalappointments) db.session.commit() return res.putSuccess("Appointment {} updated.".format(appointmentId), appointment_schema.dump(appointment).data)
def put(self, mentorId): data = request.get_json() if not data: return res.badRequestError( "No data provided. Please read API documentation") queryMentor = Mentor.query \ .filter_by(id=mentorId) \ .first() if not queryMentor: return res.badRequestError( "No mentor with id {} was found".format(mentorId)) if 'active' in data: queryMentor.active = data.get('active') db.session.commit() return res.putSuccess('Mentor {} updated'.format(mentorId))
def get(self, projectId): # get mentors that exist for that project query = Mentor.query \ .filter_by(id_project42=projectId, active=True) \ .all() if not query: return res.badRequestError( 'No Projects with id {} exist'.format(projectId)) mentors = mentors_schema.dump(query).data return res.getSuccess( 'mentors available for project {}'.format(projectId), result)
def get(self, mentorId): query = Mentor.query.filter_by(id=mentorId).first() if not query: return res.badRequestError( 'no mentor record with id {} exists'.format(mentorId)) data = mentor_schema.dump(query).data if not data: return res.internalServiceError('failed to build mentor data') return res.getSuccess( 'mentor data retrieved for user {} on project {}'.format( query.user.login, query.project.name), data)
def post(self): data = request.get_json() # Checks if required data to create an appointment was provided in request if not data: return res.badRequestError("Missing data to process request.") if not data.get("topic") and not data.get("project"): return res.badRequestError( "Missing data to process request. No topic or project provided to search for mentors" ) if not data.get("login"): return res.badRequestError( "Missing data to process request. No user login provided") # Checks if project name exists in database queryProject = Project.query.filter_by( name=data.get("project")).first() if not queryProject: return res.resourceMissing("No project {} found.".format( data.get("project"))) project, error = project_schema.dump(queryProject) if error: return res.internalServiceError(error) # Checks if user with provided login exists in database user, error = User.queryByLogin(data.get("login")) if error: return res.resourceMissing(error) # Check if the user already has an appointment pending queryUserAppointment = Appointment.query.filter_by( id_user=user['id'], status=Status['Pending']).first() if queryUserAppointment: return res.badRequestError( "You have already an appointment pending") # Limits appointments made by user for a specific project projectAppointmentsCount = Appointment.queryCountProjectAppointmentsbyUser( project["id_project42"], user["id"]) if projectAppointmentsCount > _maxAppointmentsPerDay: return res.badRequestError( "User reached limit appointments for project {}".format( data.get("project"))) # jmeier id 23677, mentor id 48 project rec 847 # Filters out any mentors who have an appointment pending goodMentors = [] queryMentor = Mentor.query \ .filter(Mentor.id_project42==project['id_project42'], Mentor.active==True, Mentor.id_user42!=user['id_user42']) \ .all() # Check that the mentor does not have an existing pending appointment for q in queryMentor: appointment = Appointment.query.filter( Appointment.id_mentor == q.id, Appointment.status == Status['Pending']).first() if not appointment: goodMentors.append(q) if not goodMentors: return res.resourceMissing( 'No mentors without pending appointments found') onlineUsers = Api42.onlineUsers() # Checks online students is not empty if len(onlineUsers) == 0: return res.resourceMissing("No mentors found on campus.") # Filtering out the available mentors with the online students availablementors = [ mentor for mentor in goodMentors for o in onlineUsers if mentor.id_user42 == o['id'] ] # Checks if there is avaliable online mentors for the project/topic if not availablementors: return res.resourceMissing( "No mentors online found for {}.".format(data.get("project"))) # Calls 'mentor algorithm' to select a mentor from availablementors. chosenMentor = mentorAlgorithm(availablementors) # Creates and returns appointment if valid if not chosenMentor: return res.internalServiceError("Error: mentor selection.") mentorLogin = [ i['login'] for i in onlineUsers if i['id'] == chosenMentor.id_user42 ][0] # Gets the mentor's 'login' if not mentorLogin: return res.internalServiceError('Something strange happened') # FINALLY, create the appointment newappointment, error = Appointment.createAppointment( chosenMentor.id, user['id']) if error: return res.internalServiceError(error) return res.postSuccess("Appointment created successfully", newappointment)
def get(self, appointmentId): appointment, err = Appointment.queryById(appointmentId) if err: return res.badRequestError(err) return res.getSuccess(appointment)
def post(self): data = request.get_json() # Checks if required data to create an appointment was provided in request if not data: return res.badRequestError("Missing data to process request.") if not data.get("topic") and not data.get("project"): return res.badRequestError( "Missing data to process request. No topic or project provided to search for mentors" ) if not data.get("login"): return res.badRequestError( "Missing data to process request. No user login provided") # Checks if project name exists in database queryProject = Project.query.filter_by( name=data.get("project")).first() if not queryProject: return res.resourceMissing("No project {} found.".format( data.get("project"))) project, error = project_schema.dump(queryProject) if error: return res.internalServiceError(error) print(project) # Checks if user with provided login exists in database user, error = User.queryByLogin(data.get("login")) if error: return res.resourceMissing(error) print(user) queryUserAppointment = Appointment.query.filter_by( id_user=user['id'], status=Status['Pending']).first() if queryUserAppointment: return res.badRequestError( "You have already an appointment pending") # Limits appointments made by user for a specific project projectAppointmentsCount = Appointment.queryCountProjectAppointmentsbyUser( project["id_project42"], user["id"]) if projectAppointmentsCount > _maxAppointmentsPerDay: return res.badRequestError( "User reached limit appointments for project {}".format( data.get("project"))) # Retrieves available mentors for the specified project queryMentor = Mentor.query \ .filter(~Mentor.appointments.any(), Mentor.id_project42==project['id_project42'], Mentor.active==True, Mentor.id_user42!=user['id_user42']) \ .all() queryMentor2 = Mentor.query \ .join(Appointment) \ .filter(Mentor.id_project42==project['id_project42'], Mentor.active==True, Mentor.id_user42!=user['id_user42']) \ .filter(Appointment.status==2) \ .all() for q in queryMentor2: queryMentor.append(q) if not queryMentor: print("hereee") return res.resourceMissing( 'No mentors found for project {}'.format(data.get('project'))) #mentors = [mentor for mentor in queryMentor if mentor.app] #mentors = mentors_schema.dump(queryMentor).data onlineUsers = Api42.onlineUsers() # Checks online students is not empty if len(onlineUsers) == 0: return res.resourceMissing("No mentors found on campus.") availablementors = [ mentor for mentor in queryMentor for x in onlineUsers if mentor.id_user42 == x['id'] ] # Checks if there is avaliable online mentors for the project/topic if not availablementors: return res.resourceMissing( "No mentors online found for {}.".format(data.get("project"))) # Calls 'mentor algorithm' to select a mentor from availablementors. chosenMentor = mentorAlgorithm(availablementors) print(chosenMentor) # Creates and returns appointment if valid if not chosenMentor: return res.internalServiceError("Error: mentor selection.") newappointment, error = Appointment.createAppointment( chosenMentor.id, user['id']) if error: return res.internalServiceError(error) print(newappointment) return res.postSuccess("Appointment created successfully", newappointment)
def get(self): query = Mentor.query.all() if not query: return res.badRequestError("No mentors") data = mentors_schema.dump(query).data return res.getSuccess('all mentors', data)