kobe6258 5 місяців тому
батько
коміт
c9091869e5

+ 168 - 4
controllers/product.go

@@ -8,15 +8,31 @@ import (
 	"eta/eta_mini_crm_ht/models/response"
 	"eta/eta_mini_crm_ht/services"
 	"eta/eta_mini_crm_ht/utils"
+	"fmt"
 	"github.com/go-sql-driver/mysql"
 	"github.com/rdlucklib/rdluck_tools/paging"
 	"github.com/shopspring/decimal"
+	"math/rand"
 	"strconv"
 	"strings"
 	"sync"
 	"time"
 )
 
+var (
+	CNProductMap = map[models.MerchantProductType]string{
+		models.ProductPackage: "套餐",
+		models.ProductVideo:   "视频",
+		models.ProductAudio:   "音频",
+		models.ProductReport:  "报告",
+	}
+
+	CNSaleStatusMap = map[models.SaleStatus]string{
+		models.OnSale:  "已上架",
+		models.OffSale: "未上架",
+	}
+)
+
 type ProductController struct {
 	BaseAuthController
 }
@@ -135,6 +151,7 @@ func (this *ProductController) AddProduct() {
 		this.ServeJSON()
 	}()
 	var req request.ProductReq
+	var permissionName string
 	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
 	if err != nil {
 		br.Msg = "参数解析异常!"
@@ -157,7 +174,23 @@ func (this *ProductController) AddProduct() {
 		product.Title = req.ProductName
 		product.ValidDays = req.ValidDays
 		product.Description = req.Description
-		product.CoverSrc = req.CoverSrc
+		if req.CoverSrc == "" {
+			var imageList []models.ImageSource
+			imageList, err = models.GetImageByPermissionId(req.SourceId)
+			if err != nil {
+				utils.FileLog.Error("套餐封面获取失败", err.Error())
+				//br.Msg = "默认套餐封面获取失败,请上传封面"
+				//br.ErrMsg = "默认套餐封面获取失败,请上传封面,Err:" + err.Error()
+				//return
+			} else {
+				var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
+				index := rnd.Intn(len(imageList))
+				product.CoverSrc = imageList[index].SrcUrl
+			}
+		} else {
+			product.CoverSrc = req.CoverSrc
+		}
+
 	}
 	switch req.Type {
 	case "report":
@@ -167,7 +200,7 @@ func (this *ProductController) AddProduct() {
 	case "video":
 		product.RiskLevel, product.Title, err = services.GetRiskLevel("video", req.SourceId)
 	case "package":
-		product.RiskLevel, _, err = services.GetRiskLevel("package", req.SourceId)
+		product.RiskLevel, permissionName, err = services.GetRiskLevel("package", req.SourceId)
 	default:
 		br.Msg = "产品类型错误"
 		br.ErrMsg = "获取产品列表失败,Err:产品类型错误"
@@ -216,6 +249,7 @@ func (this *ProductController) AddProduct() {
 	product.Price = req.Price
 	product.SourceId = req.SourceId
 	product.Type = models.MerchantProductType(req.Type)
+	product.Creator = this.SysUser.SysRealName
 	if product.Type == "" {
 		br.Msg = "新增产品错误"
 		br.ErrMsg = "产品类型为空"
@@ -227,8 +261,21 @@ func (this *ProductController) AddProduct() {
 		var mysqlErr *mysql.MySQLError
 		if errors.As(err, &mysqlErr) {
 			if mysqlErr.Number == 1062 {
-				br.Msg = "该产品已设置付费,请刷新后重试"
-				br.ErrMsg = "该产品已设置付费,请刷新后重试"
+				if product.Type == models.ProductPackage {
+					var dbProduct models.MerchantProduct
+					dbProduct, err = models.GetProductByProductType(product.SourceId, models.ProductPackage)
+					if err != nil {
+						utils.FileLog.Error("获取套餐产品信息失败,err:" + err.Error())
+						br.Msg = "[" + permissionName + "]已设置付费套餐,请重新选择"
+						br.ErrMsg = "[" + permissionName + "]已设置付费套餐,请重新选择"
+					} else {
+						br.Msg = "[" + permissionName + "]已设置付费套餐[" + dbProduct.Title + "],请重新选择"
+						br.ErrMsg = "[" + permissionName + "]已设置付费套餐[" + dbProduct.Title + "],请重新选择"
+					}
+				} else {
+					br.Msg = "该产品已设置付费,请刷新后重试"
+					br.ErrMsg = "该产品已设置付费,请刷新后重试"
+				}
 			} else {
 				utils.FileLog.Error("新增产品失败,err:" + err.Error())
 				br.Msg = "新增产品失败"
@@ -350,6 +397,123 @@ func (this *ProductController) DeleteProduct() {
 	br.Success = true
 }
 
+// ProductList
+// @Title 产品列表
+// @Description pdf研报列表
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Param   ClassifyIds   query   string  true       "二级分类id,可多选用英文,隔开"
+// @Param   KeyWord   query   string  true       "报告标题/创建人"
+// @Param   SortType   query   string  true       "排序方式"
+// @Success 200 {object} models.ReportAuthorResp
+// @router /productList [get]
+func (this *ProductController) ProductList() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+	sortType := this.GetString("SortType")
+	KeyWord := this.GetString("KeyWord")
+	CreatedTime := this.GetString("CreatedTime")
+	UpdatedTime := this.GetString("UpdatedTime")
+	IsSingle, _ := this.GetBool("IsSingle", true)
+	ProductType := this.GetString("ProductType")
+	SaleStatus := this.GetString("SaleStatus")
+	var condition string
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	if KeyWord != "" {
+		condition += " AND title like '%" + KeyWord + "%'"
+	}
+	sortCondition := " ORDER BY created_time "
+	if sortType == "" {
+		sortType = "DESC"
+	}
+	if CreatedTime != "" {
+		condition += " AND Date(created_time) = '" + CreatedTime + "'"
+	}
+	if UpdatedTime != "" {
+		condition += " AND Date(updated_time) = '" + UpdatedTime + "'"
+	}
+	if SaleStatus != "" {
+		switch SaleStatus {
+		case "onSale":
+			condition += " AND sale_status='on_sale'"
+		case "offSale":
+			condition += " AND sale_status='off_sale'"
+		default:
+			br.Msg = "无效的销售状态"
+			br.ErrMsg = "无效的销售状态:" + SaleStatus
+			return
+		}
+	}
+	if IsSingle {
+		if ProductType != "" {
+			switch ProductType {
+			case "report":
+				condition += " AND type='" + string(models.ProductReport) + "'"
+			case "audio":
+				condition += " AND type='" + string(models.ProductAudio) + "'"
+			case "video":
+				condition += " AND type='" + string(models.ProductVideo) + "'"
+			default:
+				br.Msg = "无效的产品类型"
+				br.ErrMsg = "无效的产品类型:" + ProductType
+				return
+			}
+		}
+
+	} else {
+		condition += " AND type = '" + string(models.ProductPackage) + "'"
+	}
+	sortCondition = sortCondition + sortType
+	total, err := models.GetProductCountByCondition(condition)
+	if err != nil {
+		br.Msg = "获取产品列表失败"
+		br.ErrMsg = "获取产品列表失败,Err:" + err.Error()
+		return
+	}
+
+	startSize := utils.StartIndex(currentIndex, pageSize)
+	List, err := models.GetProductByCondition(condition, sortCondition, startSize, pageSize)
+	if err != nil {
+		br.Msg = "获取产品列表失败"
+		br.ErrMsg = "获取产品列表失败,Err:" + err.Error()
+		return
+	}
+	var ListView []*services.ProductView
+	for _, product := range List {
+		view := &services.ProductView{
+			ProductName:   product.Title,
+			ProductType:   CNProductMap[product.Type],
+			PublishedTime: product.CreatedTime.Format(time.DateTime),
+			RiskLevel:     product.RiskLevel,
+			Price:         fmt.Sprintf("¥%s", product.Price),
+			SaleStatus:    CNSaleStatusMap[product.SaleStatus],
+		}
+		if !product.UpdatedTime.IsZero() {
+			view.UpdatedTime = product.UpdatedTime.Format(time.DateTime)
+		}
+		ListView = append(ListView, view)
+	}
+	page := paging.GetPaging(currentIndex, pageSize, total)
+	resp := new(response.ProductListResp)
+	resp.List = ListView
+	resp.Paging = page
+
+	br.Ret = 200
+	br.Success = true
+	br.Data = resp
+	br.Msg = "获取成功"
+}
+
 //
 //// OnSale @Title 上架产品
 //// @Description 上架产品

+ 6 - 1
models/image_sources.go

@@ -62,13 +62,18 @@ func (i *ImageSource) Delete() (err error) {
 	return
 }
 
+func GetImageByPermissionId(permissionId int) (items []ImageSource, err error) {
+	o := orm.NewOrm()
+	sql := "select id from image_sources where permission_id = ?"
+	_, err = o.Raw(sql, permissionId).QueryRows(&items)
+	return
+}
 func GetImageIdByPermissionId(permissionId int) (items []int, err error) {
 	o := orm.NewOrm()
 	sql := "select id from image_sources where permission_id = ?"
 	_, err = o.Raw(sql, permissionId).QueryRows(&items)
 	return
 }
-
 func GetImageById(Id int) (item *ImageSource, err error) {
 	o := orm.NewOrm()
 	sql := "select id from image_sources where id = ?"

+ 40 - 15
models/merchant_product.go

@@ -19,20 +19,21 @@ const (
 )
 
 type MerchantProduct struct {
-	Id          int                 `gorm:"column:id;primary_key;autoIncrement;comment:主键"`
-	SourceId    int                 `gorm:"column:source_id;type:int(11);comment:单品或者套餐对应的主键"`
-	Title       string              `gorm:"column:title;type:varchar(255);comment:标题"`
-	CoverSrc    string              `gorm:"column:cover_src;type:varchar(255);comment:封面图片"`
-	Description string              `gorm:"column:description;type:varchar(255);comment:描述"`
-	Price       string              `gorm:"column:price;type:decimal(10,2);comment:价格"`
-	RiskLevel   string              `gorm:"column:risk_level;type:varchar(255);not null;comment:风险等级"`
-	Type        MerchantProductType `gorm:"column:type;type:enum('report','video','audio','package');not null;comment:类型"`
-	IsPermanent bool                `gorm:"column:is_permanent;type:int(1);not null;default:0;comment:是否永久"`
-	ValidDays   int                 `gorm:"column:valid_days;type:int(11);comment:有效期天数"`
-	SaleStatus  SaleStatus          `gorm:"column:sale_status;type:enum('on_sale','off_sale');not null;default:'on_sale';comment:上架/下架状态"`
-	Deleted     bool                `gorm:"column:deleted;type:tinyint(1);not null;default:0;comment:是否删除"`
-	CreatedTime time.Time           `gorm:"column:created_time;type:datetime;comment:创建时间"`
-	UpdatedTime time.Time           `gorm:"column:updated_time;type:datetime;comment:更新时间;default:CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
+	Id          int                 `description:"column:id;primary_key;autoIncrement;comment:主键"`
+	SourceId    int                 `description:"column:source_id;type:int(11);comment:单品或者套餐对应的主键"`
+	Title       string              `description:"column:title;type:varchar(255);comment:标题"`
+	CoverSrc    string              `description:"column:cover_src;type:varchar(255);comment:封面图片"`
+	Description string              `description:"column:description;type:varchar(255);comment:描述"`
+	Price       string              `description:"column:price;type:decimal(10,2);comment:价格"`
+	RiskLevel   string              `description:"column:risk_level;type:varchar(255);not null;comment:风险等级"`
+	Type        MerchantProductType `description:"column:type;type:enum('report','video','audio','package');not null;comment:类型"`
+	IsPermanent bool                `description:"column:is_permanent;type:int(1);not null;default:0;comment:是否永久"`
+	ValidDays   int                 `description:"column:valid_days;type:int(11);comment:有效期天数"`
+	Creator     string              `description:"创建人"`
+	SaleStatus  SaleStatus          `description:"column:sale_status;type:enum('on_sale','off_sale');not null;default:'on_sale';comment:上架/下架状态"`
+	Deleted     bool                `description:"column:deleted;type:tinyint(1);not null;default:0;comment:是否删除"`
+	CreatedTime time.Time           `description:"column:created_time;type:datetime;comment:创建时间"`
+	UpdatedTime time.Time           `description:"column:updated_time;type:datetime;comment:更新时间;default:CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
 }
 
 func (m *MerchantProduct) TableName() string {
@@ -70,7 +71,11 @@ func GetProductSourceIdsByProductType(productType string) (ids []int, err error)
 	_, err = o.Raw("select source_id from merchant_products where deleted = 0 " + condition).QueryRows(&ids)
 	return
 }
-
+func GetProductByProductType(sourceId int, productType MerchantProductType) (product MerchantProduct, err error) {
+	o := orm.NewOrm()
+	err = o.Raw("select * from merchant_products where source_id =? and type=? and  deleted = 0 ", sourceId, productType).QueryRow(&product)
+	return
+}
 func (mp *MerchantProduct) AddProduct() (err error) {
 	o := orm.NewOrm()
 	_, err = o.Insert(mp)
@@ -96,3 +101,23 @@ func (mp *MerchantProduct) Delete() (err error) {
 	_, err = o.Update(mp, "deleted", "updated_time")
 	return
 }
+
+func GetProductByCondition(condition string, sortCondition string, startSize int, pageSize int) (list []*MerchantProduct, err error) {
+	o := orm.NewOrm()
+	sql := `select * from merchant_products where deleted=0`
+	if condition != "" {
+		sql += condition
+	}
+	if sortCondition != "" {
+		sql += sortCondition
+	}
+	sql += ` LIMIT ?,?`
+	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&list)
+	return
+}
+
+func GetProductCountByCondition(condition string) (total int, err error) {
+	o := orm.NewOrm()
+	err = o.Raw("select count(*) from merchant_products where deleted=0" + condition).QueryRow(&total)
+	return
+}

+ 6 - 0
models/response/product.go

@@ -1,6 +1,7 @@
 package response
 
 import (
+	"eta/eta_mini_crm_ht/models"
 	"eta/eta_mini_crm_ht/services"
 	"github.com/rdlucklib/rdluck_tools/paging"
 )
@@ -9,3 +10,8 @@ type ProductListResp struct {
 	List   []*services.ProductView
 	Paging *paging.PagingItem `description:"分页数据"`
 }
+
+type ProductList2Resp struct {
+	List   []*models.MerchantProduct
+	Paging *paging.PagingItem `description:"分页数据"`
+}

+ 9 - 0
routers/commentsRouter.go

@@ -351,6 +351,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_mini_crm_ht/controllers:ProductController"] = append(beego.GlobalControllerRouter["eta/eta_mini_crm_ht/controllers:ProductController"],
+        beego.ControllerComments{
+            Method: "ProductList",
+            Router: `/productList`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_mini_crm_ht/controllers:ProductController"] = append(beego.GlobalControllerRouter["eta/eta_mini_crm_ht/controllers:ProductController"],
         beego.ControllerComments{
             Method: "UnSetProductList",

+ 4 - 1
services/product.go

@@ -164,6 +164,9 @@ type ProductView struct {
 	ProductType   string
 	RiskLevel     string
 	PublishedTime string
+	UpdatedTime   string
+	Price         string
+	SaleStatus    string
 }
 
 func GetRiskLevel(productType string, id int) (riskLevel string, productName string, err error) {
@@ -264,7 +267,7 @@ func GetRiskLevel(productType string, id int) (riskLevel string, productName str
 		if permission.RiskLevel == "" {
 			return "", "", errors.New("当前品种未设置风测等级")
 		}
-		return permission.RiskLevel, "", nil
+		return permission.RiskLevel, permission.Name, nil
 	default:
 		var media *models.Media
 		media, err = models.GetMediaById(models.MediaType(productType), id)