k3cloud.go 8.9 KB
package syncdata

import (
	"strconv"
	"strings"
	"time"

	"github.com/linmadan/egglib-go/core/application"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils/k3cloud"
)

//拉取金蝶k3cloud的数据,并更新本地数据库

type PullDataK3CloudService struct {
}

func newK3cloudClient() (*k3cloud.Client, error) {
	// TODO 使用配置方式传入
	var (
		acctID   = "20211118121754866"
		username = "18559023318"
		password = "stx@123456"
		hostUrl  = "https://tianlian.test.ik3cloud.com/k3cloud"
	)
	client, err := k3cloud.NewClient(hostUrl, acctID, username, password)
	return client, err
}

func (srv *PullDataK3CloudService) PullMaterialNewest() error {
	var (
		err         error
		materialDao *dao.MaterialK3cloudDao
	)
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	materialDao, err = dao.NewMaterialK3cloudDao(transactionContext.(*pgTransaction.TransactionContext))
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	version, err := materialDao.GetLastVersion()
	if err != nil {
		return application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	if err = transactionContext.CommitTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	var timeFilter time.Time
	if version > 0 {
		timeFilter = time.Unix(version, 0)
	}
	err = srv.PullMaterial(timeFilter)
	if err != nil {
		return err
	}
	return err
}

//PullMaterial 拉取物料数据
func (srv *PullDataK3CloudService) PullMaterial(timeFilter time.Time) error {
	//拉取数据
	var filterString []string
	if !timeFilter.IsZero() {
		str := timeFilter.Format("2006-01-02T15:04:05")
		filterString = append(filterString, "FModifyDate>='"+str+"'")
	}
	client, err := newK3cloudClient()
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	fieldKeys := []string{
		"FMATERIALID", "FSpecification", "FName", "FNumber",
		"FDocumentStatus", "FForbidStatus", "FErpClsID",
		"FBaseUnitId", "FBaseUnitId.FName", "FCreateDate", "FModifyDate",
		"FForbidDate", "FApproveDate", "FMaterialGroup", "FMaterialGroup.FName",
		"FRefStatus", "FMaterialGroup.FNumber", "FUseOrgId", "FUseOrgId.FName",
	}
	var (
		startRow  int
		allResult []map[string]string
		queryErr  error
	)
	for {
		result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
			FormId: "BD_MATERIAL",
			Data: k3cloud.ExecuteBillQueryData{
				FormId:       "BD_MATERIAL",
				FieldKeys:    strings.Join(fieldKeys, ","), //查询的字段
				StartRow:     startRow,
				Limit:        1000,
				FilterString: strings.Join(filterString, " and "),
			},
		})
		if err != nil {
			queryErr = err
			break
		}
		mp := result.ToMapString()
		if len(mp) == 0 {
			break
		}
		allResult = append(allResult, mp...)
		startRow += 1000
	}
	if queryErr != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	var (
		materialModels []models.MaterialK3cloud
		materialTemp   models.MaterialK3cloud
	)
	nowTime := time.Now()
	for _, item := range allResult {
		materialId, err := strconv.Atoi(item["FMATERIALID"])
		if err != nil {
			return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
		fErpClsID, _ := strconv.Atoi(item["FErpClsID"])
		fBaseUnitId, _ := strconv.Atoi(item["FBaseUnitId"])
		materialGroup, _ := strconv.Atoi(item["MaterialGroup"])
		fUseOrgId, _ := strconv.Atoi(item["FUseOrgId"])
		refStatus, _ := strconv.Atoi(item["RefStatus"])
		fCreateDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FCreateDate"])
		fModifyDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FModifyDate"])
		fForbidDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FForbidDate"])
		fApproveDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FApproveDate"])
		materialTemp = models.MaterialK3cloud{
			MaterialId:          materialId,
			Name:                item["FName"],
			Number:              item["FNumber"],
			Specification:       item["FSpecification"],
			ForbidStatus:        item["FForbidStatus"],
			ErpClsId:            fErpClsID,
			BaseUnitId:          fBaseUnitId,
			BaseUnitName:        item["FBaseUnitId.FName"],
			CreateDate:          fCreateDate,
			ModifyDate:          fModifyDate,
			ForbidDate:          fForbidDate,
			ApproveDate:         fApproveDate,
			MaterialGroup:       materialGroup,
			MaterialGroupNumber: item["FMaterialGroup.FNumber"],
			MaterialGroupName:   item["FMaterialGroup.FName"],
			RefStatus:           refStatus,
			UseOrgId:            fUseOrgId,
			UseOrgName:          item["FUseOrgId.FName"],
			JoinProductId:       0,
			DataVersion:         nowTime.Unix(),
		}
		materialModels = append(materialModels, materialTemp)
	}
	var (
		materialDao *dao.MaterialK3cloudDao
	)
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	materialDao, err = dao.NewMaterialK3cloudDao(transactionContext.(*pgTransaction.TransactionContext))
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	//同步MaterialK3cloud表数据
	err = materialDao.SyncDataMaterialK3cloud(materialModels)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	//MaterialK3cloud表数据到Proudct表
	err = materialDao.SyncDataProudct(nowTime.Unix())
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err = transactionContext.CommitTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return nil
}

//PullMaterialGroup 拉取物料分组
func (srv *PullDataK3CloudService) PullMaterialGroup() error {
	client, err := newK3cloudClient()
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	fieldKeys := []string{
		"FID", "FNumber", "FName", "FParentId",
	}
	var (
		startRow  int
		allResult []map[string]string
		queryErr  error
	)
	for {
		result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
			FormId: "SAL_MATERIALGROUP",
			Data: k3cloud.ExecuteBillQueryData{
				FormId:    "SAL_MATERIALGROUP",
				FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
				StartRow:  startRow,
				Limit:     1000,
			},
		})
		if err != nil {
			queryErr = err
			break
		}
		mp := result.ToMapString()
		if len(mp) == 0 {
			break
		}
		allResult = append(allResult, mp...)
		startRow += 1000
	}
	if queryErr != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	var (
		materialGroups    []models.MaterialGroupK3cloud
		materialGroupTemp models.MaterialGroupK3cloud
	)
	nowTime := time.Now()
	for _, item := range allResult {
		id, _ := strconv.Atoi(item["FID"])
		fParentId, _ := strconv.Atoi(item["FParentId"])
		materialGroupTemp = models.MaterialGroupK3cloud{
			Id:          id,
			ParentId:    fParentId,
			Number:      item["FNumber"],
			Name:        item["FName"],
			DataVersion: nowTime.Unix(),
		}
		materialGroups = append(materialGroups, materialGroupTemp)
	}

	var (
		materialGroupDao *dao.MaterialGroupK3cloudDao
	)
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	materialGroupDao, err = dao.NewMaterialGroupK3cloudDao(transactionContext.(*pgTransaction.TransactionContext))
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	//记录到MaterialGroupK3cloud表
	err = materialGroupDao.SyncDataMaterialGroupK3cloud(materialGroups)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err = transactionContext.CommitTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return nil
}