def test_complete_task_api(self):

        relation = MentorshipRelationModel.find_by_id(
            self.mentorship_relation_w_second_user.id
        )
        incomplete_task = relation.tasks_list.find_task_by_id(1)
        self.assertIsNotNone(incomplete_task)
        self.assertIsNone(incomplete_task.get("completed_at"))
        self.assertFalse(incomplete_task.get("is_done"))

        auth_header = get_test_request_header(self.first_user.id)
        expected_response = messages.TASK_WAS_ACHIEVED_SUCCESSFULLY
        actual_response = self.client.put(
            "/mentorship_relation/%s/task/%s/complete"
            % (self.mentorship_relation_w_second_user.id, 1),
            follow_redirects=True,
            headers=auth_header,
        )

        self.assertEqual(200, actual_response.status_code)
        self.assertDictEqual(expected_response, json.loads(actual_response.data))

        relation = MentorshipRelationModel.find_by_id(
            self.mentorship_relation_w_second_user.id
        )
        complete_task = relation.tasks_list.find_task_by_id(1)
        self.assertIsNotNone(complete_task)
        self.assertIsNotNone(complete_task.get("completed_at"))
        self.assertTrue(complete_task.get("is_done"))
Beispiel #2
0
    def setUp(self):
        super(TestListMentorshipRelationsApi, self).setUp()

        self.notes_example = "description of a good mentorship relation"
        self.now_datetime = datetime.now()
        self.past_end_date_example = self.now_datetime - timedelta(weeks=5)
        self.future_end_date_example = self.now_datetime + timedelta(weeks=5)

        # create new mentorship relation

        self.past_mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.past_end_date_example.timestamp(),
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        self.future_pending_mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.future_end_date_example.timestamp(),
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        self.future_accepted_mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.future_end_date_example.timestamp(),
            state=MentorshipRelationState.ACCEPTED,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        self.admin_only_mentorship_relation = MentorshipRelationModel(
            action_user_id=self.admin_user.id,
            mentor_user=self.admin_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.future_end_date_example.timestamp(),
            state=MentorshipRelationState.REJECTED,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        db.session.add(self.past_mentorship_relation)
        db.session.add(self.future_pending_mentorship_relation)
        db.session.add(self.future_accepted_mentorship_relation)
        db.session.commit()
    def delete_request(user_id: int, request_id: int):
        """Deletes a mentorship request.

        Deletes a mentorship request if the current user was the one who created it and the request is in the pending state.

        Args:
            user_id: ID of the user that is deleting a request.
            request_id: ID of the request.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relation request is deleted, failure if otherwise.
        """

        user = UserModel.find_by_id(user_id)
        request = MentorshipRelationModel.find_by_id(request_id)

        # verify if request exists
        if request is None:
            return messages.MENTORSHIP_RELATION_REQUEST_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # verify if request is in pending state
        if request.state != MentorshipRelationState.PENDING:
            return messages.NOT_PENDING_STATE_RELATION, HTTPStatus.BAD_REQUEST

        # verify if user created the mentorship request
        if request.action_user_id != user_id:
            return messages.CANT_DELETE_UNINVOLVED_REQUEST, HTTPStatus.BAD_REQUEST

        # All was checked
        request.delete_from_db()

        return messages.MENTORSHIP_RELATION_WAS_DELETED_SUCCESSFULLY, HTTPStatus.OK
 def test_recepient_already_in_relation_accept_request(self):
     # create existing relation between admin_user and second_user
     mentorship_relation_current = MentorshipRelationModel(
         action_user_id=self.admin_user.id,
         mentor_user=self.admin_user,
         mentee_user=self.second_user,
         creation_date=self.now_datetime.timestamp(),
         end_date=self.end_date_example.timestamp(),
         state=MentorshipRelationState.ACCEPTED,
         notes=self.notes_example,
         tasks_list=TasksListModel(),
     )
     db.session.add(mentorship_relation_current)
     db.session.commit()
     self.assertEqual(MentorshipRelationState.ACCEPTED,
                      mentorship_relation_current.state)  # current
     self.assertEqual(MentorshipRelationState.PENDING,
                      self.mentorship_relation.state)  # new
     with self.client:
         response = self.client.put(
             f"/mentorship_relation/{self.mentorship_relation.id}/accept",
             headers=get_test_request_header(self.second_user.id),
         )
         self.assertEqual(403, response.status_code)
         self.assertEqual(MentorshipRelationState.ACCEPTED,
                          mentorship_relation_current.state)  # current
         self.assertEqual(MentorshipRelationState.PENDING,
                          self.mentorship_relation.state)  # new
         self.assertDictEqual(
             messages.USER_IS_INVOLVED_IN_A_MENTORSHIP_RELATION,
             json.loads(response.data),
         )
    def test_accepted_requests_auth(self):
        start_date = datetime.now()
        end_date = start_date + timedelta(weeks=4)
        start_date = start_date.timestamp()
        end_date = end_date.timestamp()
        tasks_list = TasksListModel()

        mentorship_relation = MentorshipRelationModel(
            action_user_id=self.user2.id,
            mentor_user=self.user1,
            mentee_user=self.user2,
            creation_date=start_date,
            end_date=end_date,
            state=MentorshipRelationState.ACCEPTED,
            notes="",
            tasks_list=tasks_list,
        )

        db.session.add(mentorship_relation)
        db.session.commit()
        expected_response = {
            "name": "User1",
            "pending_requests": 0,
            "accepted_requests": 1,
            "rejected_requests": 0,
            "completed_relations": 0,
            "cancelled_relations": 0,
            "achievements": [],
        }
        auth_header = get_test_request_header(self.user1.id)
        actual_response = self.client.get(
            "/home", follow_redirects=True, headers=auth_header
        )
        self.assertEqual(200, actual_response.status_code)
        self.assertEqual(expected_response, json.loads(actual_response.data))
    def reject_request(user_id: int, request_id: int):
        """Rejects a mentorship request.

        Args:
            user_id: ID of the user rejecting the request.
            request_id: ID of the request to be rejected.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relation request is rejected, failure if otherwise.
        """

        user = UserModel.find_by_id(user_id)
        request = MentorshipRelationModel.find_by_id(request_id)

        # verify if request exists
        if request is None:
            return messages.MENTORSHIP_RELATION_REQUEST_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # verify if request is in pending state
        if request.state != MentorshipRelationState.PENDING:
            return messages.NOT_PENDING_STATE_RELATION, HTTPStatus.BAD_REQUEST

        # verify if I'm the receiver of the request
        if request.action_user_id == user_id:
            return messages.USER_CANT_REJECT_REQUEST_SENT_BY_USER, HTTPStatus.BAD_REQUEST

        # verify if I'm involved in this relation
        if not (request.mentee_id == user_id or request.mentor_id == user_id):
            return messages.CANT_REJECT_UNINVOLVED_RELATION_REQUEST, HTTPStatus.BAD_REQUEST

        # All was checked
        request.state = MentorshipRelationState.REJECTED
        request.save_to_db()

        return messages.MENTORSHIP_RELATION_WAS_REJECTED_SUCCESSFULLY, HTTPStatus.OK
Beispiel #7
0
    def list_tasks(user_id: int, mentorship_relation_id: int):
        """Retrieves all tasks of a user in a mentorship relation.

        Lists all tasks from a mentorship relation for the specified user if the user is involved in a current mentorship relation.

        Args:
            user_id: The id of the user.
            mentorship_relation_id: The id of the mentorship relation.

        Returns:
            A list containing all the tasks one user has in a mentorship relation. otherwise, it returns a two element list where the first element is
            a dictionary containing a key 'message' indicating in its value if there were any problem finding user's tasks in the specified
            mentorship relation as a string. The last element is the HTTP response code
        """

        user = UserModel.find_by_id(user_id)
        relation = MentorshipRelationModel.find_by_id(mentorship_relation_id)
        if relation is None:
            return messages.MENTORSHIP_RELATION_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        if not (user_id == relation.mentee_id or user_id == relation.mentor_id):
            return messages.USER_NOT_INVOLVED_IN_THIS_MENTOR_RELATION, HTTPStatus.UNAUTHORIZED

        all_tasks = relation.tasks_list.tasks

        return all_tasks
Beispiel #8
0
    def delete_task(user_id: int, mentorship_relation_id: int, task_id: int):
        """Deletes a specified task from a mentorship relation.

        Deletes a task that belongs to a user who is involved in the specified
        mentorship relation.

        Args:
            user_id: The id of the user.
            mentorship_relation_id: The id of the mentorship relation.
            task_id: The id of the task.

        Returns:
            A two element list where the first element is a dictionary containing a key 'message' indicating in its value if the
            task was deleted successfully or not as a string. The last element is the HTTP response code.
        """

        user = UserModel.find_by_id(user_id)
        relation = MentorshipRelationModel.find_by_id(mentorship_relation_id)
        if relation is None:
            return messages.MENTORSHIP_RELATION_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        task = relation.tasks_list.find_task_by_id(task_id)
        if task is None:
            return messages.TASK_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        if not (user_id == relation.mentee_id or user_id == relation.mentor_id):
            return messages.USER_NOT_INVOLVED_IN_THIS_MENTOR_RELATION, HTTPStatus.UNAUTHORIZED

        relation.tasks_list.delete_task(task_id)

        return messages.TASK_WAS_DELETED_SUCCESSFULLY, HTTPStatus.OK
Beispiel #9
0
    def create_task(user_id: int, mentorship_relation_id: int, data: Dict[str, str]):
        """Creates a new task.

        Creates a new task in a mentorship relation if the specified user is already involved in it.

        Args:
            user_id: The id of the user.
            mentorship_relation_id: The id of the mentorship relation.
            data: A list containing the description of the task.

        Returns:
            A two element list where the first element is a dictionary containing a key 'message' indicating
            in its value if the task creation was successful or not as a string. The last element is the HTTP
            response code.
        """

        description = data["description"]

        user = UserModel.find_by_id(user_id)
        relation = MentorshipRelationModel.find_by_id(_id=mentorship_relation_id)
        if relation is None:
            return messages.MENTORSHIP_RELATION_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        if relation.state != MentorshipRelationState.ACCEPTED:
            return messages.UNACCEPTED_STATE_RELATION, HTTPStatus.FORBIDDEN

        if (relation.mentor_id != user_id) and (relation.mentee_id != user_id):
            return messages.USER_NOT_INVOLVED_IN_THIS_MENTOR_RELATION, 403

        now_timestamp = datetime.now().timestamp()
        relation.tasks_list.add_task(description=description, created_at=now_timestamp)
        relation.tasks_list.save_to_db()

        return messages.TASK_WAS_CREATED_SUCCESSFULLY, HTTPStatus.CREATED
    def cancel_relation(user_id: int, relation_id: int):
        """Allows a given user to terminate a particular relationship.

        Args:
            user_id: ID of the user terminating the relationship.
            relation_id: ID of the relationship.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relation is terminated, failure if otherwise.
        """

        user = UserModel.find_by_id(user_id)
        request = MentorshipRelationModel.find_by_id(relation_id)

        # verify if request exists
        if request is None:
            return messages.MENTORSHIP_RELATION_REQUEST_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # verify if request is in pending state
        if request.state != MentorshipRelationState.ACCEPTED:
            return messages.UNACCEPTED_STATE_RELATION, HTTPStatus.BAD_REQUEST

        # verify if I'm involved in this relation
        if not (request.mentee_id == user_id or request.mentor_id == user_id):
            return messages.CANT_CANCEL_UNINVOLVED_REQUEST, HTTPStatus.BAD_REQUEST

        # All was checked
        request.state = MentorshipRelationState.CANCELLED
        request.save_to_db()

        return messages.MENTORSHIP_RELATION_WAS_CANCELLED_SUCCESSFULLY, HTTPStatus.OK
    def test_dao_create_mentorship_relation_with_mentor_already_in_relation(self):

        self.mentorship_relation = MentorshipRelationModel(
            action_user_id=self.admin_user.id,
            mentor_user=self.admin_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.ACCEPTED,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        db.session.add(self.mentorship_relation)
        db.session.commit()

        dao = MentorshipRelationDAO()
        data = dict(
            mentor_id=self.second_user.id,
            mentee_id=self.first_user.id,
            end_date=self.end_date_example.timestamp(),
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        # Use DAO to create a mentorship relation

        result = dao.create_mentorship_relation(self.second_user.id, data)

        self.assertEqual((messages.MENTOR_ALREADY_IN_A_RELATION, 400), result)

        query_mentorship_relations = MentorshipRelationModel.query.all()

        self.assertTrue(1, len(query_mentorship_relations))
    def accept_request(user_id: int, request_id: int):
        """Allows a mentorship request.

        Args:
            user_id: ID of the user accepting the request.
            request_id: ID of the request to be accepted.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relation request is accepted, failure if otherwise.
        """

        user = UserModel.find_by_id(user_id)
        request = MentorshipRelationModel.find_by_id(request_id)

        # verify if request exists
        if request is None:
            return messages.MENTORSHIP_RELATION_REQUEST_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # verify if request is in pending state
        if request.state != MentorshipRelationState.PENDING:
            return messages.NOT_PENDING_STATE_RELATION, HTTPStatus.BAD_REQUEST

        # verify if I'm the receiver of the request
        if request.action_user_id == user_id:
            return messages.CANT_ACCEPT_MENTOR_REQ_SENT_BY_USER, HTTPStatus.BAD_REQUEST

        # verify if I'm involved in this relation
        if not (request.mentee_id == user_id or request.mentor_id == user_id):
            return messages.CANT_ACCEPT_UNINVOLVED_MENTOR_RELATION, HTTPStatus.BAD_REQUEST

        my_requests = user.mentee_relations + user.mentor_relations

        # verify if I'm on a current relation
        for my_request in my_requests:
            if my_request.state == MentorshipRelationState.ACCEPTED:
                return messages.USER_IS_INVOLVED_IN_A_MENTORSHIP_RELATION, HTTPStatus.BAD_REQUEST

        mentee = request.mentee
        mentor = request.mentor

        # If I am mentor : Check if the mentee isn't in any other relation already
        if user_id == mentor.id:
            mentee_requests = mentee.mentee_relations + mentee.mentor_relations

            for mentee_request in mentee_requests:
                if mentee_request.state == MentorshipRelationState.ACCEPTED:
                    return messages.MENTEE_ALREADY_IN_A_RELATION, HTTPStatus.BAD_REQUEST
        # If I am mentee : Check if the mentor isn't in any other relation already
        else:
            mentor_requests = mentor.mentee_relations + mentor.mentor_relations

            for mentor_request in mentor_requests:
                if mentor_request.state == MentorshipRelationState.ACCEPTED:
                    return messages.MENTOR_ALREADY_IN_A_RELATION, HTTPStatus.BAD_REQUEST

        # All was checked
        request.state = MentorshipRelationState.ACCEPTED
        request.save_to_db()

        return messages.MENTORSHIP_RELATION_WAS_ACCEPTED_SUCCESSFULLY, HTTPStatus.OK
Beispiel #13
0
    def setUp(self):
        super(TestMentorshipRelationAcceptRequestDAO, self).setUp()

        self.notes_example = "description of a good mentorship relation"
        self.now_datetime = datetime.now()
        self.end_date_example = self.now_datetime + timedelta(weeks=5)

        # create new mentorship relation

        self.mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        self.mentorship_relation2 = MentorshipRelationModel(
            action_user_id=self.third_user.id,
            mentor_user=self.first_user,
            mentee_user=self.third_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        self.mentorship_relation3 = MentorshipRelationModel(
            action_user_id=self.second_user.id,
            mentor_user=self.third_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        db.session.add(self.mentorship_relation)
        db.session.add(self.mentorship_relation2)
        db.session.add(self.mentorship_relation3)
        db.session.commit()
Beispiel #14
0
    def setUp(self):
        db.create_all()

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.second_user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )

        self.notes_example = "description of a good mentorship relation"

        now_datetime = datetime.now()
        self.start_date_example = datetime(year=now_datetime.year + 1,
                                           month=3,
                                           day=1).timestamp()
        self.end_date_example = datetime(year=now_datetime.year + 1,
                                         month=5,
                                         day=1).timestamp()
        self.now_datetime = datetime.now().timestamp()

        db.session.add(self.first_user)
        db.session.add(self.second_user)
        db.session.commit()

        self.mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime,
            end_date=self.end_date_example,
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )
        db.session.add(self.mentorship_relation)
        db.session.commit()
Beispiel #15
0
    def test_get_achievements(self):
        dao = UserDAO()

        mentor = UserModel("Test mentor", "test_mentor", "test_password",
                           "*****@*****.**", True)

        mentee = UserModel("Test mentee", "test_mentee", "test_password",
                           "*****@*****.**", True)

        mentor.is_email_verified = True
        mentor.available_to_mentor = True
        mentee.is_email_verified = True
        mentee.need_mentoring = True

        db.session.add(mentor)
        db.session.add(mentee)
        db.session.commit()

        start_date = datetime.datetime.now()
        end_date = start_date + datetime.timedelta(weeks=4)

        tasks_list = TasksListModel()
        tasks_list.add_task(
            description="Test Task",
            created_at=start_date.timestamp(),
            is_done=True,
            completed_at=end_date.timestamp(),
        )
        tasks_list.add_task(
            description="Test Task 2",
            created_at=start_date.timestamp(),
            is_done=True,
            completed_at=end_date.timestamp(),
        )

        relation = MentorshipRelationModel(
            action_user_id=mentee.id,
            mentor_user=mentor,
            mentee_user=mentee,
            creation_date=start_date.timestamp(),
            end_date=end_date.timestamp(),
            state=MentorshipRelationState.ACCEPTED,
            tasks_list=tasks_list,
            notes="Test Notes",
        )

        db.session.add(tasks_list)
        db.session.add(relation)
        db.session.commit()

        achievements = dao.get_achievements(mentee.id)

        self.assertEqual(2, len(achievements))

        for achievement in achievements:
            self.assertTrue(achievement.get("is_done"))
Beispiel #16
0
 def create_relationship(self):
     """Creates relationship between verified and other user."""
     relation = MentorshipRelationModel(
         self.other_user.id,
         self.other_user,
         self.verified_user,
         datetime.now().timestamp(),
         (datetime.now() + timedelta(weeks=5)).timestamp(),
         MentorshipRelationState.ACCEPTED,
         "notes",
         TasksListModel(),
     )
     db.session.add(relation)
     db.session.commit()
    def setUp(self):
        super(TestMentorshipRelationDeleteDAO, self).setUp()

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.second_user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )

        # making sure both are available to be mentor or mentee
        self.first_user.need_mentoring = True
        self.first_user.available_to_mentor = True
        self.first_user.is_email_verified = True
        self.second_user.need_mentoring = True
        self.second_user.available_to_mentor = True
        self.second_user.is_email_verified = True

        self.notes_example = "description of a good mentorship relation"

        self.now_datetime = datetime.now()
        self.end_date_example = self.now_datetime + timedelta(weeks=5)

        db.session.add(self.first_user)
        db.session.add(self.second_user)
        db.session.commit()

        # create new mentorship relation

        self.mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        db.session.add(self.mentorship_relation)
        db.session.commit()
def validate_data_for_task_comment(user_id, task_id, relation_id):
    relation = MentorshipRelationModel.find_by_id(relation_id)
    if relation is None:
        return messages.MENTORSHIP_RELATION_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

    if user_id != relation.mentor_id and user_id != relation.mentee_id:
        return messages.USER_NOT_INVOLVED_IN_THIS_MENTOR_RELATION, HTTPStatus.UNAUTHORIZED

    if relation.state != MentorshipRelationState.ACCEPTED:
        return messages.UNACCEPTED_STATE_RELATION, HTTPStatus.BAD_REQUEST

    task = relation.tasks_list.find_task_by_id(task_id)
    if task is None:
        return messages.TASK_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

    return {}
Beispiel #19
0
    def complete_task(user_id: int, mentorship_relation_id: int, task_id: int):
        """Marks a task as completed.

        Updates the task that belongs to a user who is involved in the specified
        mentorship relation to finished task status.

        Args:
            user_id: The id of the user.
            mentorship_relation_id: The id of the mentorship relation.
            task_id: The id of the task.

        Returns:
            A two element list where the first element is a dictionary containing a key 'message' indicating in its value
            if the task was set to complete successfully or not as a string. The last element is the HTTP response code.
        """

        user = UserModel.find_by_id(user_id)
        relation = MentorshipRelationModel.find_by_id(mentorship_relation_id)
        if relation is None:
            return messages.MENTORSHIP_RELATION_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        if not (user_id == relation.mentee_id
                or user_id == relation.mentor_id):
            return messages.USER_NOT_INVOLVED_IN_THIS_MENTOR_RELATION, HTTPStatus.UNAUTHORIZED

        task = relation.tasks_list.find_task_by_id(task_id)
        if task is None:
            return messages.TASK_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        if task.get("is_done"):
            return messages.TASK_WAS_ALREADY_ACHIEVED, HTTPStatus.BAD_REQUEST
        else:
            relation.tasks_list.update_task(
                task_id=task_id,
                is_done=True,
                completed_at=datetime.now().timestamp())

        return messages.TASK_WAS_ACHIEVED_SUCCESSFULLY, HTTPStatus.OK
Beispiel #20
0
def send_email_mentorship_relation_accepted(request_id):
    """
    Sends a notification email to the sender of the mentorship relation request,
    stating that his request has been accepted.

    Args:
        request_id: Request id of the mentorship request.
    """

    from app.database.models.user import UserModel
    from app.database.models.mentorship_relation import MentorshipRelationModel

    # Getting the request from id.
    request = MentorshipRelationModel.find_by_id(request_id)

    # Getting the sender and receiver of the mentorship request from their ids.
    if request.action_user_id == request.mentor_id:
        request_sender = UserModel.find_by_id(request.mentor_id)
        request_receiver = UserModel.find_by_id(request.mentee_id)
        role = "mentee"
    else:
        request_sender = UserModel.find_by_id(request.mentee_id)
        request_receiver = UserModel.find_by_id(request.mentor_id)
        role = "mentor"

    end_date = request.end_date
    date = datetime.datetime.fromtimestamp(end_date).strftime("%d-%m-%Y")

    subject = "Mentorship relation accepted!"
    html = render_template(
        "mentorship_relation_accepted.html",
        request_sender=request_sender.name,
        request_receiver=request_receiver.name,
        role=role,
        end_date=date,
    )
    send_email(request_sender.email, subject, html)
Beispiel #21
0
 def test_find_mentorship_relation_by_id(self):
     query_mentorship_relation = MentorshipRelationModel.query.first()
     find_by_id_result = MentorshipRelationModel.find_by_id(
         query_mentorship_relation.id)
     self.assertEqual(query_mentorship_relation, find_by_id_result)
    def setUp(self):
        super(TestUserDao, self).setUp()

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.second_user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )

        # making sure both are available to be mentor or mentee
        self.first_user.need_mentoring = True
        self.first_user.available_to_mentor = True
        self.first_user.is_email_verified = True
        self.second_user.need_mentoring = True
        self.second_user.available_to_mentor = True
        self.second_user.is_email_verified = True

        self.notes_example = "description of a good mentorship relation"

        self.now_datetime = datetime.now()
        self.end_date_example = self.now_datetime + timedelta(weeks=5)

        self.tasks_list_1 = TasksListModel()
        self.tasks_list_2 = TasksListModel()
        self.tasks_list_3 = TasksListModel()

        db.session.add(self.tasks_list_1)
        db.session.add(self.tasks_list_2)
        db.session.add(self.tasks_list_3)
        db.session.add(self.first_user)
        db.session.add(self.second_user)
        db.session.commit()

        # create new mentorship relation
        self.mentorship_relation1 = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.ACCEPTED,
            notes=self.notes_example,
            tasks_list=self.tasks_list_1,
        )

        self.mentorship_relation2 = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=self.tasks_list_2,
        )

        self.mentorship_relation3 = MentorshipRelationModel(
            action_user_id=self.second_user.id,
            mentor_user=self.second_user,
            mentee_user=self.first_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.CANCELLED,
            notes=self.notes_example,
            tasks_list=self.tasks_list_3,
        )

        db.session.add(self.mentorship_relation1)
        db.session.add(self.mentorship_relation3)
        db.session.add(self.mentorship_relation2)
        db.session.commit()

        self.description_example = "This is an example of a description"

        self.tasks_list_1.add_task(
            description=self.description_example,
            created_at=self.now_datetime.timestamp(),
        )
        self.tasks_list_1.add_task(
            description=self.description_example,
            created_at=self.now_datetime.timestamp(),
            is_done=True,
            completed_at=self.end_date_example.timestamp(),
        )
        self.tasks_list_2.add_task(
            description=self.description_example,
            created_at=self.now_datetime.timestamp(),
        )

        db.session.add(self.tasks_list_1)
        db.session.add(self.tasks_list_2)
        db.session.commit()

        self.test_description = "testing this description"
        self.test_is_done = False
