Ejemplo n.º 1
0
        public async Task <bool> AssignUsersToRoleAsync(RoleAssignInputModel roleAssignModel)
        {
            TEAM team      = _teamRepository.GetTeamById(roleAssignModel.TeamId);
            ROLE role      = _roleRepository.GetRoleById(roleAssignModel.RoleId);
            bool canDelete = false;

            if (team != null && role != null)
            {
                canDelete = true;

                List <USER_TEAM_ROLES> usersToRemove = new List <USER_TEAM_ROLES>();
                if (roleAssignModel.IdsToRemove != null)
                {
                    foreach (string idToRemove in roleAssignModel.IdsToRemove)
                    {
                        USER user = await _userRepository.GetUserById(idToRemove);

                        if (user != null && _teamRepository.IsTeamMember(user, team.ID))
                        {
                            usersToRemove.Add(user.USER_TEAM_ROLEs.FirstOrDefault(x => x.ROLE == role && x.TEAM == team));
                        }
                    }
                }

                List <USER_TEAM_ROLES> usersToAdd = new List <USER_TEAM_ROLES>();
                if (roleAssignModel.IdsToAdd != null)
                {
                    foreach (string idToAdd in roleAssignModel.IdsToAdd)
                    {
                        USER user = await _userRepository.GetUserById(idToAdd);

                        if (user != null && _teamRepository.IsTeamMember(user, team.ID))
                        {
                            usersToAdd.Add(new USER_TEAM_ROLES {
                                ROLE = role, TEAM = team, USER = user
                            });
                        }
                    }
                }

                if (role.IS_REQUIRED && usersToAdd.Count <= 0)
                {
                    var userRoleCount = _roleRepository.GetUsersByTeamRole(role, team).Count();
                    canDelete = usersToRemove.Count < userRoleCount;
                }

                if (canDelete)
                {
                    _roleRepository.AddAndDeleteUserTeamRoles(usersToAdd, usersToRemove);
                }
            }

            return(canDelete);
        }