Example #1
0
    def post(self):
        #	Check if any projects exist
        existingProjects, error = Project.queryAll()
        if error:
            return res.internalServiceError(error)

        #	get existing projects from 42 API
        data = Api42.allProjects()
        if not data:
            return res.internalServiceError("unable to query the 42 API")

        #	only add new projects that are not in the projects table
        newProjects = []
        existingProjects = []
        for d in data:
            #	check if project exists
            projectCheck = Project.query.filter_by(
                id_project42=d['id_project42']).first()

            #	only add the new projects that don't exist in the database
            if not projectCheck:
                newProject, err = project_schema.load(d)
                if err:
                    db.session.rollback()
                    return res.internalServiceError('bad data')
                db.session.add(newProject)
                newProjects.append(project_schema.dump(newProject).data)
            else:
                projectCheck.name = d['name']
                projectCheck.slug = d['slug']
                projectCheck.tier = d['tier']
                existingProjects.append(project_schema.dump(projectCheck).data)

        print("COMMITTING NEW PROJECTS")
        db.session.commit()

        #   change return message if projects were updated
        retMessage = 'created new project' if newProjects else 'no new projects needed to be updated'
        retData = {
            'newProjects': newProjects,
            'existingProjects': existingProjects
        }
        return res.postSuccess(retMessage, retData)


#	LOAD takes a python DICTIONARY of data and will return a new CLASS object (the 'record')
#	DUMP takes a CLASS object (the 'record') and returns a tuple of data and something else
Example #2
0
 def get(self, id_user42):
     queryUser = User.query.filter_by(id_user42=id_user42).first()
     if not queryUser:
         return res.resourceMissing('User {} not found.'.format(id_user42))
     
     userStats = {}
     userStats['globalStats'] = user_schema.dump(queryUser).data
     
     mentorStats = []
     mentors = getattr(queryUser, 'mentor')
     for m in mentors:
         mentorObj = {}
         mentorObj['mentorstat'] = mentorstatschema.dump(getattr(m, 'mentorstat')).data
         mentorObj['project'] = project_schema.dump(getattr(m, 'project')).data
         mentorStats.append(mentorObj)
     userStats['mentorStats'] = mentorStats
     return res.getSuccess("Stats for user {}".format(queryUser.login), userStats)
Example #3
0
	def get(self, userId):
		#	Appointments Table query for the specified user as mentee
		queryAppointments = Appointment.query \
			.join(User) \
			.filter(Appointment.status==Status['Pending']) \
			.filter(User.id_user42==userId) \
			.all()
		if not queryAppointments:
			return res.resourceMissing("No appointments found")
		pendingAppointments = []
		for a in queryAppointments:
			obj = {
				'appointment': appointment_schema.dump(a).data,
				'mentor': user_schema.dump(getattr(getattr(a, 'mentor'), 'user')).data,
				'project': project_schema.dump(getattr(getattr(a, 'mentor'), 'project')).data
			}
			pendingAppointments.append(obj)
		return res.getSuccess("Appointmensts for user", pendingAppointments)
Example #4
0
    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)
Example #5
0
    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)