pg_create_role_service.go 1.9 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 PgCreateRoleService struct {
	transactionContext *pgTransaction.TransactionContext
}

// CreateRole  创建角色
//
// optUser 操作用户
// roleInfo 角色信息
func (ptr *PgCreateRoleService) CreateRole(optUser *domain.CheckOptions, roleInfo *domain.Role) (*domain.Role, error) {
	if len(roleInfo.RoleName) == 0 {
		return nil, fmt.Errorf("角色名称不能为空")
	}
	if len(roleInfo.Desc) == 0 {
		return nil, fmt.Errorf("角色描述不能为空")
	}

	// 1.角色名称在当前企业及组织机构下进行唯一性校验
	var role *domain.Role
	var err error
	roleRepository, _ := repository.NewRoleRepository(ptr.transactionContext)
	if role, err = roleRepository.FindOne(map[string]interface{}{"companyId": roleInfo.CompanyId, "orgId": roleInfo.OrgId, "roleName": roleInfo.RoleName}); err == nil && role != nil {
		return nil, fmt.Errorf("该角色在当前组织机构已经存在")
	}

	// 2.企业管理员 需要配置所有菜单
	if roleInfo.RoleType == domain.RoleTypeAdmin {
		menuRepository, _ := repository.NewMenuRepository(ptr.transactionContext)
		_, menus, _ := menuRepository.Find(map[string]interface{}{"isPublish": 1})
		for i := range menus {
			roleInfo.AccessMenus = append(roleInfo.AccessMenus, menus[i].MenuId)
		}
	}

	if role, err = roleRepository.Save(roleInfo); err != nil {
		return nil, err
	}
	return role, nil
}

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