k3cloud.go 22.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
package syncdata

import (
	"fmt"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
	"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"
	)
	if constant.SERVICE_ENV == "prd" {
		hostUrl = "https://tianlian.ik3cloud.com/k3cloud"
		acctID = "20211118121126059"
	}
	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())
	}

	var userService = domainService.NewUserService()
	org, err := userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	//MaterialK3cloud表数据到Proudct表
	err = materialDao.SyncDataProudct(nowTime.Unix(), org.OrgName)
	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
}

//PullPrdMoNewest 拉取生产订单数据
func (srv *PullDataK3CloudService) PullPrdMoNewest() error {
	var (
		err      error
		prdMoDao *dao.PrdMoK3cloudDao
	)
	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()
	}()
	prdMoDao, err = dao.NewPrdMoK3cloudDao(transactionContext.(*pgTransaction.TransactionContext))
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	version, err := prdMoDao.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.PullPrdMo(timeFilter)
	if err != nil {
		return err
	}
	return err
}

//PullPrdMo 拉取生产订单数据
func (srv *PullDataK3CloudService) PullPrdMo(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{
		"FRowId", "FBillNo", "FWorkShopID", "FWorkShopID.FName", "FMaterialId", "FMaterialId.FName",
		"FMaterialId.FNumber", "FMaterialId.FSpecification", "FPlanStartDate", "FPlanFinishDate", "FDate", "FQty",
		"FCreateDate", "FModifyDate", "FPrdOrgId", "FPrdOrgId.FName", "FUnitId", "FUnitId.FName", "FDescription",
		"FStatus",
	}
	var (
		startRow  int
		allResult []map[string]string
		queryErr  error
	)
	for {
		result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
			FormId: "PRD_MO",
			Data: k3cloud.ExecuteBillQueryData{
				FormId:       "PRD_MO",
				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 (
		prdMoModels []models.PrdMoK3cloud
		prdMoTemp   models.PrdMoK3cloud
	)
	version := time.Now().Unix()
	for _, item := range allResult {
		workShopID, _ := strconv.Atoi(item["FWorkShopID"])
		materialId, _ := strconv.Atoi(item["FMaterialId"])
		qty, _ := strconv.ParseFloat(item["FQty"], 64)
		fPrdOrgId, _ := strconv.Atoi(item["FPrdOrgId"])
		planStartDate, _ := time.Parse("2006-01-02T15:04:05", item["FPlanStartDate"])
		planFinishDate, _ := time.Parse("2006-01-02T15:04:05", item["FPlanFinishDate"])
		fDate, _ := time.Parse("2006-01-02T15:04:05", item["FDate"])
		fCreateDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FCreateDate"])
		fModifyDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FModifyDate"])
		fUnitId, _ := strconv.Atoi(item["FUnitId"])
		status, _ := strconv.Atoi(item["FStatus"])
		prdMoTemp = models.PrdMoK3cloud{
			RowId:          item["FRowId"],
			WorkShopID:     workShopID,
			MaterialId:     materialId,
			Qty:            qty,
			PlanStartDate:  planStartDate,
			PlanFinishDate: planFinishDate,
			FDate:          fDate,
			CreateDate:     fCreateDate,
			ModifyDate:     fModifyDate,
			BillNo:         item["FBillNo"],
			WorkShopName:   item["FWorkShopID.FName"],
			MaterialName:   item["FMaterialId.FName"],
			MaterialNumber: item["FMaterialId.FNumber"],
			DataVersion:    version,
			PrdOrgId:       fPrdOrgId,
			PrdOrgName:     item["FPrdOrgId.FName"],
			Specification:  item["FMaterialId.FSpecification"],
			UnitName:       item["FUnitId.FName"],
			UnitId:         fUnitId,
			Description:    item["FDescription"],
			Status:         status,
		}
		prdMoModels = append(prdMoModels, prdMoTemp)
	}
	var (
		prdMoDao *dao.PrdMoK3cloudDao
	)
	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()
	}()
	prdMoDao, err = dao.NewPrdMoK3cloudDao(transactionContext.(*pgTransaction.TransactionContext))
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	//同步PrdMoK3cloud表数据
	err = prdMoDao.SyncDataPrdMoK3cloud(prdMoModels)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	//var userService = domainService.NewUserService()
	//org, err := userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
	//if err != nil {
	//	return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	//}

	//同步ProductPlan 表数据
	//err = prdMoDao.SyncDataProductPlan(version, constant.MANUFACTURE_DEFAULT_COMPANYID, constant.MANUFACTURE_DEFAULT_ORGID, org.OrgName)
	//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
}

// 同步产品
func (srv *PullDataK3CloudService) SyncDataProduct(ptr *pgTransaction.TransactionContext, fromTime time.Time) error {
	prdMoDao, err := dao.NewMaterialK3cloudDao(ptr)
	if err != nil {
		return err
	}
	var userService = domainService.NewUserService()
	org, err := userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	materials, err := prdMoDao.SearchProductByTime(fromTime, "素天下") // 默认企业名称素天下、或者使用组织ID
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	var (
		cid = constant.MANUFACTURE_DEFAULT_COMPANYID
		oid = constant.MANUFACTURE_DEFAULT_ORGID
	)
	productRepository, _, _ := factory.FastPgProduct(ptr, 0)
	for _, v := range materials {
		var product *domain.Product
		product, err = productRepository.FindOne(map[string]interface{}{"companyId": cid, "orgId": oid, "productCode": v.Number})
		if err == nil && product != nil {
			continue
		}
		if err == domain.ErrorNotFound {
			err = nil
			product = &domain.Product{
				CompanyId:       cid,
				OrgId:           oid,
				ProductCode:     v.Number,
				ProductName:     v.Name,
				ProductCategory: v.MaterialGroupName,
				ProductSpec: &domain.UnitQuantity{
					Unit:       v.Specification,
					UnitWeight: 0,
				},
				CreatedAt: v.CreateDate,
				UpdatedAt: time.Now(),
				Ext:       domain.NewExt(org.OrgName),
			}
		}
		if product, err = productRepository.Save(product); err != nil {
			return err
		}
	}
	return nil
	//return prdMoDao.SyncDataProductByTime(fromTime, org.OrgName)
}

// 同步生产计划
func (srv *PullDataK3CloudService) SyncDataProductPlan(ptr *pgTransaction.TransactionContext, fromTime time.Time) error {
	/*
		1.获取更新时间
		2.获取prd_mo_k3cloud从更新时间开始的有变化的数据
		3.查询是否有重复的批次号
		4.有进行更新,其他的插入
	*/
	//lastTime, err := redis.GetLastFetchTime()
	//if err != nil {
	//	return err
	//}
	var lastTime = utils.GetZeroTime(time.Now()).Add(-time.Hour * 24) //前一天有修改的记录
	if !fromTime.IsZero() {
		lastTime = fromTime
	}
	prdMoK3cloudDao, _ := dao.NewPrdMoK3cloudDao(ptr)
	records, err := prdMoK3cloudDao.GetLatestData(lastTime)
	if err != nil {
		return err
	}
	var userService = domainService.NewUserService()
	org, err := userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	var (
		cid      = constant.MANUFACTURE_DEFAULT_COMPANYID
		oid      = constant.MANUFACTURE_DEFAULT_ORGID
		workshop *domain.Workshop
		exists   bool
	)

	workshops, _ := factory.FastPgWorkshops(ptr, cid)

	productPlanRepository, _, _ := factory.FastPgProductPlan(ptr, 0)
	productRepository, _, _ := factory.FastPgProduct(ptr, 0)
	for _, v := range records {
		if workshop, exists = workshops.ExistsWorkshops(v.WorkShopName); !exists {
			continue
		}
		var plan *domain.ProductPlan
		var product *domain.Product

		// 产品信息
		product, err = productRepository.FindOne(map[string]interface{}{"companyId": cid, "orgId": oid, "productCode": v.MaterialNumber})
		if err != nil || err == domain.ErrorNotFound {
			continue
		}
		// 计划信息
		plan, err = productPlanRepository.FindOne(map[string]interface{}{"companyId": cid, "orgId": oid, "erpBillNo": v.BillNo, "productCode": v.MaterialNumber})
		if err == nil && plan != nil {
			continue
		}
		batchNumber, genBatchNumberErr := redis.GenCode(redis.NewBillNoCodeCache(cid, v.BillNo))
		if genBatchNumberErr != nil {
			log.Logger.Error(err.Error(), map[string]interface{}{"id": v.RowId, "err": "gen batch number error"})
			continue
		}
		if err == domain.ErrorNotFound {
			plan = &domain.ProductPlan{
				CompanyId:   cid,
				OrgId:       oid,
				BatchNumber: batchNumber,
				ProductDate: v.PlanStartDate,
				Workshop:    workshop.CloneSample(),
				WorkOn:      0,
				Machine:     "",
				PlanStatus:  domain.PlanOffline,
				WorkStation: &domain.WorkStation{},
				CreatedAt:   time.Now(),
				UpdatedAt:   time.Now(),
			}
		}
		// 更新数据
		plan.PlanDevoted = &domain.UnitQuantity{
			Unit:       product.ProductSpec.Unit,
			Quantity:   v.Qty,
			Weight:     product.ProductWeigh(v.Qty),
			UnitWeight: product.ProductSpec.UnitWeight,
		}
		plan.Workshop = workshop.CloneSample()
		plan.UpdatedAt = time.Now()
		plan.Ext = domain.NewExt(org.OrgName).WithProductPlanExt(&domain.ProductPlanExt{
			ProductId:   product.ProductId,
			ProductCode: product.ProductCode,
			ProductName: product.ProductName,
			DevotedUnit: "份",
			ErpBillNo:   v.BillNo,
		})
		plan.PlanProductName = product.ProductName
		plan.Remark = v.Description

		if plan, err = productPlanRepository.Save(plan); err != nil {
			return err
		}
	}
	return nil
}

// 同步产品
func (srv *PullDataK3CloudService) SyncDataMaterialGroup(ptr *pgTransaction.TransactionContext) error {
	prdMoDao, err := dao.NewMaterialK3cloudDao(ptr)
	if err != nil {
		return err
	}
	var userService = domainService.NewUserService()
	org, err := userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	fromMaterialGroups, err := prdMoDao.SearchMaterialGroup() // 默认企业名称素天下、或者使用组织ID
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	var (
		cid = constant.MANUFACTURE_DEFAULT_COMPANYID
		oid = constant.MANUFACTURE_DEFAULT_ORGID
	)
	productMaterialGroupRepository, _, _ := factory.FastProductMaterialGroup(ptr, 0)
	_, materialGroups, err := productMaterialGroupRepository.Find(map[string]interface{}{"companyId": cid})
	if err != nil {
		return err
	}
	mapMaterialGroups := domain.ProductMaterialGroups(materialGroups).ToMapByGroupNumber()
	mapFromMaterialGroups := models.MaterialGroupK3clouds(fromMaterialGroups).ToMapId()
	for _, from := range fromMaterialGroups {
		to, ok := mapMaterialGroups[from.Number]
		if ok {
			// 更新
			if to.MaterialGroupName != from.Name {
				log.Logger.Info(fmt.Sprintf("更新物料分组 old:%v new:%v", to.MaterialGroupName, from.Name), map[string]interface{}{"material": to})
				to.MaterialGroupName = from.Name
			}
			continue
		}
		var parentId int
		if from.ParentId > 0 {
			parent, ok := mapFromMaterialGroups[from.ParentId]
			if !ok {
				log.Logger.Warn("parent node not exits", map[string]interface{}{"material": to})
				continue
			}
			toParent, ok := mapMaterialGroups[parent.Number]
			if !ok {
				log.Logger.Warn("to parent node not exits", map[string]interface{}{"material": to})
				continue
			}
			parentId = toParent.ProductMaterialGroupId
		}
		productMaterialGroup := &domain.ProductMaterialGroup{
			CompanyId:           cid,
			OrgId:               oid,
			Pid:                 parentId,
			MaterialGroupName:   from.Name,
			MaterialGroupNumber: from.Number,
			CreatedAt:           time.Now(),
			UpdatedAt:           time.Now(),
			Ext:                 domain.NewExt(org.OrgName),
		}
		if productMaterialGroup, err = productMaterialGroupRepository.Save(productMaterialGroup); err != nil {
			return err
		}
		mapMaterialGroups[productMaterialGroup.MaterialGroupNumber] = productMaterialGroup
	}
	return nil
}