system_add_logic.go 2.5 KB
package department

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/contextdata"
	"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 SystemAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *SystemAddLogic) SystemAdd(req *types.DepartmentAddRequest) (resp *types.DepartmentGetResponse, err error) {
	var userToken = contextdata.GetUserTokenFromCtx(l.ctx)
	var conn = l.svcCtx.DefaultDBConn()

	total, _, err := l.svcCtx.DepartmentRepository.Find(l.ctx, conn, domain.NewQueryOptions().
		WithCountOnly().
		WithKV("companyId", userToken.CompanyId).
		WithKV("name", req.Name))
	if err != nil {
		return nil, err
	}
	if total > 0 {
		return nil, xerr.NewErrMsg("该分组名称已存在(不能重复)")
	}

	insert := &domain.Department{
		ParentId:  0,
		CompanyId: userToken.CompanyId,
		Name:      req.Name,
	}
	err = transaction.UseTrans(l.ctx, conn.DB(), func(ctx context.Context, conn transaction.Conn) error {
		_, err = l.svcCtx.DepartmentRepository.Insert(l.ctx, conn, insert)
		if err != nil {
			return err
		}

		// 用户添加到分组下
		if len(req.Ids) > 0 {
			_, users, err := l.svcCtx.UserRepository.Find(l.ctx, conn, domain.NewQueryOptions().
				WithOffsetLimit(1, len(req.Ids)).WithFindOnly().
				WithKV("ids", req.Ids).
				WithKV("companyId", userToken.CompanyId))
			if err != nil {
				return err
			}
			for i := range users {
				user := users[i]
				user.Departments = append(user.Departments, insert.Id)
				_, err := l.svcCtx.UserRepository.UpdateWithVersion(l.ctx, conn, user)
				if err != nil {
					return err
				}
			}
		}
		return nil
	}, true)
	if err != nil {
		return nil, xerr.NewErrMsgErr("新增分组失败", err)
	}

	resp = &types.DepartmentGetResponse{
		Department: types.Department{
			Id:        insert.Id,
			CompanyId: insert.CompanyId,
			ParentId:  insert.ParentId,
			Name:      insert.Name,
		},
	}
	return resp, nil
}