Beispiel #23
0
 def test_empty_table(self):
     self.assertFalse(MentorshipRelationModel.is_empty())
     db.session.delete(self.mentorship_relation)
     db.session.commit()
     self.assertTrue(MentorshipRelationModel.is_empty())
Beispiel #24
0
class TestMentorshipRelationModel(BaseTestCase):

    # Setup consists of adding 2 users into the database
    def setUp(self):
        db.create_all()

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.second_user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )

        self.notes_example = "description of a good mentorship relation"

        now_datetime = datetime.now()
        self.start_date_example = datetime(year=now_datetime.year + 1,
                                           month=3,
                                           day=1).timestamp()
        self.end_date_example = datetime(year=now_datetime.year + 1,
                                         month=5,
                                         day=1).timestamp()
        self.now_datetime = datetime.now().timestamp()

        db.session.add(self.first_user)
        db.session.add(self.second_user)
        db.session.commit()

        self.mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime,
            end_date=self.end_date_example,
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )
        db.session.add(self.mentorship_relation)
        db.session.commit()

    def test_mentorship_relation_creation(self):
        query_mentorship_relation = MentorshipRelationModel.query.first()

        self.assertTrue(query_mentorship_relation is not None)

        self.assertEqual(1, query_mentorship_relation.id)

        # asserting relation extra fields
        self.assertEqual(self.first_user.id,
                         query_mentorship_relation.action_user_id)
        self.assertEqual(self.now_datetime,
                         query_mentorship_relation.creation_date)
        self.assertIsNone(query_mentorship_relation.accept_date)
        self.assertIsNone(query_mentorship_relation.start_date)
        self.assertEqual(self.end_date_example,
                         query_mentorship_relation.end_date)
        self.assertEqual(self.notes_example, query_mentorship_relation.notes)
        self.assertEqual(MentorshipRelationState.PENDING,
                         query_mentorship_relation.state)

        # asserting mentor and mentees setup
        self.assertEqual(self.first_user.id,
                         query_mentorship_relation.mentor_id)
        self.assertEqual(self.second_user.id,
                         query_mentorship_relation.mentee_id)

        # assert mentors' mentor_relations and mentee_relations
        self.assertEqual(1, len(self.first_user.mentor_relations))
        self.assertEqual(query_mentorship_relation,
                         self.first_user.mentor_relations[0])
        self.assertEqual([], self.first_user.mentee_relations)

        # assert mentees' mentor_relations and mentee_relations
        self.assertEqual(1, len(self.second_user.mentee_relations))
        self.assertEqual(query_mentorship_relation,
                         self.second_user.mentee_relations[0])
        self.assertEqual([], self.second_user.mentor_relations)

    def test_mentorship_relation_json_representation(self):
        expected_json = {
            "id": 1,
            "action_user_id": self.first_user.id,
            "mentor_id": self.first_user.id,
            "mentee_id": self.second_user.id,
            "creation_date": self.now_datetime,
            "accept_date": None,
            "start_date": None,
            "end_date": self.end_date_example,
            "state": MentorshipRelationState.PENDING,
            "notes": self.notes_example,
        }
        self.assertEqual(expected_json, self.mentorship_relation.json())

    def test_mentorship_relation_update(self):
        new_notes = "This contract notes are different..."
        self.mentorship_relation.notes = new_notes

        db.session.add(self.mentorship_relation)
        db.session.commit()

        self.assertEqual(self.mentorship_relation.notes, new_notes)

        # assert mentors' mentor_relations and mentee_relations
        self.assertEqual(1, len(self.first_user.mentor_relations))
        self.assertEqual(new_notes, self.first_user.mentor_relations[0].notes)
        self.assertEqual([], self.first_user.mentee_relations)

        # assert mentees' mentor_relations and mentee_relations
        self.assertEqual(1, len(self.second_user.mentee_relations))
        self.assertEqual(new_notes, self.second_user.mentee_relations[0].notes)
        self.assertEqual([], self.second_user.mentor_relations)

    def test_find_mentorship_relation_by_id(self):
        query_mentorship_relation = MentorshipRelationModel.query.first()
        find_by_id_result = MentorshipRelationModel.find_by_id(
            query_mentorship_relation.id)
        self.assertEqual(query_mentorship_relation, find_by_id_result)

    def test_empty_table(self):
        self.assertFalse(MentorshipRelationModel.is_empty())
        db.session.delete(self.mentorship_relation)
        db.session.commit()
        self.assertTrue(MentorshipRelationModel.is_empty())
    def test_achievements(self):
        start_date = datetime.now()
        end_date = start_date + timedelta(weeks=4)
        start_date = start_date.timestamp()
        end_date = end_date.timestamp()

        tasks_list = TasksListModel()
        task_created_time = datetime.now().timestamp()
        task_completed_time = task_created_time + 100
        tasks_list.add_task(
            description="Test task",
            created_at=task_created_time,
            is_done=True,
            completed_at=task_completed_time,
        )
        tasks_list.add_task(
            description="Incomplete task: Should not appear in achievements",
            created_at=task_created_time,
            is_done=False,
            completed_at=task_completed_time,
        )

        db.session.add(tasks_list)
        db.session.commit()

        mentorship_relation = MentorshipRelationModel(
            action_user_id=self.user2.id,
            mentor_user=self.user1,
            mentee_user=self.user2,
            creation_date=start_date,
            end_date=end_date,
            state=MentorshipRelationState.ACCEPTED,
            notes="",
            tasks_list=tasks_list,
        )

        db.session.add(mentorship_relation)
        db.session.commit()

        expected_response = {
            "name": "User1",
            "pending_requests": 0,
            "accepted_requests": 1,
            "rejected_requests": 0,
            "completed_relations": 0,
            "cancelled_relations": 0,
            "achievements": [
                {
                    "completed_at": task_completed_time,
                    "created_at": task_created_time,
                    "description": "Test task",
                    "id": 1,  # This is the only task in the list
                    "is_done": True,
                }
            ],
        }
        auth_header = get_test_request_header(self.user1.id)
        actual_response = self.client.get(
            "/home", follow_redirects=True, headers=auth_header
        )
        self.assertEqual(200, actual_response.status_code)
        self.assertEqual(expected_response, json.loads(actual_response.data))
    def create_mentorship_relation(self, user_id: int, data: Dict[str, str]):
        """Creates a relationship between two users.

        Establishes the mentor-mentee relationship.

        Args:
            user_id: ID of the user initiating this request. Has to be either the mentor or the mentee.
            data: List containing the mentor_id, mentee_id, end_date_timestamp and notes.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relationship is established, failure if otherwise.
        """
        action_user_id = user_id
        mentor_id = data["mentor_id"]
        mentee_id = data["mentee_id"]
        end_date_timestamp = data["end_date"]
        notes = data["notes"]

        # user_id has to match either mentee_id or mentor_id
        is_valid_user_ids = action_user_id == mentor_id or action_user_id == mentee_id
        if not is_valid_user_ids:
            return messages.MATCH_EITHER_MENTOR_OR_MENTEE, HTTPStatus.BAD_REQUEST

        # mentor_id has to be different from mentee_id
        if mentor_id == mentee_id:
            return messages.MENTOR_ID_SAME_AS_MENTEE_ID, HTTPStatus.BAD_REQUEST

        try:
            end_date_datetime = datetime.fromtimestamp(end_date_timestamp)
        except ValueError:
            return messages.INVALID_END_DATE, HTTPStatus.BAD_REQUEST

        now_datetime = datetime.now()
        if end_date_datetime < now_datetime:
            return messages.END_TIME_BEFORE_PRESENT, HTTPStatus.BAD_REQUEST

        # business logic constraints

        max_relation_duration = end_date_datetime - now_datetime
        if max_relation_duration > self.MAXIMUM_MENTORSHIP_DURATION:
            return messages.MENTOR_TIME_GREATER_THAN_MAX_TIME, HTTPStatus.BAD_REQUEST

        if max_relation_duration < self.MINIMUM_MENTORSHIP_DURATION:
            return messages.MENTOR_TIME_LESS_THAN_MIN_TIME, HTTPStatus.BAD_REQUEST

        # validate if mentor user exists
        mentor_user = UserModel.find_by_id(mentor_id)
        if mentor_user is None:
            return messages.MENTOR_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # validate if mentor is available to mentor
        if not mentor_user.available_to_mentor:
            return messages.MENTOR_NOT_AVAILABLE_TO_MENTOR, HTTPStatus.BAD_REQUEST

        # validate if mentee user exists
        mentee_user = UserModel.find_by_id(mentee_id)
        if mentee_user is None:
            return messages.MENTEE_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # validate if mentee is wants to be mentored
        if not mentee_user.need_mentoring:
            return messages.MENTEE_NOT_AVAIL_TO_BE_MENTORED, HTTPStatus.BAD_REQUEST

        # TODO add tests for this portion

        all_mentor_relations = (
            mentor_user.mentor_relations + mentor_user.mentee_relations
        )
        for relation in all_mentor_relations:
            if relation.state == MentorshipRelationState.ACCEPTED:
                return messages.MENTOR_ALREADY_IN_A_RELATION, HTTPStatus.BAD_REQUEST

        all_mentee_relations = (
            mentee_user.mentor_relations + mentee_user.mentee_relations
        )
        for relation in all_mentee_relations:
            if relation.state == MentorshipRelationState.ACCEPTED:
                return messages.MENTEE_ALREADY_IN_A_RELATION, HTTPStatus.BAD_REQUEST

        # All validations were checked

        tasks_list = TasksListModel()
        tasks_list.save_to_db()

        mentorship_relation = MentorshipRelationModel(
            action_user_id=action_user_id,
            mentor_user=mentor_user,
            mentee_user=mentee_user,
            creation_date=datetime.now().timestamp(),
            end_date=end_date_timestamp,
            state=MentorshipRelationState.PENDING,
            notes=notes,
            tasks_list=tasks_list,
        )

        mentorship_relation.save_to_db()

        return messages.MENTORSHIP_RELATION_WAS_SENT_SUCCESSFULLY, HTTPStatus.OK
Beispiel #27
0
    def test_get_user_statistics(self):
        dao = UserDAO()

        mentor = UserModel("Test mentor", "test_mentor", "__test__",
                           "*****@*****.**", True)

        mentee = UserModel("Test mentee", "test_mentee", "__test__",
                           "*****@*****.**", True)

        mentor.is_email_verified = True
        mentor.available_to_mentor = True
        mentee.is_email_verified = True
        mentee.need_mentoring = True

        db.session.add(mentor)
        db.session.add(mentee)
        db.session.commit()

        start_date = datetime.datetime.now()
        end_date = start_date + datetime.timedelta(weeks=4)

        tasks_list = TasksListModel()

        pending_relation = MentorshipRelationModel(
            action_user_id=mentee.id,
            mentor_user=mentor,
            mentee_user=mentee,
            creation_date=start_date.timestamp(),
            end_date=end_date.timestamp(),
            state=MentorshipRelationState.PENDING,
            tasks_list=tasks_list,
            notes="Test Notes",
        )

        db.session.add(tasks_list)
        db.session.add(pending_relation)
        db.session.commit()

        # We first test pending relations
        expected_response = {
            "name": mentor.name,
            "pending_requests": 1,
            "accepted_requests": 0,
            "rejected_requests": 0,
            "completed_relations": 0,
            "cancelled_relations": 0,
            "achievements": [],
        }

        actual_response = dao.get_user_statistics(mentor.id)
        self.assertEqual(expected_response, actual_response)

        # We now test accepted relations
        pending_relation.state = MentorshipRelationState.ACCEPTED
        expected_response["pending_requests"] = 0
        expected_response["accepted_requests"] = 1

        actual_response = dao.get_user_statistics(mentor.id)
        self.assertEqual(expected_response, actual_response)

        # We now test completed relations
        pending_relation.state = MentorshipRelationState.COMPLETED
        expected_response["accepted_requests"] = 0
        expected_response["completed_relations"] = 1

        actual_response = dao.get_user_statistics(mentor.id)
        self.assertEqual(expected_response, actual_response)

        # We now test rejected relations
        pending_relation.state = MentorshipRelationState.REJECTED
        expected_response["completed_relations"] = 0
        expected_response["rejected_requests"] = 1

        actual_response = dao.get_user_statistics(mentor.id)
        self.assertEqual(expected_response, actual_response)

        # We now test cancelled relations
        pending_relation.state = MentorshipRelationState.CANCELLED
        expected_response["rejected_requests"] = 0
        expected_response["cancelled_relations"] = 1

        actual_response = dao.get_user_statistics(mentor.id)
        self.assertEqual(expected_response, actual_response)

        # We now test achievements
        pending_relation.state = MentorshipRelationState.ACCEPTED
        tasks_list.add_task(
            description="Test Task",
            created_at=start_date.timestamp(),
            is_done=True,
            completed_at=end_date.timestamp(),
        )
        tasks_list.add_task(
            description="Test Task 2",
            created_at=start_date.timestamp(),
            is_done=True,
            completed_at=end_date.timestamp(),
        )

        expected_response["cancelled_relations"] = 0
        expected_response["accepted_requests"] = 1
        expected_response["achievements"] = [
            {
                "completed_at": end_date.timestamp(),
                "created_at": start_date.timestamp(),
                "description": "Test Task",
                "id": 1,  # This is the first task in the list
                "is_done": True,
            },
            {
                "completed_at": end_date.timestamp(),
                "created_at": start_date.timestamp(),
                "description": "Test Task 2",
                "id": 2,  # This is the second task in the list
                "is_done": True,
            },
        ]
        actual_response = dao.get_user_statistics(mentor.id)
        self.assertEqual(expected_response, actual_response)