pg_batch_remove_role_service.go 2.1 KB
package domainService

import (
	"fmt"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/repository"
)

// PgCreateRoleService 传教角色服务
type PgBatchRemoveRoleService struct {
	transactionContext *pgTransaction.TransactionContext
}

// CreateRole  批量删除角色
//
// optUser 操作用户
// roleInfo 角色信息
func (ptr *PgBatchRemoveRoleService) BatchRemove(optUser *domain.OperateInfo, roleIds []int64) (interface{}, error) {

	roleRepository, _ := repository.NewRoleRepository(ptr.transactionContext)
	userRepository, _ := repository.NewUserRepository(ptr.transactionContext)

	for i := range roleIds {
		roleId := roleIds[i]
		role, err := roleRepository.FindOne(map[string]interface{}{"roleId": roleId})
		if err != nil {
			return nil, err
		}
		if role.RoleType == domain.RoleTypeAdmin {
			return nil, fmt.Errorf("主管理员角色不可删除")
		}
		if ok := role.IsRemoved(); !ok {
			continue
		}

		// 1.移除角色
		if _, err := roleRepository.Remove(role); err != nil {
			return nil, err
		}

		// 2.移除用户中有配置该角色的数据
		var offset, limit int = 0, repository.MaxRowLimit
		for {
			_, users, e := userRepository.Find(map[string]interface{}{"companyId": optUser.CompanyId, "roleId": roleId, "limit": limit, "offset": offset})
			for i := 0; i < len(users); i++ {
				if !users[i].RemoveUserRole(roleId) {
					continue
				}
				if _, err := userRepository.Save(users[i]); err != nil {
					return nil, err
				}
			}
			if len(users) == 0 || len(users) < repository.MaxRowLimit || e != nil {
				break
			}
			offset += limit
		}
	}

	return struct{}{}, nil
}

func NewPgBatchRemoveRoleService(transactionContext *pgTransaction.TransactionContext) (*PgBatchRemoveRoleService, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &PgBatchRemoveRoleService{
			transactionContext: transactionContext,
		}, nil
	}
}