import_product.go 2.0 KB
package service

import (
	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/utils/excel"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
	productService "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/product/service"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils/converter"
	"strings"
)

// ImportProduct 导入生产信息
func (srv ExcelDataService) ImportProduct(importDataCommand *command.ImportDataCommand) (interface{}, error) {
	excelImport := excel.NewExcelImport()
	excelImport.RowBegin = 3 //第二行开始读取
	excelImport.DataFields = []excel.DataField{
		{EnName: "productCode", CnName: "产品编号"},
		{EnName: "productName", CnName: "*品名"},
		{EnName: "unit", CnName: "*规格"},
		{EnName: "productCategory", CnName: "*类别"},
		{EnName: "unitWeight", CnName: "投入单份重量"},
	}
	excelData, err := converter.OpenImportFileFromIoReader(excelImport, importDataCommand.Reader, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	items := make([]*domain.ImportProductItem, 0)
	for _, v := range excelData {
		item := &domain.ImportProductItem{
			ProductCode:     strings.TrimSpace(v["productCode"]),
			ProductName:     strings.TrimSpace(v["productName"]),
			ProductCategory: strings.TrimSpace(v["productCategory"]),
			Unit:            strings.TrimSpace(v["unit"]),
			UnitWeight:      strings.TrimSpace(v["unitWeight"]),
		}
		items = append(items, item)
	}

	svr := productService.NewProductService(nil)
	failRows, err := svr.BatchAddProduct(importDataCommand.Operator, items)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return srv.importResultWithHeader(excelImport.DataFields, failRows, len(items)), nil
}