pg_batch_add_org_service.go 2.0 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"
	"time"
)

// PgBatchAddOrgService 批量创建组织服务
type PgBatchAddOrgService struct {
	transactionContext *pgTransaction.TransactionContext
}

func (ptr *PgBatchAddOrgService) BatchAddOrg(optUser *domain.OperateInfo, orgList []*domain.BatchAddOrgItem) error {
	orgRepository, err := repository.NewOrgRepository(ptr.transactionContext)
	if err != nil {
		return err
	}
	_, orgs, err := orgRepository.Find(map[string]interface{}{"companyId": optUser.CompanyId, "limit": 10000})
	if err != nil {
		return err
	}
	var mapOrg = make(map[string]*domain.Org)
	for i := range orgs {
		mapOrg[orgs[i].OrgCode] = orgs[i]
	}

	createOrgService, _ := NewPgCreateOrgService(ptr.transactionContext)
	for i := range orgList {
		item := orgList[i]
		orgItem := &domain.Org{
			CompanyId: optUser.CompanyId,
			OrgCode:   item.OrgCode,
			OrgName:   item.OrgName,
			IsOrg:     domain.IsNotOrgFlag,
			ParentId:  0,
			OrgStatus: domain.OrgStatusEnable,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
			Ext:       &domain.Ext{},
		}
		if v, ok := mapOrg[item.ParentOrgCode]; !ok {
			return fmt.Errorf(fmt.Sprintf("找不到组织:%v", item.OrgCode))
		} else {
			orgItem.ParentId = v.OrgId
		}

		orgItem, err = createOrgService.CreateOrg(optUser, orgItem)
		if err != nil {
			return fmt.Errorf("%v %v", item.OrgName, err.Error())
		}
		if _, ok := mapOrg[orgItem.OrgCode]; !ok {
			mapOrg[orgItem.OrgCode] = orgItem
		}
	}
	return err
}

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