package svc import ( "applet/app/db" "applet/app/e" svc2 "applet/app/svc" "applet/app/utils" "applet/app/utils/cache" "applet/app/utils/logx" db2 "applet/supply/db" "applet/supply/db/model" "applet/supply/enum" "applet/supply/md" "errors" "fmt" "github.com/gin-gonic/gin" "github.com/jinzhu/copier" cregex "github.com/mingrammer/commonregex" "github.com/shopspring/decimal" "regexp" "strings" "time" ) //处理图片 func DealImg(c *gin.Context, imageListUrl []string) []string { //七牛云配置 scheme, host, subDomain, moreSubDomain := ImageBucketNew(c) domain := fmt.Sprintf("%s://%s/", scheme, host) secondDomain := fmt.Sprintf("%s://%s/", scheme, subDomain) fmt.Println("") //处理图片链接 for k, v := range imageListUrl { imageListUrl[k] = strings.ReplaceAll(v, domain, "{{host}}") imageListUrl[k] = strings.ReplaceAll(imageListUrl[k], secondDomain, "{{subhost}}") //兼容商品是迁移过来的 for moreK, moreV := range moreSubDomain { keys := strings.ReplaceAll(moreK, "file_bucket_sub_host", "") moreDomain := fmt.Sprintf("%s://%s/", scheme, moreV) imageListUrl[k] = strings.ReplaceAll(imageListUrl[k], moreDomain, "{{subhost"+keys+"}}") } } return imageListUrl } func CloudChainFenXiaoGoodsChangeMallGoods(c *gin.Context, cloudChainGoods map[string]interface{}, mallGoods *md.AddGoodsReq) error { defer func() { if err := recover(); err != nil { logx.Error(err) } }() productInfo, ok := cloudChainGoods["productInfo"].(map[string]interface{}) if !ok { return logx.Error("错误的数据") } shippingInfo, ok := productInfo["shippingInfo"].(map[string]interface{}) if !ok { return logx.Error("错误的数据") } tem, err := CloudChainGoodsShippingTemChangeMallShippingTem(c, shippingInfo, mallGoods.Base.CloudChainGoodsId, mallGoods.Base.MerchantId) if err != nil { return err } key := fmt.Sprintf("%s:merchant_1688_line_price_rete", c.GetString("mid")) rate, _ := cache.GetString(key) if rate == "" { rate = "50" } rateD, _ := decimal.NewFromString(rate) rateD = rateD.Div(decimal.NewFromInt(100)) rate = rateD.String() rateF := utils.AnyToFloat64(rate) mallGoods.Base.GoodsCode = "f1x688" + mallGoods.Base.CloudChainGoodsId mallGoods.Base.ShippingType = enum.MallShippingTypeExpress if tem.Id == 1 && tem.CloudChainTemId == "1" { mallGoods.Base.ShippingFeeType = enum.MallShippingFeeTypeUnify mallGoods.Base.ShippingTplID = 0 mallGoods.Base.ShippingFee = "0" } else if tem.Id == 0 && tem.CloudChainTemId == "1" { mallGoods.Base.ShippingFeeType = enum.MallShippingFeeTypeUnify mallGoods.Base.ShippingTplID = 0 mallGoods.Base.ShippingFee = "0" } else if tem.Id == 0 && tem.CloudChainTemId != "" { mallGoods.Base.ShippingFeeType = enum.MallShippingFeeTypeUnify mallGoods.Base.ShippingTplID = 0 mallGoods.Base.ShippingFee = "0" } else { mallGoods.Base.ShippingFeeType = enum.MallShippingFeeTypeTpl mallGoods.Base.ShippingTplID = tem.Id } //将1688的商品属性转换成custom_property var cloudChainGoodsSpeMap []struct { GroupName string `json:"group_name" label:"属性组别名称"` Index int `json:"index" label:"属性值索引"` Name string `json:"name" label:"属性值"` } // 自定义参数 type Attribute struct { AttributeID int64 `json:"attributeID"` AttributeName string `json:"attributeName"` IsCustom bool `json:"isCustom"` Value string `json:"value"` } var attributes []*Attribute utils.Unserialize([]byte(utils.SerializeStr(productInfo["attributes"])), &attributes) for index, attribute := range attributes { cloudChainGoodsSpeMap = append(cloudChainGoodsSpeMap, struct { GroupName string `json:"group_name" label:"属性组别名称"` Index int `json:"index" label:"属性值索引"` Name string `json:"name" label:"属性值"` }{ attribute.AttributeName, index, attribute.Value, }) } //标题 mallGoods.Base.Title = utils.AnyToString(productInfo["subject"]) mallGoods.Base.CustomProperty = cloudChainGoodsSpeMap //最低限购 mallGoods.Base.MinOrderQuantity = utils.AnyToString(productInfo["saleInfo"].(map[string]interface{})["minOrderQuantity"]) //商品主图 utils.Unserialize([]byte(utils.SerializeStr(productInfo["image"].(map[string]interface{})["images"])), &mallGoods.Base.ImageList) for i, image := range mallGoods.Base.ImageList { //https://cbu01.alicdn.com/ if !strings.Contains(image, "https") || !strings.Contains(image, "http") { if !strings.Contains(image, "https://cbu01.alicdn.com") { mallGoods.Base.ImageList[i] = "https://cbu01.alicdn.com/" + image } } } //商品详情图 if _, ok := productInfo["description"]; ok { compile := regexp.MustCompile("src=\"https://.*?\"") tmpsLinks := compile.FindAllString(utils.AnyToString(productInfo["description"]), -1) Links := cregex.Links(utils.AnyToString(tmpsLinks)) mallGoods.Base.Detail = Links if len(mallGoods.Base.Detail) == 0 { mallGoods.Base.Detail = mallGoods.Base.ImageList } } else { if _, ok := productInfo["intelligentInfo"]; ok { utils.Unserialize([]byte(utils.SerializeStr(productInfo["intelligentInfo"].(map[string]interface{})["descriptionImages"])), &mallGoods.Base.Detail) if len(mallGoods.Base.Detail) == 0 { mallGoods.Base.Detail = mallGoods.Base.ImageList } } else { mallGoods.Base.Detail = mallGoods.Base.ImageList } } //处理sku type skuAttribute struct { AttributeID int64 `json:"attributeID"` AttributeName string `json:"attributeName"` AttributeValue string `json:"attributeValue"` SkuImageURL string `json:"skuImageUrl,omitempty"` } type skuInfo struct { RetailPrice float64 `json:"retailPrice"` //建议零售价 AmountOnSale int `json:"amountOnSale"` //可销售数量 Attributes []skuAttribute `json:"attributes"` //SKU属性值,可填多组信息 CargoNumber string `json:"cargoNumber"` //指定规格的货号 ConsignPrice float64 `json:"consignPrice"` //分销基准价。代销场景均使用该价格。无SKU商品查看saleInfo中的consignPrice Price float64 `json:"price"` // 报价时该规格的单价 ChannelPrice float64 `json:"channelPrice"` // 厂货通渠道专享价(单位:元) CpsSuggestPrice float64 `json:"cpsSuggestPrice"` //CPS建议价(单位:元) SkuID int64 `json:"skuId"` //skuId,该规格在所有商品中的唯一标记 SpecID string `json:"specId"` //specId,该规格在本商品内的唯一标记 } var skuInfos []*skuInfo utils.Unserialize([]byte(utils.SerializeStr(productInfo["skuInfos"])), &skuInfos) BaseSpe := make(map[string]map[string]string) for _, info := range skuInfos { for _, attribute := range info.Attributes { valuesMap := BaseSpe[attribute.AttributeName] if valuesMap == nil { valuesMap = make(map[string]string) } valuesMap[attribute.AttributeValue] = "" BaseSpe[attribute.AttributeName] = valuesMap } } for name, valueMap := range BaseSpe { var spe md.Spe spe.Name = name values := make([]string, 0) for value, _ := range valueMap { values = append(values, value) } spe.Values = values mallGoods.Base.Spe = append(mallGoods.Base.Spe, spe) } for _, info := range skuInfos { var skuMd md.MallGoodsSku consignPrice := info.ConsignPrice if info.RetailPrice > 0 { consignPrice = info.RetailPrice } else { if consignPrice < info.ChannelPrice { consignPrice = info.ChannelPrice } } skuMd.LinePrice = utils.AnyToString(consignPrice + consignPrice*rateF) skuMd.Price = utils.AnyToString(consignPrice) skuMd.Stock = info.AmountOnSale skuMd.CloudChainSkuId = utils.AnyToString(info.SkuID) skuMd.SpecID = info.SpecID skuMd.Weight = utils.AnyToString(shippingInfo["unitWeight"]) skuMd.SkuCode = "f1x688" + skuMd.CloudChainSkuId if len(info.Attributes) > 0 { skuMd.CloudChainSkuImgUrl = info.Attributes[0].SkuImageURL //https://cbu01.alicdn.com/ if !strings.Contains(skuMd.CloudChainSkuImgUrl, "https") || !strings.Contains(skuMd.CloudChainSkuImgUrl, "http") { if !strings.Contains(skuMd.CloudChainSkuImgUrl, "https://cbu01.alicdn.com") { skuMd.CloudChainSkuImgUrl = "https://cbu01.alicdn.com/" + skuMd.CloudChainSkuImgUrl } } } skuSkuMap := make(map[string]*md.MallGoodsSkuSku) for _, attribute := range info.Attributes { var skuSkuMd md.MallGoodsSkuSku skuSkuMd.Name = attribute.AttributeName skuSkuMd.Value = attribute.AttributeValue _, ok := skuSkuMap[attribute.AttributeName] if !ok { skuMd.Sku = append(skuMd.Sku, skuSkuMd) skuSkuMap[attribute.AttributeName] = &skuSkuMd } else { break } } mallGoods.SkuList = append(mallGoods.SkuList, &skuMd) } if len(mallGoods.SkuList) == 0 { type PriceRange struct { Price float64 `json:"price"` StartQuantity int `json:"startQuantity"` } type saleInfo struct { AmountOnSale int `json:"amountOnSale"` MinOrderQuantity int `json:"minOrderQuantity"` MixWholeSale bool `json:"mixWholeSale"` PriceAuth bool `json:"priceAuth"` PriceRanges []PriceRange `json:"priceRanges"` QuoteType int `json:"quoteType"` SupportOnlineTrade bool `json:"supportOnlineTrade"` Unit string `json:"unit"` BatchNumber int `json:"batchNumber"` RetailPrice float64 `json:"retailprice"` Sellunit string `json:"sellunit"` ConsignPrice float64 `json:"consignPrice"` CpsSuggestPrice float64 `json:"cpsSuggestPrice"` ChannelPrice float64 `json:"channelPrice"` } var saleInfoMd saleInfo utils.Unserialize([]byte(utils.SerializeStr(productInfo["saleInfo"])), &saleInfoMd) consignPrice := saleInfoMd.ConsignPrice if consignPrice < saleInfoMd.ChannelPrice { consignPrice = saleInfoMd.ChannelPrice } for _, priceRange := range saleInfoMd.PriceRanges { if consignPrice < priceRange.Price { consignPrice = priceRange.Price } } var skuMd md.MallGoodsSku skuMd.LinePrice = utils.AnyToString(consignPrice + consignPrice*rateF) skuMd.Price = utils.AnyToString(consignPrice) skuMd.Stock = saleInfoMd.AmountOnSale skuMd.CloudChainSkuId = utils.AnyToString(mallGoods.Base.CloudChainGoodsId) skuMd.SpecID = "" skuMd.Weight = utils.AnyToString(shippingInfo["unitWeight"]) skuMd.Sku = make([]md.MallGoodsSkuSku, 0) mallGoods.SkuList = append(mallGoods.SkuList, &skuMd) } return nil } func CalculateFirstAddPriceNumByMainSystem(price float64) float64 { var basicSetting model.SupplyBasicSetting get, _ := db.Db.Get(&basicSetting) if get { if basicSetting.PriceAdjustBaseType == 2 { if basicSetting.PriceAdjustType == 1 { afterPrice := price + utils.StrToFloat64(basicSetting.PriceAdjustValue) return afterPrice } else if basicSetting.PriceAdjustType == 2 { afterPrice := price + (price * (utils.StrToFloat64(basicSetting.PriceAdjustValue) / 100)) return afterPrice } } return price } return price } func CloudChainGoodsChangeMallGoodsV2(c *gin.Context, cloudChainGoods map[string]interface{}, mallGoods *md.AddGoodsReq) error { defer func() { if err := recover(); err != nil { logx.Error(err) } }() productInfo, ok := cloudChainGoods["productInfo"].(map[string]interface{}) if !ok { return logx.Error("错误的数据") } shippingInfo, ok := productInfo["shippingInfo"].(map[string]interface{}) if !ok { return logx.Error("错误的数据") } key := fmt.Sprintf("%s:merchant_1688_line_price_rete", c.GetString("mid")) rate, _ := cache.GetString(key) if rate == "" { rate = "50" } rateD, _ := decimal.NewFromString(rate) rateD = rateD.Div(decimal.NewFromInt(100)) rate = rateD.String() rateF := utils.AnyToFloat64(rate) mallGoods.Base.ShippingType = enum.MallShippingTypeExpress //将1688的商品属性转换成spe cloudChainGoodsSpeMap := make(map[string][]string) type Attribute struct { AttributeID int64 `json:"attributeID"` AttributeName string `json:"attributeName"` IsCustom bool `json:"isCustom"` Value string `json:"value"` } var attributes []*Attribute utils.Unserialize([]byte(utils.SerializeStr(productInfo["attributes"])), &attributes) for _, attribute := range attributes { cloudChainGoodsSpeMap[attribute.AttributeName] = append(cloudChainGoodsSpeMap[attribute.AttributeName], attribute.Value) } //标题 mallGoods.Base.Title = utils.AnyToString(productInfo["subject"]) //最低限购 mallGoods.Base.MinOrderQuantity = utils.AnyToString(productInfo["saleInfo"].(map[string]interface{})["minOrderQuantity"]) //商品主图 utils.Unserialize([]byte(utils.SerializeStr(productInfo["image"].(map[string]interface{})["images"])), &mallGoods.Base.ImageList) for i, image := range mallGoods.Base.ImageList { //https://cbu01.alicdn.com/ if !strings.Contains(image, "https") || !strings.Contains(image, "http") { if !strings.Contains(image, "https://cbu01.alicdn.com") { mallGoods.Base.ImageList[i] = "https://cbu01.alicdn.com/" + image } } } //商品详情图 if _, ok := productInfo["description"]; ok { Links := cregex.Links(utils.AnyToString(productInfo["description"])) mallGoods.Base.Detail = Links if len(mallGoods.Base.Detail) == 0 { mallGoods.Base.Detail = mallGoods.Base.ImageList } } else { if _, ok := productInfo["intelligentInfo"]; ok { utils.Unserialize([]byte(utils.SerializeStr(productInfo["intelligentInfo"].(map[string]interface{})["descriptionImages"])), &mallGoods.Base.Detail) if len(mallGoods.Base.Detail) == 0 { mallGoods.Base.Detail = mallGoods.Base.ImageList } for i, img := range mallGoods.Base.Detail { if strings.Contains("\\", img) { mallGoods.Base.Detail[i] = strings.ReplaceAll(img, "\\", "") } } } else { mallGoods.Base.Detail = mallGoods.Base.ImageList } } //处理sku type skuAttribute struct { AttributeID int64 `json:"attributeID"` AttributeName string `json:"attributeName"` AttributeValue string `json:"attributeValue"` SkuImageURL string `json:"skuImageUrl,omitempty"` } type skuInfo struct { RetailPrice float64 `json:"retailPrice"` //建议零售价 AmountOnSale int `json:"amountOnSale"` //可销售数量 Attributes []skuAttribute `json:"attributes"` //SKU属性值,可填多组信息 CargoNumber string `json:"cargoNumber"` //指定规格的货号 ConsignPrice float64 `json:"consignPrice"` //分销基准价。代销场景均使用该价格。无SKU商品查看saleInfo中的consignPrice Price float64 `json:"price"` // 报价时该规格的单价 ChannelPrice float64 `json:"channelPrice"` // 厂货通渠道专享价(单位:元) CpsSuggestPrice float64 `json:"cpsSuggestPrice"` //CPS建议价(单位:元) SkuID int64 `json:"skuId"` //skuId,该规格在所有商品中的唯一标记 SpecID string `json:"specId"` //specId,该规格在本商品内的唯一标记 } var skuInfos []*skuInfo utils.Unserialize([]byte(utils.SerializeStr(productInfo["skuInfos"])), &skuInfos) BaseSpe := make(map[string]map[string]string) for _, info := range skuInfos { for _, attribute := range info.Attributes { valuesMap := BaseSpe[attribute.AttributeName] if valuesMap == nil { valuesMap = make(map[string]string) } valuesMap[attribute.AttributeValue] = "" BaseSpe[attribute.AttributeName] = valuesMap } } for name, valueMap := range BaseSpe { var spe md.Spe spe.Name = name values := make([]string, 0) for value, _ := range valueMap { values = append(values, value) } spe.Values = values mallGoods.Base.Spe = append(mallGoods.Base.Spe, spe) } for _, info := range skuInfos { var skuMd md.MallGoodsSku consignPrice := info.ConsignPrice if info.RetailPrice > 0 { consignPrice = info.RetailPrice } else { if consignPrice < info.ChannelPrice { consignPrice = info.ChannelPrice } } skuMd.LinePrice = utils.AnyToString(consignPrice + consignPrice*rateF) skuMd.Price = utils.AnyToString(consignPrice) skuMd.Stock = info.AmountOnSale skuMd.CloudChainSkuId = utils.AnyToString(info.SkuID) skuMd.SpecID = info.SpecID skuMd.Weight = utils.AnyToString(shippingInfo["unitWeight"]) if len(info.Attributes) > 0 { skuMd.CloudChainSkuImgUrl = info.Attributes[0].SkuImageURL //https://cbu01.alicdn.com/ if skuMd.CloudChainSkuImgUrl != "" { if !strings.Contains(skuMd.CloudChainSkuImgUrl, "https") || !strings.Contains(skuMd.CloudChainSkuImgUrl, "http") { if !strings.Contains(skuMd.CloudChainSkuImgUrl, "https://cbu01.alicdn.com") { skuMd.CloudChainSkuImgUrl = "https://cbu01.alicdn.com/" + skuMd.CloudChainSkuImgUrl } } } } skuSkuMap := make(map[string]*md.MallGoodsSkuSku) for _, attribute := range info.Attributes { var skuSkuMd md.MallGoodsSkuSku skuSkuMd.Name = attribute.AttributeName skuSkuMd.Value = attribute.AttributeValue _, ok := skuSkuMap[attribute.AttributeName] if !ok { skuMd.Sku = append(skuMd.Sku, skuSkuMd) skuSkuMap[attribute.AttributeName] = &skuSkuMd } else { break } } mallGoods.SkuList = append(mallGoods.SkuList, &skuMd) } if len(mallGoods.SkuList) == 0 { type PriceRange struct { Price float64 `json:"price"` StartQuantity int `json:"startQuantity"` } type saleInfo struct { AmountOnSale int `json:"amountOnSale"` MinOrderQuantity int `json:"minOrderQuantity"` MixWholeSale bool `json:"mixWholeSale"` PriceAuth bool `json:"priceAuth"` PriceRanges []PriceRange `json:"priceRanges"` QuoteType int `json:"quoteType"` SupportOnlineTrade bool `json:"supportOnlineTrade"` Unit string `json:"unit"` BatchNumber int `json:"batchNumber"` RetailPrice float64 `json:"retailprice"` Sellunit string `json:"sellunit"` ConsignPrice float64 `json:"consignPrice"` CpsSuggestPrice float64 `json:"cpsSuggestPrice"` ChannelPrice float64 `json:"channelPrice"` } var saleInfoMd saleInfo utils.Unserialize([]byte(utils.SerializeStr(productInfo["saleInfo"])), &saleInfoMd) consignPrice := saleInfoMd.ConsignPrice if saleInfoMd.RetailPrice > 0 { consignPrice = saleInfoMd.RetailPrice } else { if consignPrice < saleInfoMd.ChannelPrice { consignPrice = saleInfoMd.ChannelPrice } for _, priceRange := range saleInfoMd.PriceRanges { if consignPrice < priceRange.Price { consignPrice = priceRange.Price } } } var skuMd md.MallGoodsSku skuMd.LinePrice = utils.AnyToString(consignPrice + consignPrice*rateF) skuMd.Price = utils.AnyToString(consignPrice) skuMd.Stock = saleInfoMd.AmountOnSale skuMd.CloudChainSkuId = utils.AnyToString(mallGoods.Base.CloudChainGoodsId) skuMd.SpecID = "" skuMd.Weight = utils.AnyToString(shippingInfo["unitWeight"]) skuMd.Sku = make([]md.MallGoodsSkuSku, 0) mallGoods.SkuList = append(mallGoods.SkuList, &skuMd) } return nil } // AddMallGoods 添加、编辑商品 func AddMallGoods(c *gin.Context, req *md.AddGoodsReq) error { if req.Base.GoodsId != "" { _, has, err := db.GetComm(svc2.MasterDb(c), &model.MallGoods{GoodsId: utils.StrToInt64(req.Base.GoodsId)}) if err != nil { return e.NewErr(e.ERR_DB_ORM, err.Error()) } if !has { return e.NewErr(e.ERR_INVALID_ARGS, "编辑的商品ID不存在") } } sess := svc2.MasterDb(c).NewSession() defer func() { _ = sess.Close() }() err := sess.Begin() if err != nil { return e.NewErr(e.ERR_DB_ORM, err.Error()) } // 基本信息保存 var goodsModel model.MallGoods err = copier.Copy(&goodsModel, req.Base) goodsModel.GoodsId = utils.StrToInt64(req.Base.GoodsId) if err != nil { return e.NewErr(e.ERR_DB_ORM, err.Error()) } now := time.Now() goodsModel.CloudChainGoodsId = req.Base.CloudChainGoodsId goodsModel.MinOrderQuantity = req.Base.MinOrderQuantity goodsModel.SaleState = 0 //TODO::所有商家端编辑的产品,都需要重新审核 goodsModel.MerchantId = req.Base.MerchantId goodsModel.GoodsCode = req.Base.GoodsCode goodsModel.CreateTime = now goodsModel.UpdateTime = now goodsModel.CustomProperty = utils.SerializeStr(req.Base.CustomProperty) SaleStartTime, _ := utils.TimeParse("2006-01-02 15:04:05", req.Base.SaleStartTime) goodsModel.SaleStartTime = SaleStartTime //处理图片链接 req.Base.ImageListUrl = DealImg(c, req.Base.ImageList) goodsModel.ImageList = utils.SerializeStr(req.Base.ImageListUrl) goodsModel.Spe = utils.SerializeStr(req.Base.Spe) //处理图片链接 req.Base.SpeImagesUrl = DealImg(c, req.Base.SpeImages) goodsModel.SpeImages = utils.SerializeStr(req.Base.SpeImagesUrl) //处理图片链接 req.Base.DetailUrl = DealImg(c, req.Base.Detail) goodsModel.Detail = utils.SerializeStr(req.Base.DetailUrl) // detail为详情图列表 if req.Base.Service != nil { goodsModel.Service = utils.SerializeStr(req.Base.Service) // 支持的服务 } goodsModel.IsSpeImageInDetail = req.Base.IsSpeImageInDetail goodsModel.IsSpeImageOn = req.Base.IsSpeImageOn goodsModel.ShippingFeeType = int(req.Base.ShippingFeeType) goodsModel.ShippingFee = req.Base.ShippingFee goodsModel.ShippingTplId = req.Base.ShippingTplID if req.Base.GoodsId == "" { category, err := db2.GetCategoryById(svc2.MasterDb(c), utils.AnyToString(req.Base.CategoryId)) if err != nil { _ = sess.Rollback() return err } goodsId, err := MakeGoodsId(c, utils.AnyToString(category.McId), utils.AnyToString(req.Base.CategoryId), utils.AnyToString(goodsModel.MerchantId)) if err != nil { _ = sess.Rollback() return err } goodsModel.GoodsId = utils.StrToInt64(goodsId) merchant, err := db2.GetMerchantById(svc2.MasterDb(c), goodsModel.MerchantId) if err != nil { _ = sess.Rollback() return err } if merchant == nil { _ = sess.Rollback() return errors.New("未查询到对应供应商商家记录") } goodsModel.SaleState = 1 if merchant.IsOpenAuditGoods == 1 { goodsModel.SaleState = 0 } affect, err := sess.Insert(&goodsModel) if err != nil || affect != 1 { _ = sess.Rollback() return e.NewErr(e.ERR_DB_ORM, "插入商品失败") } } else { affect, err := sess.Where("goods_id=?", req.Base.GoodsId).AllCols().Update(&goodsModel) if err != nil || affect != 1 { return e.NewErr(e.ERR_DB_ORM, "更新商品失败") } } // 统计总库存 var stockAll int // sku保存 // 创建商品,则全部为插入 skuModelList := make([]*model.MallSku, 0, len(req.SkuList)) for key, item := range req.SkuList { stockAll += item.Stock skuModelList = append(skuModelList, &model.MallSku{ SkuId: utils.StrToInt64(utils.AnyToString(goodsModel.GoodsId) + utils.AnyToString(key)), GoodsId: goodsModel.GoodsId, SkuCode: item.SkuCode, Price: item.Price, LinePrice: item.LinePrice, Weight: item.Weight, Stock: item.Stock, Indexes: GetIndexesStr(&req.Base, item), Sku: utils.SerializeStr(&item.Sku), CreateTime: now, UpdateTime: now, SpecId: item.SpecID, CloudChainSkuId: item.CloudChainSkuId, CloudChainSkuImgUrl: item.CloudChainSkuImgUrl, }) } if req.Base.GoodsId != "" { // 如果是更新 先删除旧的再插入 _, err = sess.Delete(&model.MallSku{GoodsId: goodsModel.GoodsId}) if err != nil { return e.NewErr(e.ERR_DB_ORM, "规格更新失败") } } // 插入sku insert, err := sess.Insert(skuModelList) if err != nil { fmt.Println(err) logx.Warn(err) return err } if insert < 1 { return e.NewErr(e.ERR_DB_ORM, "插入商品规格失败") } minProfit := GetMinProfitRate(skuModelList) minPrice := GetMinPrice(skuModelList) // 更新总库存 _, err = sess.Where("goods_id=?", goodsModel.GoodsId).Update(&model.MallGoods{ Stock: stockAll, ProfitRate: utils.AnyToString(minProfit), Price: utils.AnyToString(minPrice), }) if err != nil { return e.NewErr(e.ERR_DB_ORM, "更新总库存失败") } err = sess.Commit() if err != nil { return e.NewErr(e.ERR_DB_ORM, "更新商品失败") } return nil } func MakeGoodsId(c *gin.Context, mcId, categoryId, merchantId string) (string, error) { var goodsId = mcId + utils.AnyToString(time.Now().UnixNano()/1e6) return goodsId, nil } func GetIndexesStr(baseGoods *md.MallBaseGoods, goodsSku *md.MallGoodsSku) string { spe := baseGoods.Spe sku := goodsSku.Sku result := "" for index, item := range sku { for _, itm := range spe { if item.Name == itm.Name { for i, v := range spe[index].Values { if v == item.Value { result = result + utils.IntToStr(i) + "-" } } } } } return strings.Trim(result, "-") }