pg_batch_add_product_service.go 5.0 KB
package domainService

import (
	"fmt"
	"github.com/linmadan/egglib-go/core/application"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"github.com/linmadan/egglib-go/utils/tool_funs"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
	"strconv"
	"time"
)

type PGBatchAddProductService struct {
	transactionContext *pgTransaction.TransactionContext
}

// BatchAddProduct 批量添加产品

// replaceOld true:已存在的做更新操作
func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, list []*domain.ImportProductItem, replaceOld bool) ([]interface{}, error) {
	var failRows = make([]interface{}, 0)

	productRepository, _ := repository.NewProductRepository(ptr.transactionContext)
	_, products, _ := productRepository.Find(map[string]interface{}{"companyId": opt.CompanyId, "orgId": opt.OrgId})
	var mapProduct = make(map[string]*domain.Product)
	for i := range products {
		mapProduct[products[i].ProductCode] = products[i]
	}

	var userService = NewUserService()
	var org *domain.Org
	org, err := userService.Organization(opt.OrgId)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	var materials domain.ProductMaterials
	if materials, err = ptr.GetProductMaterialByImportItems(opt.CompanyId, list); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	mapMaterials := materials.ToMapByNumber()
	for i := range list {
		item := list[i]
		if v, ok := mapMaterials[item.ProductCode]; !ok {
			item.FailReason = "导入的产品编号不存在"
			failRows = append(failRows, item)
			continue
		} else {
			item.Unit = v.ProductMaterialExt.Unit
			item.ProductName = v.MaterialName
			item.ProductCategory = v.MaterialCategory.Category
		}
		if err := item.Valid(); err != nil {
			item.FailReason = err.Error()
			failRows = append(failRows, item)
			continue
		}
		unitWeight, _ := strconv.ParseFloat(item.UnitWeight, 64)
		newItem := &domain.Product{
			CompanyId:       opt.CompanyId,
			OrgId:           opt.OrgId,
			ProductCode:     item.ProductCode,
			ProductName:     item.ProductName,
			ProductCategory: item.ProductCategory,
			ProductSpec: &domain.UnitQuantity{
				Unit:       item.Unit,
				UnitWeight: unitWeight,
			},
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
			Ext:       domain.NewExt(org.OrgName),
		}
		// 存在旧数据->>覆盖
		if replaceOld {
			if old, ok := mapProduct[newItem.ProductCode]; ok {
				if err := ptr.updateProduct(opt, item, old); err != nil {
					return failRows, err
				}
				continue
			}
		}

		if _, ok := mapProduct[newItem.ProductCode]; !ok {
			mapProduct[newItem.ProductCode] = newItem
		} else {
			item.FailReason = "导入的产品编号已存在"
			failRows = append(failRows, item)
			continue
		}
		if _, err := productRepository.Save(newItem); err != nil {
			log.Logger.Error(err.Error())
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
		}
	}
	return failRows, nil
}

func (ptr *PGBatchAddProductService) updateProduct(opt *domain.OperateInfo, item *domain.ImportProductItem, old *domain.Product) error {
	productRepository, _ := repository.NewProductRepository(ptr.transactionContext)
	if err := old.Update(tool_funs.SimpleStructToMap(item)); err != nil {
		return err
	}
	if _, err := productRepository.Save(old); err != nil {
		log.Logger.Error(err.Error())
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
	}
	return nil
}

func (ptr *PGBatchAddProductService) GetProductMaterialByProductCodes(companyId int, productCodes []string) ([]*domain.ProductMaterial, error) {
	productMaterialRepository, _ := repository.NewProductMaterialRepository(ptr.transactionContext)
	_, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"companyId": companyId, "materialNumbers": productCodes})
	return productMaterials, err
}

func (ptr *PGBatchAddProductService) GetProductMaterialByImportItems(companyId int, list []*domain.ImportProductItem) ([]*domain.ProductMaterial, error) {
	productCodes := ptr.GetProductCodesByImportItems(list)
	if len(productCodes) == 0 {
		return []*domain.ProductMaterial{}, nil
	}
	return ptr.GetProductMaterialByProductCodes(companyId, productCodes)
}

func (ptr *PGBatchAddProductService) GetProductCodesByImportItems(list []*domain.ImportProductItem) []string {
	var result = utils.NewSet()
	for _, v := range list {
		result.Add(v.ProductCode)
	}
	return result.KeysStr()
}

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