|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444 |
- package goods
-
- import (
- "applet/app/admin/enum"
- "applet/app/admin/md"
- "applet/app/db"
- "applet/app/db/model"
- "applet/app/e"
- "applet/app/svc"
- "applet/app/utils"
- "applet/app/utils/logx"
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/jinzhu/copier"
- "github.com/pkg/errors"
- "reflect"
- "strings"
- "time"
- )
-
- // 处理图片
- func DealImg(c *gin.Context, imageListUrl []string) []string {
- //七牛云配置
- scheme, host, subDomain, moreSubDomain := svc.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
- }
-
- // AddMallGoods 添加、编辑商品
- func AddMallGoods(c *gin.Context, req *md.AddGoodsReq) error {
- if req.Base.GoodsId != "" {
- _, has, err := db.GetComm(db.Db, &model.Goods{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 := db.Db.NewSession()
- defer func() {
- _ = sess.Close()
- }()
- err := sess.Begin()
- if err != nil {
- return e.NewErr(e.ERR_DB_ORM, err.Error())
- }
-
- // 基本信息保存
- var goodsModel model.Goods
- 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.SaleState = int(enum.MallGoodsSaleStateOnShelf)
- goodsModel.CreateAt = now.Format("2006-01-02 03:04:05")
- goodsModel.UpdateAt = now.Format("2006-01-02 03:04:05")
- //处理图片链接
- req.Base.ImageListUrl = DealImg(c, req.Base.ImageList)
- goodsModel.ImageList = utils.SerializeStr(req.Base.ImageListUrl)
- goodsModel.Spe = utils.SerializeStr(req.Base.Spe)
- //处理图片链接
- req.Base.DetailUrl = DealImg(c, req.Base.Detail)
- goodsModel.Detail = utils.SerializeStr(req.Base.DetailUrl) // detail为详情图列表
-
- if req.Base.GoodsId == "" {
- category, err := db.GetCategoryById(db.Db, utils.AnyToString(req.Base.CategoryId))
- if err != nil {
- _ = sess.Rollback()
- return err
- }
- goodsId, err := MakeGoodsId(c, utils.AnyToString(category.Id))
- if err != nil {
- _ = sess.Rollback()
- return err
- }
- goodsModel.GoodsId = utils.StrToInt64(goodsId)
- 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, "更新商品失败")
- }
- }
-
- // 统计总库存
-
- // sku保存
- // 创建商品,则全部为插入
- skuModelList := make([]*model.Sku, 0, len(req.SkuList))
- for key, item := range req.SkuList {
- skuModelList = append(skuModelList, &model.Sku{
- SkuId: utils.StrToInt64(utils.AnyToString(goodsModel.GoodsId) + utils.AnyToString(key)),
- GoodsId: goodsModel.GoodsId,
- SkuCode: item.SkuCode,
- Price: item.Price,
- Indexes: GetIndexesStr(&req.Base, item),
- Sku: utils.SerializeStr(&item.Sku),
- CreateAt: now.Format("2006-01-02 03:04:05"),
- UpdateAt: now.Format("2006-01-02 03:04:05"),
- })
- }
- if req.Base.GoodsId != "" {
- // 如果是更新 先删除旧的再插入
- _, err = sess.Delete(&model.Sku{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, "插入商品规格失败")
- }
-
- err = sess.Commit()
- if err != nil {
- return e.NewErr(e.ERR_DB_ORM, "更新商品失败")
- }
- return nil
- }
-
- // EditMallGoods 編辑商品
- func EditMallGoods(c *gin.Context, req *md.AddGoodsReq) error {
- _, has, err := db.GetComm(db.Db, &model.Goods{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 := db.Db.NewSession()
- defer func() {
- _ = sess.Close()
- }()
- err = sess.Begin()
- if err != nil {
- return e.NewErr(e.ERR_DB_ORM, err.Error())
- }
-
- // 基本信息保存
- var goodsModel model.Goods
- 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.UpdateAt = now.Format("2006-01-02 03:04:05")
- //处理图片链接
- req.Base.ImageListUrl = DealImg(c, req.Base.ImageList)
- goodsModel.ImageList = utils.SerializeStr(req.Base.ImageListUrl)
- goodsModel.Spe = utils.SerializeStr(req.Base.Spe)
- //处理图片链接
- req.Base.DetailUrl = DealImg(c, req.Base.Detail)
- goodsModel.Detail = utils.SerializeStr(req.Base.DetailUrl) // detail为详情图列表
-
- if req.Base.GoodsId == "" {
- goodsModel.SaleState = 0
- affect, err := sess.Insert(&goodsModel)
- if err != nil || affect != 1 {
- _ = sess.Rollback()
- return e.NewErr(e.ERR_DB_ORM, "插入商品失败")
-
- }
- } else {
- _, err := sess.Where("goods_id=?", req.Base.GoodsId).AllCols().Update(&goodsModel)
- if err != nil {
- return e.NewErr(e.ERR_DB_ORM, "更新商品失败")
- }
- }
-
- // sku保存
- // 创建商品,则全部为插入
- skuModelList := make([]*model.Sku, 0, len(req.SkuList))
- for key, item := range req.SkuList {
- skuModelList = append(skuModelList, &model.Sku{
- SkuId: utils.StrToInt64(utils.AnyToString(goodsModel.GoodsId) + "0" + utils.AnyToString(key)),
- GoodsId: goodsModel.GoodsId,
- Price: item.Price,
- SkuCode: item.SkuCode,
- Indexes: GetIndexesStr(&req.Base, item),
- Sku: utils.SerializeStr(&item.Sku),
- CreateAt: now.Format("2006-01-02 03:04:05"),
- UpdateAt: now.Format("2006-01-02 03:04:05"),
- })
- }
- //先删除旧的再插入
- _, err = sess.Delete(&model.Sku{GoodsId: goodsModel.GoodsId})
- if err != nil {
- return e.NewErr(e.ERR_DB_ORM, "规格更新失败")
- }
-
- // 插入sku
- insert, err := sess.Insert(skuModelList)
- if err != nil || insert < 1 {
- return e.NewErr(e.ERR_DB_ORM, "插入商品规格失败")
- }
-
- err = sess.Commit()
- if err != nil {
- return e.NewErr(e.ERR_DB_ORM, "更新商品失败")
- }
- return nil
- }
-
- // GetIndexesStr sku属性值在spe中的index
- 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, "-")
- }
-
- func GetGoodsDetail(c *gin.Context, id int) (map[string]interface{}, error) {
- resp := make(map[string]interface{})
- var skuList []*model.Sku
- var goodsModel *model.Goods
-
- // 新增商品的时候默认数据
- if id == 0 {
- resp["base_goods"] = nil
- resp["sku"] = nil
- return resp, nil
- }
-
- goodsModelInterface, has, err := db.GetComm(db.Db, &model.Goods{GoodsId: int64(id)})
- if !has {
- return nil, errors.New("当前商品不存在")
- }
- if err != nil {
- _ = logx.Error(err)
- return nil, e.NewErr(e.ERR_DB_ORM, fmt.Sprintf("查询商品失败:%#v", err))
- }
- goodsModel = goodsModelInterface.(*model.Goods)
-
- err = db.Db.Where("goods_id=?", id).Find(&skuList)
- if err != nil || len(skuList) == 0 {
- _ = logx.Error(err)
- return nil, e.NewErr(e.ERR_DB_ORM, fmt.Sprintf("查询商品规格失败:%#v\n", err))
- }
-
- var goodsMap map[string]interface{}
- utils.Unserialize([]byte(utils.SerializeStr(goodsModel)), &goodsMap)
- goodsMap["goods_id"] = utils.AnyToString(goodsModel.GoodsId)
- // 分类名称
- if goodsModel != nil && goodsModel.CategoryId != 0 {
- categoryInterface, has, err := db.GetComm(db.Db, &model.GoodsCategory{Id: goodsModel.CategoryId})
- if err != nil {
- return nil, errors.New("查询商品类目失败")
- }
- categoryModel := categoryInterface.(*model.GoodsCategory)
- if !has {
- goodsMap["category_name"] = ""
- } else {
- goodsMap["category_name"] = categoryModel.Name
- }
- }
-
- // **处理各复合结构**
- var tmpMap interface{}
-
- scheme, host, subDomain, moreSubDomain := svc.ImageBucketNew(c)
-
- // 商品主图
- if goodsMap["image_list"] != nil && goodsMap["image_list"] != "null" {
- utils.Unserialize([]byte(goodsMap["image_list"].(string)), &tmpMap)
- goodsMap["image_list"] = tmpMap
- var imageListUrlTmp []string
- for _, v := range goodsMap["image_list"].([]interface{}) {
- imageListUrlTmp = append(imageListUrlTmp, svc.ImageFormatWithBucketNew(scheme, host, subDomain, moreSubDomain, v.(string)))
- }
- goodsMap["image_list_url"] = imageListUrlTmp
- } else {
- goodsMap["image_list"] = []struct{}{}
- goodsMap["image_list_url"] = []struct{}{}
- }
-
- // 详情图
- if goodsMap["detail"] != nil && goodsMap["detail"] != "null" {
- var tmpDetailImageList []interface{}
- utils.Unserialize([]byte(goodsMap["detail"].(string)), &tmpDetailImageList)
- goodsMap["detail"] = tmpDetailImageList
- var detailImageUrlTmp []string
- for _, v := range goodsMap["detail"].([]interface{}) {
- detailImageUrlTmp = append(detailImageUrlTmp, svc.ImageFormatWithBucketNew(scheme, host, subDomain, moreSubDomain, v.(string)))
- }
- goodsMap["detail_url"] = detailImageUrlTmp
- }
-
- if goodsMap["detail"] == nil || reflect.ValueOf(goodsMap["detail"]).IsNil() {
- goodsMap["detail"] = []interface{}{}
- goodsMap["detail_url"] = []interface{}{}
- }
-
- // 规格属性
- speJson, ok := goodsMap["spe"].(string)
- if ok {
- if goodsMap["spe"] != nil && speJson != "" && speJson != "null" {
- utils.Unserialize([]byte(speJson), &tmpMap)
- goodsMap["spe"] = tmpMap
- } else {
- utils.Unserialize([]byte("[{\"name\": \"默认\",\"values\": [\"默认\"]}]"), &tmpMap)
- goodsMap["spe"] = tmpMap
- }
- } else {
- utils.Unserialize([]byte("[{\"name\": \"默认\",\"values\": [\"默认\"]}]"), &tmpMap)
- goodsMap["spe"] = tmpMap
- }
- if goodsMap["spe_images"] != nil && goodsMap["spe_images"] != "null" && goodsMap["spe_images"] != "[]" && goodsMap["spe_images"] != "" {
- var speImageListUrlTmp []string
- utils.Unserialize([]byte(goodsMap["spe_images"].(string)), &tmpMap)
- goodsMap["spe_images"] = tmpMap
- for _, v := range goodsMap["spe_images"].([]interface{}) {
- speImageListUrlTmp = append(speImageListUrlTmp, svc.ImageFormatWithBucketNew(scheme, host, subDomain, moreSubDomain, v.(string)))
- }
- goodsMap["spe_images_url"] = speImageListUrlTmp
- } else {
- goodsMap["spe_images"] = []struct{}{}
- goodsMap["spe_images_url"] = []struct{}{}
- }
-
- // sku处理
- skuListMap := make([]map[string]interface{}, 0, len(skuList))
- for _, item := range skuList {
- tmp := make(map[string]interface{})
- tmp["goods_id"] = item.GoodsId
- tmp["sku_id"] = item.SkuId
- tmp["sku_code"] = item.SkuCode
- tmp["price"] = item.Price
- tmp["indexes"] = item.Indexes
- utils.Unserialize([]byte(item.Sku), &tmpMap)
- tmp["sku"] = tmpMap
- if item.Indexes == "" || item.Indexes == " " {
- tmp["indexes"] = "0"
- utils.Unserialize([]byte("[{\"name\": \"默认\",\"values\": [\"默认\"]}]"), &tmpMap)
- tmp["sku"] = tmpMap
- }
- skuListMap = append(skuListMap, tmp)
- }
-
- // 清理不用的字段
- if _, ok := goodsMap["create_time"]; ok {
- delete(goodsMap, "create_at")
- }
- if _, ok := goodsMap["update_time"]; ok {
- delete(goodsMap, "update_at")
- }
- if _, ok := goodsMap["delete_at"]; ok {
- delete(goodsMap, "delete_at")
- }
-
- goodsMap["sale_state_zh"] = ""
- if _, ok := goodsMap["sale_state"]; ok {
- switch goodsMap["sale_state"] {
- case 1.00:
- goodsMap["sale_state_zh"] = "销售中"
- break
- case 2.00:
- goodsMap["sale_state_zh"] = "下架"
- break
- }
- }
-
- goodsMap["create_at"] = goodsModel.CreateAt
- goodsMap["update_at"] = goodsModel.UpdateAt
-
- resp["base_goods"] = goodsMap
- resp["sku"] = skuListMap
-
- return resp, nil
-
- }
-
- func MakeGoodsId(c *gin.Context, categoryId string) (string, error) {
-
- var goodsId = categoryId + utils.AnyToString(time.Now().UnixNano()/1e6)
-
- return goodsId, nil
- }
-
- func DelMallGoods(c *gin.Context, ids []string) {
- engine := db.Db
- session := engine.NewSession()
- defer func() {
- session.Close()
- }()
- session.Begin()
- _, err := session.Table("goods").Where(fmt.Sprintf("goods_id in (%s)", strings.Join(ids, ","))).Delete(new(model.Goods))
- if err != nil {
- session.Rollback()
- e.OutErr(c, e.ERR_DB_ORM, err)
- return
- }
- _, err = session.Table("sku").In("goods_id", ids).Delete(new(model.Sku))
- if err != nil {
- session.Rollback()
- e.OutErr(c, e.ERR_DB_ORM, err)
- return
- }
- session.Commit()
- e.OutSuc(c, []int{}, nil)
- }
|