pg_batch_add_org_service.go 2.3 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) ([]*domain.BatchAddOrgItem, error) {
	orgRepository, err := repository.NewOrgRepository(ptr.transactionContext)
	var failRows = make([]*domain.BatchAddOrgItem, 0)
	if err != nil {
		return failRows, err
	}
	_, orgs, err := orgRepository.Find(map[string]interface{}{"companyId": optUser.CompanyId, "limit": 10000})
	if err != nil {
		return failRows, 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 {
			item.FailReason = fmt.Sprintf("找不到组织:%v", item.OrgCode)
			failRows = append(failRows, item)
			continue
			//return fmt.Errorf(fmt.Sprintf("找不到组织:%v", item.OrgCode))
		} else {
			orgItem.ParentId = v.OrgId
		}

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

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