Commit 9aa0e50d by mushishixian

样片接口

parent 3b61fdee
package controller
import (
"github.com/gin-gonic/gin"
"go_sku_server/pkg/common"
"go_sku_server/service"
)
//获取样片分类列表
func SampleClassList(ctx *gin.Context) {
var sampleClassService service.SampleClassService
classList, err := sampleClassService.GetSampleClassList()
if err != nil {
common.Output(ctx, 0, "success", err.Error())
return
}
common.Output(ctx, 0, "success", classList)
return
}
//获取样片列表
func SampleList(ctx *gin.Context) {
var sampleClassService service.SampleService
sampleList, err := sampleClassService.GetSampleList(ctx)
if err != nil {
common.Output(ctx, 0, "success", err.Error())
return
}
common.Output(ctx, 0, "success", sampleList)
return
}
......@@ -33,12 +33,12 @@ const goodsSliceCount = 10 //每多少个型号id开启一个协程
*/
func CommonController(ctx *gin.Context) map[string]interface{} {
GoodsIdStr := ctx.Request.FormValue("goods_id")
common.PrintDebugHeader(ctx) //开启debug调试
//抽取自营 或者联营 goods_id
zyService := service.ZiyingService{} //实例化自营查询
lyService := service.LyService{} //实例化自营查询
var goodsIdArr []string
//抽取自营 或者联营 goods_id
GoodsIdStr := ctx.Request.FormValue("goods_id")
if GoodsIdStr == "" {
goodsIdMap := ctx.PostFormMap("goods_id")
for _, goodsId := range goodsIdMap {
......@@ -52,7 +52,6 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
return nil
}
//wg := sync.WaitGroup{} //协程
ch := make(chan sync.Map) //管道
p := 0 //总共协程
zyGoodsId := make([]string, 0)
......@@ -95,11 +94,9 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
if len(lyGoodsId) > 0 {
common.PrintDebugHtml(ctx, "ly增加协程1004:")
common.PrintDebugHtml(ctx, zyGoodsId)
//wg.Add(1)
go lyService.LyGoodsDetail(ctx, lyGoodsId, ch)
p++
}
//wg.Wait()
//异步map最后转成map
temp := make(map[string]interface{})
......@@ -124,11 +121,6 @@ func Synchronization(ctx *gin.Context) {
res := CommonController(ctx)
common.Output(ctx, 0, "success", res)
}
func Synchronization1(ctx *gin.Context) {
res := CommonController(ctx)
common.Output(ctx, 0, "success", res)
}
/*
健康监测
......
......@@ -13,7 +13,7 @@ func PushMsg(listName string, data string) {
listName,
"",
"direct",
"amqp://guest:guest@192.168.2.232:5672/",
"amqp://guest:guest@192.168.1.252:5672/",
}
rabbitmq.Send(queueExchange, data)
}
\ No newline at end of file
package model
type Sample struct {
GoodsId int `json:"goods_id"`
Id int `json:"id"`
ClassId int `json:"class_id"`
MaxNumber int `json:"max_number"`
Quota int `json:"quota"`
ClassName string `xorm:"-" json:"class_name"`
GoodsInfo interface{} `xorm:"-" json:"goods_info"`
}
package model
type SampleClass struct {
Id int `json:"id"`
ClassName string `json:"class_name"`
ParentId int `json:"parent_id"`
Sort int `json:"sort"`
ClassIcon string `json:"class_icon"`
Status int `json:"status"`
}
......@@ -31,6 +31,10 @@ func InitRouter() *gin.Engine {
r.POST("SaveSku",controller.Error_Middleware(),controller.SaveSku)
r.POST("SkuEdit",controller.Error_Middleware(),controller.SkuEdit)
//样片相关
r.POST("/self/sample/class/list",controller.SampleClassList)
r.POST("/self/sample/list",controller.SampleList)
return r
}
......@@ -35,16 +35,6 @@ func (ls *LyService) LyGoodsDetail(ctx *gin.Context, goodsIds []string, ch chan
redisConn.Close()
}()
fast := ctx.Request.FormValue("power[fast]")
//isNewCustomer := ctx.Request.FormValue("power[newCustomer]")
//power := Power{
// UserId: ctx.Request.FormValue("power[user_id]"),
// Mobile: ctx.Request.FormValue("power[mobile]"),
// Email: ctx.Request.FormValue("power[email]"),
// Member: ctx.Request.FormValue("power[member]"),
// Invoice: ctx.Request.FormValue("power[invoice]"),
// SpecialInvoice: ctx.Request.FormValue("power[special_invoice]"),
// VerifyBlacklist: ctx.Request.FormValue("power[verify_blacklist]"),
//}
//批量获取商品详情
skuArr := gredis.Hmget("default_r", "sku", goodsIds)
//为了性能着想,这边也先去批量获取spu的信息
......
......@@ -45,51 +45,52 @@ sku基本数据增加和修改
Pdf int `json:"pdf" `
SpuBrief int `json:"spu_brief" `
Attrs int `json:"attrs" `
*/
*/
var skuCache SkuCacheService
func (S *LySaveService)SaveSku(lySaveRequest saveModel.LySaveRequest,ctx *gin.Context) (error,string) {
lySkuEntity:=lySaveRequest.ToLySkuEntity()//sku实体
func (S *LySaveService) SaveSku(lySaveRequest saveModel.LySaveRequest, ctx *gin.Context) (error, string) {
lySkuEntity := lySaveRequest.ToLySkuEntity() //sku实体
//供应商处理(处理后,将[新增/修改sku]所需供应商相关字段 赋值给 &lySkuEntity)
err:=S.supplierHandle(lySaveRequest.SupplierId,lySkuEntity.Canal,&lySkuEntity)
if(err!=nil){
return e.NewApiError("供应商处理失败"+err.Error()),""
err := S.supplierHandle(lySaveRequest.SupplierId, lySkuEntity.Canal, &lySkuEntity)
if err != nil {
return e.NewApiError("供应商处理失败" + err.Error()), ""
}
//阶梯价格处理
err=S.ladderPriceHandle(lySaveRequest.LadderPrice,&lySkuEntity)
if(err!=nil){
return e.NewApiError("阶梯价格处理失败"+err.Error()),""
err = S.ladderPriceHandle(lySaveRequest.LadderPrice, &lySkuEntity)
if err != nil {
return e.NewApiError("阶梯价格处理失败" + err.Error()), ""
}
//上下架状态处理
S.statusHandle(&lySkuEntity)
//spu处理(请求spu_server saveSpu接口,将spuId赋值给 &lySkuEntity)
lySpuRequest:=lySaveRequest.ToLySpuRequest()
err=S.spuHandle(lySpuRequest,&lySkuEntity)
if(err!=nil){
return err,""
lySpuRequest := lySaveRequest.ToLySpuRequest()
err = S.spuHandle(lySpuRequest, &lySkuEntity)
if err != nil {
return err, ""
}
//mongoDb 获取sku 唯一信息
err,mongoSkuInfo:=skuCache.MongoGetOnlySkuInfo(lySkuEntity.SpuId,lySkuEntity.SupplierId,lySkuEntity.Moq,lySkuEntity.Encoded,lySkuEntity.Canal)
if(err!=nil){
return e.NewApiError("mongo 获取sku唯一信息失败"+err.Error()),""
err, mongoSkuInfo := skuCache.MongoGetOnlySkuInfo(lySkuEntity.SpuId, lySkuEntity.SupplierId, lySkuEntity.Moq, lySkuEntity.Encoded, lySkuEntity.Canal)
if err != nil {
return e.NewApiError("mongo 获取sku唯一信息失败" + err.Error()), ""
}
if(mongoSkuInfo.GoodsId!=0){//更新
if mongoSkuInfo.GoodsId != 0 { //更新
lySkuEntity.GoodsId=gconv.String(mongoSkuInfo.GoodsId)
err:=S.update(lySkuEntity,lySaveRequest)
if(err!=nil){
return e.NewApiError("skuSave 修改sku失败"+err.Error()),""
lySkuEntity.GoodsId = gconv.String(mongoSkuInfo.GoodsId)
err := S.update(lySkuEntity, lySaveRequest)
if err != nil {
return e.NewApiError("skuSave 修改sku失败" + err.Error()), ""
}
return nil,lySkuEntity.GoodsId
}else{//插入sku
err,skuId:=S.insert(lySkuEntity,lySaveRequest)
if(err!=nil){
return e.NewApiError("skuSave insert sku失败"+err.Error()),""
return nil, lySkuEntity.GoodsId
} else { //插入sku
err, skuId := S.insert(lySkuEntity, lySaveRequest)
if err != nil {
return e.NewApiError("skuSave insert sku失败" + err.Error()), ""
}
logger.Select("lysku_save").Info("新增完成:brand_name:"+lySaveRequest.BrandName+";sku_id:"+skuId+";good_name:"+lySaveRequest.GoodsName)
logger.Select("lysku_save").Info("新增完成:brand_name:" + lySaveRequest.BrandName + ";sku_id:" + skuId + ";good_name:" + lySaveRequest.GoodsName)
return nil, skuId
}
......@@ -100,41 +101,41 @@ func (S *LySaveService)SaveSku(lySaveRequest saveModel.LySaveRequest,ctx *gin.Co
1.判断供应商是否存在,是否被禁用
2.如果供应商为专卖,参数 cannal(供应商编码)是必传的
3.得到 新增sku所需的 TypeId 和 Encoded(渠道员内部编码)
*/
func (S *LySaveService) supplierHandle(SupplierId int,Canal string,lySkuEntity *saveModel.LySkuEntity) (error) {
*/
func (S *LySaveService) supplierHandle(SupplierId int, Canal string, lySkuEntity *saveModel.LySkuEntity) error {
lySupplier:= LySupplier{}
lySupplier := LySupplier{}
has,err,supplierInfo:=lySupplier.GetSupplirInfo(SupplierId)
if(err!=nil){
return e.NewApiError("获取基石供应商详情失败"+err.Error())
has, err, supplierInfo := lySupplier.GetSupplirInfo(SupplierId)
if err != nil {
return e.NewApiError("获取基石供应商详情失败" + err.Error())
}
if(!has){
fmt.Sprintf("没有在基石获取到此供应商,供应商ID为:%s",SupplierId)
if !has {
fmt.Sprintf("没有在基石获取到此供应商,供应商ID为:%s", SupplierId)
}
if(supplierInfo.Status!=1){
if supplierInfo.Status != 1 {
return e.NewApiError("供应商被禁用")
}
//专卖处理(供应商系统)
if(supplierInfo.TypeId==2){
if(Canal==""){
if supplierInfo.TypeId == 2 {
if Canal == "" {
return e.NewApiError("专卖 cannal参数为必传")
}
has,err,poolSupplierInfo:=lySupplier.GetPoolSupplirInfo(Canal)
has, err, poolSupplierInfo := lySupplier.GetPoolSupplirInfo(Canal)
if(err!=nil){
return e.NewApiError("获取联营供应商详情失败"+err.Error())
if err != nil {
return e.NewApiError("获取联营供应商详情失败" + err.Error())
}
if(!has){
if !has {
errmsg:=fmt.Sprintf("没有获取到渠道%s的内部编码",Canal)
errmsg := fmt.Sprintf("没有获取到渠道%s的内部编码", Canal)
return e.NewApiError(errmsg)
}
lySkuEntity.Encoded=poolSupplierInfo.ChannelUid//渠道开发员 内部编码赋值给sku
lySkuEntity.Encoded = poolSupplierInfo.ChannelUid //渠道开发员 内部编码赋值给sku
}
lySkuEntity.GoodsType=supplierInfo.TypeId
lySkuEntity.GoodsType = supplierInfo.TypeId
return nil
}
......@@ -144,33 +145,32 @@ func (S *LySaveService) supplierHandle(SupplierId int,Canal string,lySkuEntity *
1.对阶梯价格排序
2.获取 ladderPrice
3.获取最便宜的价格
*/
func (S *LySaveService) ladderPriceHandle(ladderPrice []model.LadderPrice,lySkuEntity *saveModel.LySkuEntity) error {
*/
func (S *LySaveService) ladderPriceHandle(ladderPrice []model.LadderPrice, lySkuEntity *saveModel.LySkuEntity) error {
num:=len(ladderPrice)
num := len(ladderPrice)
if(len(ladderPrice)>0){//有传阶梯价
if len(ladderPrice) > 0 { //有传阶梯价
//获取最便宜的价格
sort.Sort(sorter.LadderPriceSorter(ladderPrice))//按照购买数量,小到大排序,数量越大优惠越多,所以[num-1]是最便宜的
sort.Sort(sorter.LadderPriceSorter(ladderPrice)) //按照购买数量,小到大排序,数量越大优惠越多,所以[num-1]是最便宜的
if(ladderPrice[num-1].PriceUs>=0){//如果有最低美元价,就直接读最低美元价
lySkuEntity.SinglePrice=ladderPrice[num-1].PriceUs//获取最便宜的价钱
}else{//没有美元价,就将最低人民币折算成美元
lySkuEntity.SinglePrice=php2go.Round(ladderPrice[num-1].PriceCn/6.8)
if ladderPrice[num-1].PriceUs >= 0 { //如果有最低美元价,就直接读最低美元价
lySkuEntity.SinglePrice = ladderPrice[num-1].PriceUs //获取最便宜的价钱
} else { //没有美元价,就将最低人民币折算成美元
lySkuEntity.SinglePrice = php2go.Round(ladderPrice[num-1].PriceCn / 6.8)
}
//将阶梯json字符串给到sku实体里,sku只需要字符串阶梯 存数据库
priceBytes,err:=json.Marshal(ladderPrice)
if(err!=nil){
return e.NewApiError("阶梯价格json化报错"+err.Error())
}else{
lySkuEntity.LadderPrice=string(priceBytes)
priceBytes, err := json.Marshal(ladderPrice)
if err != nil {
return e.NewApiError("阶梯价格json化报错" + err.Error())
} else {
lySkuEntity.LadderPrice = string(priceBytes)
} //状态处理
}
return nil
}
/**
spu处理(内部方法)
1.调用spu_server saveSpu接口,获取到spuId
......@@ -182,20 +182,20 @@ spu处理(内部方法)
| data | | 返回的data |
*/
func (S *LySaveService) spuHandle(lySpuRequest saveModel.LySpuRequest,lySkuEntity *saveModel.LySkuEntity) (error) {
func (S *LySaveService) spuHandle(lySpuRequest saveModel.LySpuRequest, lySkuEntity *saveModel.LySkuEntity) error {
lySpuResponse:=saveModel.LySpuResponse{}
lySpuResponse := saveModel.LySpuResponse{}
err:=gout.POST(config.Get("spu_server.api_domain").String()+"/saveSpu")/*.Debug(true)*/.SetJSON(&lySpuRequest).BindJSON(&lySpuResponse).Do()
err := gout.POST(config.Get("spu_server.api_domain").String() + "/saveSpu") /*.Debug(true)*/ .SetJSON(&lySpuRequest).BindJSON(&lySpuResponse).Do()
//err:=gout.POST("http://192.168.1.237:8005/saveSpu").Debug(false).SetJSON(&lySpuRequest).BindJSON(&lySpuResponse).Do()
if(err!=nil){
return e.NewApiError("调用spu server saveSpu接口报错"+err.Error())
if err != nil {
return e.NewApiError("调用spu server saveSpu接口报错" + err.Error())
}
if(lySpuResponse.ErrorCode==0){
lySkuEntity.SpuId=lySpuResponse.Data.SpuId
}else{
return e.NewApiError("sku Throw out"+lySpuResponse.ErrMsg)
if lySpuResponse.ErrorCode == 0 {
lySkuEntity.SpuId = lySpuResponse.Data.SpuId
} else {
return e.NewApiError("sku Throw out" + lySpuResponse.ErrMsg)
}
return nil
}
......@@ -209,58 +209,59 @@ func (S *LySaveService) spuHandle(lySpuRequest saveModel.LySpuRequest,lySkuEntit
处理流程
满足 字段 moq stock ladder_price都有值 ,并且 moq < =stock ; 那么 sku状态 就是 审核通过(status=1)
否则 就是下架状态(status=3)
*/
func (S *LySaveService) statusHandle(lySkuEntity *saveModel.LySkuEntity) {
*/
func (S *LySaveService) statusHandle(lySkuEntity *saveModel.LySkuEntity) {
lySkuEntity.GoodsStatus=1
lySkuEntity.GoodsStatus = 1
if(lySkuEntity.LadderPrice==""){
lySkuEntity.GoodsStatus=3//下架
if lySkuEntity.LadderPrice == "" {
lySkuEntity.GoodsStatus = 3 //下架
}
if(lySkuEntity.Moq==0 || lySkuEntity.Stock==0 || lySkuEntity.Moq>lySkuEntity.Stock){
lySkuEntity.GoodsStatus=3//下架
if lySkuEntity.Moq == 0 || lySkuEntity.Stock == 0 || lySkuEntity.Moq > lySkuEntity.Stock {
lySkuEntity.GoodsStatus = 3 //下架
}
}
//更新
func (S *LySaveService) update(lySkuEntity saveModel.LySkuEntity,lySaveRequest saveModel.LySaveRequest)error{
db,table:=common.ResolveSpu(lySkuEntity.GoodsId)//解析skuID,返回对应的表和库,应该在生成skuID的时候返回表和库
func (S *LySaveService) update(lySkuEntity saveModel.LySkuEntity, lySaveRequest saveModel.LySaveRequest) error {
db, table := common.ResolveSpu(lySkuEntity.GoodsId) //解析skuID,返回对应的表和库,应该在生成skuID的时候返回表和库
//修改数据库
affected, err := mysql.Conn(db).Table(table).Where("goods_id=?",lySkuEntity.GoodsId).Update(lySkuEntity)
if (err != nil) {
return e.NewApiError("修改sku mysql数据失败 msg:"+err.Error())
affected, err := mysql.Conn(db).Table(table).Where("goods_id=?", lySkuEntity.GoodsId).Update(lySkuEntity)
if err != nil {
return e.NewApiError("修改sku mysql数据失败 msg:" + err.Error())
}
if(affected<=0){//没有什么可以修改的,直接完成就好了
if affected <= 0 { //没有什么可以修改的,直接完成就好了
fmt.Println("没什么可以修改的")
logger.Select("lysku_save").Info("不需要修改:brand_name:"+lySaveRequest.BrandName+";sku_id:"+lySkuEntity.GoodsId+";good_name:"+lySaveRequest.GoodsName)
logger.Select("lysku_save").Info("不需要修改:brand_name:" + lySaveRequest.BrandName + ";sku_id:" + lySkuEntity.GoodsId + ";good_name:" + lySaveRequest.GoodsName)
return nil
}else{
err=S.skuCacheSave(false,lySkuEntity.GoodsId,lySkuEntity,lySaveRequest)
if (err != nil) {
logger.Select("lysku_save").Info("修改完成:brand_name:"+lySaveRequest.BrandName+";sku_id:"+lySkuEntity.GoodsId+";good_name:"+lySaveRequest.GoodsName)
return e.NewApiError("缓存处理失败"+err.Error())
} else {
err = S.skuCacheSave(false, lySkuEntity.GoodsId, lySkuEntity, lySaveRequest)
if err != nil {
logger.Select("lysku_save").Info("修改完成:brand_name:" + lySaveRequest.BrandName + ";sku_id:" + lySkuEntity.GoodsId + ";good_name:" + lySaveRequest.GoodsName)
return e.NewApiError("缓存处理失败" + err.Error())
}
}
return nil
}
//插入
func (S *LySaveService) insert(lySkuEntity saveModel.LySkuEntity,lySaveRequest saveModel.LySaveRequest) (error,string) {
func (S *LySaveService) insert(lySkuEntity saveModel.LySkuEntity, lySaveRequest saveModel.LySaveRequest) (error, string) {
skuId:=common.StructureNumber("sku")//生成skuID
lySkuEntity.GoodsId=skuId
db,table:=common.ResolveSpu(lySkuEntity.GoodsId)//解析skuID,返回对应的表和库,应该在生成skuID的时候返回表和库
skuId := common.StructureNumber("sku") //生成skuID
lySkuEntity.GoodsId = skuId
db, table := common.ResolveSpu(lySkuEntity.GoodsId) //解析skuID,返回对应的表和库,应该在生成skuID的时候返回表和库
//插入到数据库
_, err := mysql.Conn(db).Table(table).Insert(lySkuEntity);
if (err != nil) {
return e.NewApiError("sku插入数据库失败"+err.Error()),""
_, err := mysql.Conn(db).Table(table).Insert(lySkuEntity)
if err != nil {
return e.NewApiError("sku插入数据库失败" + err.Error()), ""
}
err=S.skuCacheSave(true,skuId,lySkuEntity,lySaveRequest)
if(err!=nil){
return e.NewApiError("缓存处理失败"+err.Error()),""
err = S.skuCacheSave(true, skuId, lySkuEntity, lySaveRequest)
if err != nil {
return e.NewApiError("缓存处理失败" + err.Error()), ""
}
return nil,skuId
return nil, skuId
}
/**
......@@ -268,26 +269,26 @@ func (S *LySaveService) insert(lySkuEntity saveModel.LySkuEntity,lySaveRequest s
1.更新 redis skuinfo (1.新增直接插入,2.修改需要将老的redis sku数据合并新的)
2.插入mongoDB sku唯一(修改不需要动)
3.推送(就是插入redis list update_list_sku)
*/
func (S *LySaveService) skuCacheSave(isAdd bool,skuId string,lySkuEntity saveModel.LySkuEntity,lySaveRequest saveModel.LySaveRequest)error{
*/
func (S *LySaveService) skuCacheSave(isAdd bool, skuId string, lySkuEntity saveModel.LySkuEntity, lySaveRequest saveModel.LySaveRequest) error {
//插入redis,redis修改和新增代码量有点大,单独封装一个函数
err:=S.saveRedisSkuInfo(isAdd,skuId,lySkuEntity,lySaveRequest)
if(err!=nil){
return e.NewApiError("插入redis失败"+err.Error())
err := S.saveRedisSkuInfo(isAdd, skuId, lySkuEntity, lySaveRequest)
if err != nil {
return e.NewApiError("插入redis失败" + err.Error())
}
if(isAdd){
if isAdd {
//插入到mongo
skuMongo:=lySkuEntity.ToMongoSku()
err=skuCache.MongoInsertOnlySkuInfo(skuMongo)
if(err!=nil){
return e.NewApiError("插入redis失败"+err.Error())
skuMongo := lySkuEntity.ToMongoSku()
err = skuCache.MongoInsertOnlySkuInfo(skuMongo)
if err != nil {
return e.NewApiError("插入redis失败" + err.Error())
}
}
//实时推送(插入到 redis list update_list_sku )
err=skuCache.RedisPushEsList(skuId)
if(err!=nil){
return e.NewApiError("实时推送失败"+err.Error())
err = skuCache.RedisPushEsList(skuId)
if err != nil {
return e.NewApiError("实时推送失败" + err.Error())
}
return nil
}
......@@ -300,58 +301,59 @@ func (S *LySaveService) skuCacheSave(isAdd bool,skuId string,lySkuEntity saveMod
2.修改
读取之前(老的)的redis数据,跟新的redisSku合并
合并规则:需要修改的,覆盖之前的,不需要修改的保持原样
*/
func (S *LySaveService) saveRedisSkuInfo(isAdd bool,skuId string,lySkuEntity saveModel.LySkuEntity,lySaveRequest saveModel.LySaveRequest) error {
redisSkuInfo:=lySkuEntity.ToRedisSku()//组装需要更新的redisSku数据
redisSkuInfo.GoodsImages=lySaveRequest.GoodsImages
redisSkuInfo.Canal=lySaveRequest.Canal
redisSkuInfo.UpdateTime=int(time.Now().Unix())
redisSkuInfo.LadderPrice=lySaveRequest.LadderPrice//LadderPrice 如果已经是字符串,json处理会有斜划线,所以再赋值一次
if(isAdd){
oldByte,err:=json.Marshal(redisSkuInfo)
if(err!=nil){
*/
func (S *LySaveService) saveRedisSkuInfo(isAdd bool, skuId string, lySkuEntity saveModel.LySkuEntity, lySaveRequest saveModel.LySaveRequest) error {
redisSkuInfo := lySkuEntity.ToRedisSku() //组装需要更新的redisSku数据
redisSkuInfo.GoodsImages = lySaveRequest.GoodsImages
redisSkuInfo.Canal = lySaveRequest.Canal
redisSkuInfo.UpdateTime = int(time.Now().Unix())
redisSkuInfo.LadderPrice = lySaveRequest.LadderPrice //LadderPrice 如果已经是字符串,json处理会有斜划线,所以再赋值一次
if isAdd {
oldByte, err := json.Marshal(redisSkuInfo)
if err != nil {
return nil
}
return skuCache.RedisInsertSkuInfo(skuId,string(oldByte))
}else{
return skuCache.RedisInsertSkuInfo(skuId, string(oldByte))
} else {
//将老的redis的数据转成map
var oldSkuInfoMap map[string]interface{}
oldSkuInfoStr,err:=skuCache.RedisGetSkuInfo(skuId)//获取老的sku数据
json.Unmarshal([]byte(oldSkuInfoStr),&oldSkuInfoMap)
if(err!=nil){
oldSkuInfoStr, err := skuCache.RedisGetSkuInfo(skuId) //获取老的sku数据
json.Unmarshal([]byte(oldSkuInfoStr), &oldSkuInfoMap)
if err != nil {
return nil
}
//is_expire 给清理掉
if _, ok := oldSkuInfoMap["is_expire"];ok{
delete(oldSkuInfoMap,"is_expire")
if _, ok := oldSkuInfoMap["is_expire"]; ok {
delete(oldSkuInfoMap, "is_expire")
}
//合并,得到新的map
err,newMap:=S.structMerageMap(redisSkuInfo,oldSkuInfoMap)
if(err!=nil){
return e.NewApiError("结构和map合并失败"+err.Error())
err, newMap := S.structMergeMap(redisSkuInfo, oldSkuInfoMap)
if err != nil {
return e.NewApiError("结构和map合并失败" + err.Error())
}
//转化成json字符串
newMapbytes,err:=json.Marshal(newMap)
if(err!=nil){
newMapBytes, err := json.Marshal(newMap)
if err != nil {
return err
}
//插入redisSku
err=skuCache.RedisInsertSkuInfo(skuId,string(newMapbytes))
if(err!=nil){
err = skuCache.RedisInsertSkuInfo(skuId, string(newMapBytes))
if err != nil {
return nil
}
}
return nil
}
/**
struct 跟map Map合并,返回一个新的map(后续可以整理成公共函数)
*/
func (S *LySaveService) structMerageMap(redisSkuInfo model.LySkuRedisInfo,oldSkuInfoMap map[string]interface{})(error,map[string]interface{}) {
func (S *LySaveService) structMergeMap(redisSkuInfo model.LySkuRedisInfo, oldSkuInfoMap map[string]interface{}) (error, map[string]interface{}) {
//将新的redisSku数据struct 和 老的redis的数据map 合并成map并转换成json返回
GetValue:= func(fieldValue reflect.Value) interface{}{
GetValue := func(fieldValue reflect.Value) interface{} {
switch fieldValue.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
return fieldValue.Int()
......@@ -370,63 +372,63 @@ func (S *LySaveService) structMerageMap(redisSkuInfo model.LySkuRedisInfo,oldSk
}
//组装需要更新的redisSku数据 struct
var newMap =make(map[string]interface{})
v:=reflect.ValueOf(redisSkuInfo)
t:=reflect.TypeOf(redisSkuInfo)
for i:=0;i<v.NumField();i++ {
name:=t.Field(i).Tag.Get("json")
fieldValue:=v.Field(i)
var newMap = make(map[string]interface{})
v := reflect.ValueOf(redisSkuInfo)
t := reflect.TypeOf(redisSkuInfo)
for i := 0; i < v.NumField(); i++ {
name := t.Field(i).Tag.Get("json")
fieldValue := v.Field(i)
//name:=v.Type().Name()
_, ok := oldSkuInfoMap[name];
if(v.Field(i).IsZero() && ok){// struct 有些字段为0值,还是要用老的redis的数据
newMap[name]=oldSkuInfoMap[name]
}else{
if(name=="ladder_price"){
newMap[name]=redisSkuInfo.LadderPrice //ladder_price 单独处理
}else{
mapValue:=GetValue(fieldValue)
newMap[name]=mapValue
_, ok := oldSkuInfoMap[name]
if v.Field(i).IsZero() && ok { // struct 有些字段为0值,还是要用老的redis的数据
newMap[name] = oldSkuInfoMap[name]
} else {
if name == "ladder_price" {
newMap[name] = redisSkuInfo.LadderPrice //ladder_price 单独处理
} else {
mapValue := GetValue(fieldValue)
newMap[name] = mapValue
}
}
delete(oldSkuInfoMap,name)//删除老的数据已经合并的字段
delete(oldSkuInfoMap, name) //删除老的数据已经合并的字段
}
//将老数据独有的字段,放进newMap
if(len(oldSkuInfoMap)>0){
for oldk,oldv:=range oldSkuInfoMap{
newMap[oldk]=oldv
if len(oldSkuInfoMap) > 0 {
for oldk, oldv := range oldSkuInfoMap {
newMap[oldk] = oldv
}
}
return nil,newMap
return nil, newMap
}
/**
修改
先写的SkuSave ,SkuEdit 基本是调用 SkuSave 之前写好的方法
*/
func (S *LySaveService)SkuEdit(lyEditRequest saveModel.LyEditRequest) (error,string){
*/
func (S *LySaveService) SkuEdit(lyEditRequest saveModel.LyEditRequest) (error, string) {
lySkuEntity:=lyEditRequest.ToLySkuEntity()//sku实体
lySkuEntity.GoodsId=lyEditRequest.GoodsId
lySkuEntity := lyEditRequest.ToLySkuEntity() //sku实体
lySkuEntity.GoodsId = lyEditRequest.GoodsId
lySaveRequest:=lyEditRequest.ToLySaveRequest()//转换成lySaveRequest 因为公用 savesku封装的的方法,公用方法需要传lySaveRequest(后续参数改成接口)
lySaveRequest := lyEditRequest.ToLySaveRequest() //转换成lySaveRequest 因为公用 savesku封装的的方法,公用方法需要传lySaveRequest(后续参数改成接口)
//阶梯价格处理
err:=S.ladderPriceHandle(lySaveRequest.LadderPrice,&lySkuEntity)
if(err!=nil){
return e.NewApiError("SkuEdit 阶梯价格处理失败"+err.Error()),""
err := S.ladderPriceHandle(lySaveRequest.LadderPrice, &lySkuEntity)
if err != nil {
return e.NewApiError("SkuEdit 阶梯价格处理失败" + err.Error()), ""
}
oldRedisStr,err:=skuCache.RedisGetSkuInfo(lyEditRequest.GoodsId)
if(err!=nil){
return e.NewApiError("修改sku:查询redis sku失败"+err.Error()),""
oldRedisStr, err := skuCache.RedisGetSkuInfo(lyEditRequest.GoodsId)
if err != nil {
return e.NewApiError("修改sku:查询redis sku失败" + err.Error()), ""
}
if(oldRedisStr==""){//判断是否存在
return e.NewApiError("sku不存在,skuID:"+lyEditRequest.GoodsId+err.Error()),""
if oldRedisStr == "" { //判断是否存在
return e.NewApiError("sku不存在,skuID:" + lyEditRequest.GoodsId + err.Error()), ""
}
err=S.update(lySkuEntity,lySaveRequest)
if(err!=nil){
return e.NewApiError("SkuEdit 修改sku失败"+err.Error()),""
err = S.update(lySkuEntity, lySaveRequest)
if err != nil {
return e.NewApiError("SkuEdit 修改sku失败" + err.Error()), ""
}
return nil,lySkuEntity.GoodsId
return nil, lySkuEntity.GoodsId
}
package service
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-xorm/xorm"
"github.com/gogf/gf/util/gconv"
"go_sku_server/model"
"go_sku_server/pkg/mysql"
"sync"
"time"
)
type SampleService struct {
}
//获取分类列表
func (ss *SampleService) GetSampleList(ctx *gin.Context) (data map[string]interface{}, err error) {
id := gconv.Int(ctx.Request.FormValue("id"))
goodsId := gconv.Int(ctx.Request.FormValue("goods_id"))
classId := gconv.Int(ctx.Request.FormValue("class_id"))
page := gconv.Int(ctx.Request.FormValue("page"))
limit := gconv.Int(ctx.Request.FormValue("limit"))
if limit == 0 {
limit = 10
}
var start int
if page == 0 || page == 1 {
page = 1
start = 0
} else {
start = (page - 1) * limit
}
query := mysql.Conn("liexin_data").Table("lie_sample").Where("status = ?", 1)
if id != 0 {
query.Where("id = ?", id)
}
if goodsId != 0 {
query.Where("goods_id = ?", goodsId)
}
if classId != 0 {
query.Where("class_id = ?", classId)
}
var sampleList []model.Sample
query.OrderBy("update_time DESC").Limit(limit, start)
err = query.Find(&sampleList)
if err != nil && err != xorm.ErrNotExist {
return nil, err
}
//构建和之前接口的数据一样的格式,有点操蛋
data = make(map[string]interface{})
goodsMap := make(map[string]interface{})
var goodsIdsSlice []string
sampleGoodsMap := make(map[string]model.Sample)
for _, sample := range sampleList {
goodsIdStr := gconv.String(sample.GoodsId)
goodsIdsSlice = append(goodsIdsSlice, goodsIdStr)
}
goodsMap = ss.GetGoods(ctx, goodsIdsSlice)
for _, sample := range sampleList {
classService := SampleClassService{}
class, _ := classService.GetSampleClass(sample.ClassId)
sample.ClassName = class.ClassName
sample.GoodsInfo = goodsMap[gconv.String(sample.GoodsId)]
sampleGoodsMap[gconv.String(sample.GoodsId)] = sample
}
data["data"] = sampleGoodsMap
return data, err
}
func (ss *SampleService) GetGoods(ctx *gin.Context, goodsIds []string) map[string]interface{} {
//抽取自营 或者联营 goods_id
zyService := ZiyingService{} //实例化自营查询
lyService := LyService{} //实例化自营查询
ch := make(chan sync.Map) //管道
p := 0 //总共协程
zyGoodsId := make([]string, 0)
lyGoodsId := make([]string, 0)
for _, goodsId := range goodsIds {
if goodsId == "" {
continue
}
if len(goodsId) < 19 { //自营
zyGoodsId = append(zyGoodsId, goodsId)
if len(zyGoodsId) >= 10 {
go zyService.ZyGoodsDetail(ctx, zyGoodsId, ch)
zyGoodsId = zyGoodsId[:0:0]
p++
}
} else { //联营
lyGoodsId = append(lyGoodsId, goodsId)
if len(lyGoodsId) >= 10 {
go lyService.LyGoodsDetail(ctx, lyGoodsId, ch)
lyGoodsId = lyGoodsId[:0:0]
p++
}
}
}
if len(zyGoodsId) > 0 {
go zyService.ZyGoodsDetail(ctx, zyGoodsId, ch)
p++
}
if len(lyGoodsId) > 0 {
go lyService.LyGoodsDetail(ctx, lyGoodsId, ch)
p++
}
//异步map最后转成map
temp := make(map[string]interface{})
for i := 0; i < p; i++ {
select {
case GoodsRes := <-ch:
GoodsRes.Range(func(k, v interface{}) bool {
s, _ := k.(string)
temp[s] = v
return true
})
case <-time.After(time.Second * 20):
fmt.Println("协程超时", "sku", 1)
}
}
return temp
}
package service
import (
"encoding/json"
"github.com/gogf/gf/util/gconv"
"github.com/gomodule/redigo/redis"
"github.com/tidwall/gjson"
"go_sku_server/model"
"go_sku_server/pkg/gredis"
"go_sku_server/pkg/mysql"
)
type SampleClassService struct {
}
//获取分类列表
func (ls *SampleClassService) GetSampleClassList() (classList []model.SampleClass, err error) {
redisCon := gredis.Conn("default_r")
defer redisCon.Close()
//var class model.SampleClass
classListStr, err := redis.String(redisCon.Do("GET", "Self_sample_class_list_web"))
if classListStr == "" {
err = mysql.Conn("liexin_data").Table("lie_sample_class").
Select("id,class_name,class_icon,parent_id,status,sort").
Where("status = ?", 1).OrderBy("sort DESC").Find(&classList)
if err != nil {
return
}
str, err := json.Marshal(&classList)
if err != nil {
return nil, err
}
_, err = redisCon.Do("SET", "Self_sample_class_list_web", str)
if err != nil {
return nil, err
}
_, err = redisCon.Do("EXPIRE", "Self_sample_class_list_web", 60)
if err != nil {
return nil, err
}
} else {
err := json.Unmarshal([]byte(classListStr), &classList)
if err != nil {
return nil, err
}
}
return classList, err
}
//获取分类信息
func (ls *SampleClassService) GetSampleClass(classId int) (class model.SampleClass, err error) {
redisCon := gredis.Conn("default_r")
defer redisCon.Close()
classStr, err := redis.String(redisCon.Do("HGET", "Self_sample_class_list", classId))
if err != nil {
return
}
class.Id = gconv.Int(classId)
class.ClassName = gjson.Get(classStr, "class_name").String()
class.Status = int(gjson.Get(classStr, "status").Int())
class.Sort = int(gjson.Get(classStr, "sort").Int())
return class, err
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment