Example #1
0
    def assert_validate_members(team_dto: TeamDTO):
        """ Validates that the users exist"""
        if len(team_dto.members) == 0:
            raise TeamServiceError("Must have at least one member")

            members = []
            managers = 0
            for member in team_dto.members:
                try:
                    UserService.get_user_by_username(member["name"])
                except NotFound:
                    raise NotFound(f'User {member["name"]} does not exist')
                if member["function"] == TeamMemberFunctions.MANAGER.name:
                    managers += 1

                members.append(member)

            if managers == 0:
                raise TeamServiceError(
                    "Must have at least one manager in team")

            team_dto.members = members
Example #2
0
    def update(self, team_dto: TeamDTO):
        """ Updates Team from DTO """
        if team_dto.organisation:
            self.organisation = Organisation().get_organisation_by_name(
                team_dto.organisation)

        for attr, value in team_dto.items():
            if attr == "visibility" and value is not None:
                value = TeamVisibility[team_dto.visibility].value

            if attr in ("members", "organisation"):
                continue

            try:
                is_field_nullable = self.__table__.columns[attr].nullable
                if is_field_nullable and value is not None:
                    setattr(self, attr, value)
                elif value is not None:
                    setattr(self, attr, value)
            except KeyError:
                continue

        if team_dto.members != self._get_team_members() and team_dto.members:
            for member in self.members:
                db.session.delete(member)

            for member in team_dto.members:
                user = User.get_by_username(member["userName"])

                if user is None:
                    raise NotFound("User not found")

                new_team_member = TeamMembers()
                new_team_member.team = self
                new_team_member.member = user
                new_team_member.function = TeamMemberFunctions[
                    member["function"]].value

        db.session.commit()
Example #3
0
    def get_all_teams(
        user_id: int = None,
        team_name_filter: str = None,
        team_role_filter: str = None,
        member_filter: int = None,
        member_request_filter: int = None,
        manager_filter: int = None,
        organisation_filter: int = None,
        omit_members: bool = False,
    ) -> TeamsListDTO:

        query = db.session.query(Team)

        orgs_query = None
        is_admin = UserService.is_user_an_admin(user_id)

        if organisation_filter:
            orgs_query = query.filter(
                Team.organisation_id == organisation_filter)

        if manager_filter and not (manager_filter == user_id and is_admin):
            manager_teams = query.filter(
                TeamMembers.user_id == manager_filter,
                TeamMembers.active == True,  # noqa
                TeamMembers.function == TeamMemberFunctions.MANAGER.value,
                Team.id == TeamMembers.team_id,
            )

            manager_orgs_teams = query.filter(
                Team.organisation_id.in_([
                    org.id for org in OrganisationService.get_organisations(
                        manager_filter)
                ]))

            query = manager_teams.union(manager_orgs_teams)

        if team_name_filter:
            query = query.filter(Team.name.ilike("%" + team_name_filter +
                                                 "%"), )

        if team_role_filter:
            try:
                role = TeamRoles[team_role_filter.upper()].value
                project_teams = (db.session.query(ProjectTeams).filter(
                    ProjectTeams.role == role).subquery())
                query = query.join(project_teams)
            except KeyError:
                pass

        if member_filter:
            team_member = (db.session.query(TeamMembers).filter(
                TeamMembers.user_id == member_filter,
                TeamMembers.active.is_(True)).subquery())
            query = query.join(team_member)

        if member_request_filter:
            team_member = (db.session.query(TeamMembers).filter(
                TeamMembers.user_id == member_request_filter,
                TeamMembers.active.is_(False),
            ).subquery())
            query = query.join(team_member)
        if orgs_query:
            query = query.union(orgs_query)

        teams_list_dto = TeamsListDTO()

        for team in query.all():
            team_dto = TeamDTO()
            team_dto.team_id = team.id
            team_dto.name = team.name
            team_dto.invite_only = team.invite_only
            team_dto.visibility = TeamVisibility(team.visibility).name
            team_dto.description = team.description
            team_dto.logo = team.organisation.logo
            team_dto.organisation = team.organisation.name
            team_dto.organisation_id = team.organisation.id
            team_dto.members = []
            is_team_member = TeamService.is_user_an_active_team_member(
                team.id, user_id)
            # Skip if members are not included
            if not omit_members:
                team_members = team.members

                team_dto.members = [
                    team.as_dto_team_member(member) for member in team_members
                ]

            if team_dto.visibility == "PRIVATE" and not is_admin:
                if is_team_member:
                    teams_list_dto.teams.append(team_dto)
            else:
                teams_list_dto.teams.append(team_dto)
        return teams_list_dto
    def post(self, team_id):
        """
        Updates a team information
        ---
        tags:
            - teams
        produces:
            - application/json
        parameters:
            - in: header
              name: Authorization
              description: Base64 encoded session token
              required: true
              type: string
              default: Token sessionTokenHere==
            - name: team_id
              in: path
              description: Unique team ID
              required: true
              type: integer
              default: 1
            - in: body
              name: body
              required: true
              description: JSON object for updating a team
              schema:
                properties:
                    name:
                        type: string
                        default: HOT - Mappers
                    logo:
                        type: string
                        default: https://tasks.hotosm.org/assets/img/hot-tm-logo.svg
                    members:
                        type: array
                        items:
                            schema:
                                $ref: "#/definitions/TeamMembers"
                    organisation:
                        type: string
                        default: HOT
                    description:
                        type: string
                        default: HOT's mapping editors
                    inviteOnly:
                        type: boolean
                        default: false
        responses:
            201:
                description: Team updated successfully
            400:
                description: Client Error - Invalid Request
            401:
                description: Unauthorized - Invalid credentials
            500:
                description: Internal Server Error
        """
        try:
            team_dto = TeamDTO(request.get_json())
            team_dto.team_id = team_id
            team_dto.validate()

            authenticated_user_id = token_auth.current_user()
            team_details_dto = TeamService.get_team_as_dto(
                team_id, authenticated_user_id)

            org = TeamService.assert_validate_organisation(
                team_dto.organisation_id)
            TeamService.assert_validate_members(team_details_dto)

            if not TeamService.is_user_team_manager(
                    team_id, authenticated_user_id
            ) and not OrganisationService.can_user_manage_organisation(
                    org.id, authenticated_user_id):
                return {
                    "Error": "User is not a admin or a manager for the team"
                }, 401
        except DataError as e:
            current_app.logger.error(f"error validating request: {str(e)}")
            return str(e), 400

        try:
            TeamService.update_team(team_dto)
            return {"Status": "Updated"}, 200
        except NotFound as e:
            return {"Error": str(e)}, 404
        except TeamServiceError as e:
            return str(e), 402
        except Exception as e:
            error_msg = f"Team POST - unhandled error: {str(e)}"
            current_app.logger.critical(error_msg)
            return {"Error": error_msg}, 500
