system_delete_role_logic.go 2.2 KB
package role

import (
	"context"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/transaction"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"

	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SystemDeleteRoleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSystemDeleteRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemDeleteRoleLogic {
	return &SystemDeleteRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SystemDeleteRoleLogic) SystemDeleteRole(req *types.RoleDeleteRequest) (resp *types.RoleDeleteResponse, err error) {
	var (
		conn               = l.svcCtx.DefaultDBConn()
		role               *domain.Role
		userRemoveRoleList []*domain.User
		userRoles          []*domain.UserRole
	)
	if role, err = l.svcCtx.RoleRepository.FindOne(l.ctx, conn, req.Id); err != nil {
		return nil, xerr.NewErrMsgErr("角色不存在", err)
	}
	_, userRoles, _ = l.svcCtx.UserRoleRepository.Find(l.ctx, conn, domain.IndexCompanyId(role.CompanyId)().WithKV("roleId", role.Id).WithFindOnly())
	for _, item := range userRoles {
		var user *domain.User
		if user, err = l.svcCtx.UserRepository.FindOne(l.ctx, conn, item.UserId); err != nil {
			continue
		}
		userRemoveRoleList = append(userRemoveRoleList, user)
	}
	if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
		if role, err = l.svcCtx.RoleRepository.Delete(l.ctx, conn, role); err != nil {
			return err
		}
		for _, user := range userRemoveRoleList {
			user.RemoveRole(role.Id)
			if user, err = l.svcCtx.UserRepository.UpdateWithVersion(ctx, conn, user); err != nil {
				return err
			}
		}
		if err = l.svcCtx.UserRoleRepository.DeleteRole(l.ctx, conn, role.Id); err != nil {
			return err
		}
		return nil
	}, true); err != nil {
		return nil, xerr.NewErrMsgErr("删除角色失败", err)
	}

	resp = &types.RoleDeleteResponse{}
	return
}