system_delete_logic.go 2.1 KB
package department

import (
	"context"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/types"
	"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"

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

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

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

func (l *SystemDeleteLogic) SystemDelete(req *types.DepartmentGetRequest) (resp *types.DepartmentGetResponse, err error) {
	var conn = l.svcCtx.DefaultDBConn()

	one, err := l.svcCtx.DepartmentRepository.FindOne(l.ctx, conn, req.Id)
	if err != nil {
		return nil, err
	}

	// 获取公司下的所有用户
	_, users, err := l.svcCtx.UserRepository.Find(l.ctx, conn, domain.NewQueryOptions().
		WithFindOnly().
		WithKV(" companyId", one.CompanyId))
	if err != nil {
		return nil, err
	}

	err = transaction.UseTrans(l.ctx, conn.DB(), func(ctx context.Context, conn transaction.Conn) error {
		_, err = l.svcCtx.DepartmentRepository.Delete(l.ctx, conn, one)
		if err != nil {
			return err
		}

		// 移除用户中关联的分组
		if len(users) > 0 {
			var findIndex = func(ids []int64, id int64) int {
				for i, _ := range ids {
					if ids[i] == id {
						return i
					}
				}
				return -1
			}
			for i := range users {
				user := users[i]
				var targetIndex = findIndex(user.Departments, req.Id)
				if targetIndex != -1 { // 归属分组存在,则移除
					user.Departments = append(user.Departments[:targetIndex], user.Departments[targetIndex+1:]...) // 移除分组ID
					_, err = l.svcCtx.UserRepository.UpdateWithVersion(l.ctx, conn, user)
					if err != nil {
						return err
					}
				}
			}
		}
		return nil
	}, true)

	return
}