Example #5
0
    def get_all_teams(
        user_id: int = None,
        team_name_filter: str = None,
        team_role_filter: str = None,
        member_filter: int = None,
        member_request_filter: int = None,
        manager_filter: int = None,
        organisation_filter: int = None,
    ) -> TeamsListDTO:

        query = db.session.query(Team).outerjoin(TeamMembers).outerjoin(
            ProjectTeams)

        orgs_query = None
        is_admin = UserService.is_user_an_admin(user_id)

        if organisation_filter:
            orgs_query = query.filter(
                Team.organisation_id.in_(organisation_filter))

        if manager_filter and not (manager_filter == user_id and is_admin):
            query = query.filter(
                TeamMembers.user_id == manager_filter,
                TeamMembers.active == True,  # noqa
                TeamMembers.function == TeamMemberFunctions.MANAGER.value,
            )

        if team_name_filter:
            query = query.filter(Team.name.contains(team_name_filter))

        if team_role_filter:
            try:
                role = TeamRoles[team_role_filter.upper()].value
                query = query.filter(ProjectTeams.role == role)
            except KeyError:
                pass

        if member_filter:
            query = query.filter(
                TeamMembers.user_id == member_filter,
                TeamMembers.active == True  # noqa
            )

        if member_request_filter:
            query = query.filter(
                TeamMembers.user_id == member_request_filter,
                TeamMembers.active == False,  # noqa
            )

        if orgs_query:
            query = query.union(orgs_query)

        teams_list_dto = TeamsListDTO()

        for team in query.all():
            team_dto = TeamDTO()
            team_dto.team_id = team.id
            team_dto.name = team.name
            team_dto.invite_only = team.invite_only
            team_dto.visibility = TeamVisibility(team.visibility).name
            team_dto.description = team.description
            team_dto.logo = team.organisation.logo
            team_dto.organisation = team.organisation.name
            team_dto.organisation_id = team.organisation.id
            team_dto.members = []
            team_members = TeamService._get_team_members(team.id)
            is_team_manager = False
            is_team_member = False
            for member in team_members:
                user = UserService.get_user_by_id(member.user_id)
                member_dto = TeamMembersDTO()
                member_dto.username = user.username
                member_dto.function = TeamMemberFunctions(member.function).name
                if member.user_id == user_id:
                    is_team_member = True
                    if member_dto.function == "MANAGER":
                        is_team_manager = True
                member_dto.picture_url = user.picture_url
                member_dto.active = member.active

                team_dto.members.append(member_dto)
            if team_dto.visibility == "PRIVATE" and not is_admin:
                if is_team_manager or is_team_member:
                    teams_list_dto.teams.append(team_dto)
            else:
                teams_list_dto.teams.append(team_dto)

        return teams_list_dto
Example #6
0
 def as_dto(self):
     """ Returns a dto for the team """
     team_dto = TeamDTO()
     team_dto.team_id = self.id
     team_dto.description = self.description
     team_dto.invite_only = self.invite_only
     team_dto.members = self._get_team_members()
     team_dto.name = self.name
     team_dto.organisation = self.organisation.name
     team_dto.organisation_id = self.organisation.id
     team_dto.logo = self.organisation.logo
     team_dto.visibility = TeamVisibility(self.visibility).name
     return team_dto