Bladeren bron

解决冲突

jiaojiao7 4 jaren geleden
bovenliggende
commit
f5fc05c1f9

+ 44 - 27
manage/product/product.go

@@ -3,8 +3,8 @@ package product
 import (
 	"github.com/gin-gonic/gin"
 	"go.uber.org/zap"
+	"net/http"
 	"sfbase/global"
-	"sfis/db"
 	"sfis/model"
 	"sfis/model/response"
 	"sfis/service"
@@ -27,16 +27,14 @@ func productCreate(context *gin.Context) {
 	var product model.Product
 	if err := context.ShouldBind(&product); err != nil {
 		global.Logger.Error("productCreate Bind Error", zap.Any("error", err))
-		response.Fail(context)
+		response.FailWithDetailed(response.ParamError, nil, "参数错误", context)
 		return
 	}
-	result := db.GetSFISDB().Create(&product)
-	if result.Error != nil {
-		global.Logger.Error("productCreate Error", zap.Any("product", product), zap.Any("error", result.Error))
-		response.Fail(context)
+	err := service.CreateProduct(product)
+	if err != nil {
+		response.FailWithMessage(err.Error(), context)
 	} else {
-		global.Logger.Info("productCreate Success", zap.Any("product", product))
-		response.OkWithData(product, context)
+		response.OkWithMessage("创建成功", context)
 	}
 
 }
@@ -45,42 +43,51 @@ func productCreate(context *gin.Context) {
 func productDelete(context *gin.Context) {
 	var product model.Product
 	if err := context.ShouldBind(&product); err != nil {
-		response.Fail(context)
+		response.FailWithDetailed(response.ParamError, nil, "参数错误", context)
 		global.Logger.Error("productDelete Bind Error", zap.Any("error", err))
 		return
 	}
-	result := db.GetSFISDB().Delete(&product)
-	if result.Error != nil {
-		global.Logger.Error("productDelete Error", zap.Any("id", product.ID), zap.Any("error", result.Error))
-		response.Fail(context)
+	err := service.DeleteProduct(product)
+	if err != nil {
+		response.FailWithMessage(err.Error(), context)
 	} else {
-		global.Logger.Info("productDelete Success", zap.Any("id", product.ID))
-		response.OkWithData(product, context)
+		response.OkWithMessage("删除成功", context)
 	}
 }
 
 //更新产品信息
 func productUpdate(context *gin.Context) {
-	var product model.Product
-	if err := context.ShouldBind(&product); err != nil {
-		global.Logger.Error("productUpdate Bind Error", zap.Any("error", err))
-		response.Fail(context)
+	id_ := context.PostForm("id")
+	name := context.PostForm("name")
+	url := context.PostForm("url")
+	unitPrice := context.PostForm("unit_price")
+	minUnit := context.PostForm("min_unit")
+	productType := context.PostForm("product_type")
+	testNum := context.PostForm("test_num")
+	if id_ == "" {
+		response.FailWithDetailed(response.ParamError, nil, "参数错误", context)
 		return
 	}
+	id, _ := strconv.Atoi(id_)
+	p := gin.H{
+		"name":         name,
+		"url":          url,
+		"unit_price":   unitPrice,
+		"min_unit":     minUnit,
+		"product_type": productType,
+		"test_num":     testNum}
 
-	result := db.GetSFISDB().Table("product").Where("id = ?", product.ID).Updates(map[string]interface{}{"name": product.Name, "url": product.Path, "unit_price": product.UnitPrice, "min_unit": product.MinUnit, "product_type": product.ProductType, "test_num": product.TestNum})
-	if result.Error != nil {
-		global.Logger.Error("productUpdate Error", zap.Any("product", product), zap.Any("error", result.Error))
-		response.Fail(context)
+	global.Logger.Info("api userProjectChoose参数:", zap.Any("param", p), zap.Any("id", id))
+	err := service.UpdateProduct(p, id)
+	if err != nil {
+		response.FailWithMessage(err.Error(), context)
 	} else {
-		global.Logger.Info("productUpdate Success", zap.Any("product", product))
-		response.OkWithData(product, context)
+		response.OkWithMessage("更新成功", context)
 	}
 }
 
 // 产品信息列表
 func productList(context *gin.Context) {
-
 	page, _ := strconv.Atoi(context.Query("page"))
 	limit, _ := strconv.Atoi(context.Query("limit"))
 	id := context.PostForm("id")
@@ -99,5 +106,15 @@ func productList(context *gin.Context) {
 		"product_type": productType,
 		"test_num":     testNum,
 	}
-	service.ListProduct(condMap,page,limit,context)
+	productList, totalCount, err := service.ListProduct(condMap, page, limit)
+	if err != nil {
+		response.FailWithMessage(err.Error(), context)
+	} else {
+		context.JSON(http.StatusOK, gin.H{
+			"code":       response.SUCCESS,
+			"data":       productList,
+			"msg":        "查询成功",
+			"totalCount": totalCount,
+		})
+	}
 }

+ 11 - 17
manage/user/user.go

@@ -8,13 +8,10 @@ import (
 	"log"
 	"sfbase/global"
 	sutils "sfbase/utils"
-	"sfis/db"
-	"sfis/lock"
 	"sfis/model"
 	"sfis/model/response"
 	"sfis/service"
 	"sfis/utils"
-	"sync"
 	"time"
 )
 
@@ -25,34 +22,31 @@ func DevUserManageRegister(router *gin.Engine) {
 		userGroup.POST("/create", userCreate)
 		userGroup.POST("/userProductChoose", userProductChoose)
 		userGroup.POST("/userProductList", userProductList)
+		userGroup.POST("/moneyRecharge", moneyRecharge)
+		userGroup.POST("/productRecharge", productRecharge)
 	}
 }
 
 // 创建用户
-func userCreate(context *gin.Context) {
+func userCreate(c *gin.Context) {
 	var user model.User
-	if err := context.ShouldBind(&user); err != nil {
-		response.Fail(context)
+	if err := c.ShouldBind(&user); err != nil {
+		response.FailWithMessage("参数错误", c)
 		return
 	}
+	global.Logger.Info("manage userCreate接口参数:", zap.Any("param", user))
 	t := time.Now()
 	appId := utils.GetAppID(t.Unix())
 	key := sutils.GetComplexRandom(8, 3, 5)
 	user.SecretKey = key
 	user.AppID = appId
-	result := db.GetSFISDB().Create(&user)
-	if result.Error != nil {
-		global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", result.Error))
-		response.Fail(context)
+	// 创建用户
+	userData, err := service.CreateUser(user)
+	if err != nil {
+		response.FailWithMessage(err.Error(), c)
 	} else {
-		global.Logger.Info("userCreate Success", zap.Any("user", user))
-		// 生全局内存锁
-		lock.MainLock.Lock()
-		lock.UserLockMap[appId] = &sync.Mutex{}
-		lock.MainLock.Unlock()
-		response.OkWithData(user, context)
+		response.OkWithData(userData, c)
 	}
-
 }
 
 func userProductChoose(c *gin.Context) {

+ 17 - 20
api/v1/userRecharge.go → manage/user/userRecharge.go

@@ -1,7 +1,6 @@
-package v1
+package user
 
 import (
-	"encoding/json"
 	"sfbase/global"
 	"sfis/model/response"
 	"sfis/service"
@@ -11,16 +10,6 @@ import (
 	"go.uber.org/zap"
 )
 
-//充值相关接口服务
-func RechargeApiRegister(router *gin.Engine) {
-	routerGroup := router.Group("/sfis/api/v1/user/")
-	routerGroup.Use()
-	{
-		routerGroup.POST("/moneyRecharge", moneyRecharge)
-		routerGroup.POST("/productRecharge", productRecharge)
-	}
-}
-
 //余额充值接口
 func moneyRecharge(c *gin.Context) {
 	appid := c.PostForm("appid")
@@ -32,10 +21,14 @@ func moneyRecharge(c *gin.Context) {
 		"appid": appid,
 		"money": money,
 	}
-	bs, _ := json.Marshal(p)
-	param := string(bs)
-	global.Logger.Info("api moneyRecharge:", zap.Any("param:", param))
-	service.MoneyRecharge(appid, money, c)
+	global.Logger.Info("api moneyRecharge:", zap.Any("param:", p))
+	errs := service.MoneyRecharge(appid, money, c)
+	if errs == nil {
+		response.Ok(c)
+	} else {
+		global.Logger.Error("数据库操作失败", zap.Any("error:", errs))
+		response.FailWithMessage("充值失败", c)
+	}
 }
 
 //产品剩余量充值接口
@@ -53,8 +46,12 @@ func productRecharge(c *gin.Context) {
 		"rechargeNum": rechargeNum,
 		"endTime":     endTime,
 	}
-	bs, _ := json.Marshal(p)
-	param := string(bs)
-	global.Logger.Info("api productRecharge:", zap.Any("param:", param))
-	service.ProductRecharge(appid, productId, rechargeNum, endTime, c)
+	global.Logger.Info("api productRecharge:", zap.Any("param:", p))
+	errss := service.ProductRecharge(appid, productId, rechargeNum, endTime, c)
+	if errs == nil {
+		response.Ok(c)
+	} else {
+		global.Logger.Error("数据库操作失败", zap.Any("error:", errss))
+		response.FailWithMessage("充值失败", c)
+	}
 }

+ 0 - 26
middleware/auth.go

@@ -3,10 +3,7 @@ package middleware
 import (
 	"fmt"
 	"sfbase/global"
-	"sfbase/redis"
 	sutils "sfbase/utils"
-	"sfis/db"
-	"sfis/model"
 	"sfis/model/response"
 	"sfis/utils"
 	"strconv"
@@ -95,29 +92,6 @@ func TokenAuth() gin.HandlerFunc {
 			context.Abort()
 			return
 		}
-
-		userProduct := &model.UserProduct{}
-		db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
-		//校验是否过期
-		end := userProduct.EndAt
-		if now > end.Unix() {
-			response.FailWithDetailed(response.InterfaceExpired, nil, "剩余量已过期", context)
-			context.Abort()
-			return
-		}
-		//校验每日调用上限
-		limittodaykey := fmt.Sprintf("limittoday_%d_%d_%s", time.Now().Day(), productID, appID)
-		limittoday := redis.GetInt("limit", limittodaykey)
-		if limittoday >= userProduct.CallTimesLimitDay { //当天调用超过次数
-			response.FailWithDetailed(response.MoreThanEveryDayDataNumberLimit, nil, "请求超过每日调用总量限制", context)
-			context.Abort()
-			return
-		} else {
-			if limittoday == 0 {
-				_, max := sutils.GetDayMinMax(time.Now())
-				redis.Put("limit", limittodaykey, 0, int(max-now))
-			}
-		}
 		context.Set("appID", appID)
 		context.Set("productID", productID)
 		context.Set("requestIP", requestIP)

+ 10 - 13
model/response/response.go

@@ -8,26 +8,26 @@ import (
 
 const (
 	ERROR   int = -1
-	SUCCESS int = 1000
+	SUCCESS int = 0
 	//服务级错误码
 	EmptyResult                  int = 201  //查询无结果
-	ParamError                   int = 4001 //参数错误
+	ParamError                   int = 202 //参数错误
 	ParamEmpty                       = 203  //参数为空
 	ParamLenInValid              int = 204  //参数长度小于4
 	Waiting                      int = 205  //等待处理中
 	MoreThanQueryDataNumberLimit int = 206  //请求数据的条数超过上限
-	LeftNumEmpty                     = 4003 //余额不足
-	QueryError                   int = 4004 //系统查询异常,请联系客服
+	LeftNumEmpty                     = 207 //余额不足
+	QueryError                   int = 299 //系统查询异常,请联系客服
 
 	//系统级错误码
-	InValidKey    = 101 //当前KEY无效
-	RemainingLack = 102 //当前KEY余额|余量不足
-	DeleteKey     = 103 //当前Key被暂停使用,请联系管理员
-	TokenInvalid  = 104 //身份验证错误
-	TokenExpired  = 107 //身份验证已过期
+	InValidKey    = 101  //当前KEY无效
+	RemainingLack = 102  //当前KEY余额|余量不足
+	DeleteKey     = 103  //当前Key被暂停使用,请联系管理员
+	TokenInvalid  = 4000 //身份验证错误
+	TokenExpired  = 4002 //身份验证已过期
 
 	//105非法请求过多,请联系管理员
-	IpInvalid                       = 4005 //被禁止的IP
+	IpInvalid                       = 108 //被禁止的IP
 	MoreThanEveryDayQueryTimesLimit = 109  //请求超过每日系统限制
 	//108当前相同查询连续出错,请等2小时后重试
 	InterfaceRightInvalid           = 110 //接口权限未开通
@@ -35,9 +35,6 @@ const (
 	InterfaceDeleted                = 112 //接口已停用,请联系管理员
 	MoreThanEveryDayDataNumberLimit = 113 //请求超过每日调用总量限制
 	OtherError                      = 199 //系统未知错误,请联系技术客服
-	//
-	SignError   = 4000 //签名错误
-	SignExpired = 4002 //签名过期
 )
 
 type Response struct {

+ 2 - 2
model/user.go

@@ -7,10 +7,10 @@ import (
 type User struct {
 	BaseModel
 	Name        string `json:"name" form:"name" binding:"required"`
-	Phone       string `json:"phone" form:"phone"`
+	Phone       string `json:"phone" form:"phone" binding:"required"`
 	AppID       string `json:"app_id"`
 	SecretKey   string `json:"secret_key"`
-	IpWhiteList string `json:"ip_white_list" form:"ip_white_list"`
+	IpWhiteList string `json:"ip_white_list" form:"ip_white_list" binding:"required"`
 }
 
 func (user *User) TableName() string {

+ 1 - 1
router/pageRouter.go

@@ -13,5 +13,5 @@ func pageRouterRegister(router *gin.Engine) {
 }
 
 func mainPage(context *gin.Context) {
-	context.HTML(200, "main.html", nil)
+	context.HTML(200, "login.html", nil)
 }

+ 0 - 1
router/route.go

@@ -17,7 +17,6 @@ func InitRouter(middleware ...gin.HandlerFunc) *gin.Engine {
 		})
 	})
 	v1.ProjectApiRegister(router)
-	v1.RechargeApiRegister(router)
 	user.DevUserManageRegister(router)
 	product.ProductManageRegister(router)
 	return router

+ 76 - 16
service/product.go

@@ -1,17 +1,70 @@
 package service
 
 import (
+	"errors"
 	"fmt"
-	"github.com/gin-gonic/gin"
 	"go.uber.org/zap"
 	"sfbase/global"
 	"sfis/db"
 	"sfis/model"
-	"sfis/model/response"
+	"strconv"
 	"strings"
 )
 
-func ListProduct(condMap map[string]interface{},page int,limit int,context *gin.Context) {
+// 创建产品
+func CreateProduct(product model.Product) error {
+	var count int64
+	// 判断用产品id是否重复
+	db.GetSFISDB().Table("product").Where("id = ?", product.ID).Count(&count)
+	fmt.Println(count, product.ID)
+	if count > 0 {
+		return errors.New("产品id重复")
+	}
+	result := db.GetSFISDB().Create(&product)
+	if result.Error != nil {
+		global.Logger.Error("productCreate Error", zap.Any("product", product), zap.Any("error", result.Error))
+		return errors.New("产品创建失败")
+	} else {
+		global.Logger.Info("productCreate Success", zap.Any("product", product))
+		return nil
+	}
+}
+
+// 删除产品
+func DeleteProduct(product model.Product) error {
+	result := db.GetSFISDB().Delete(&product)
+	if result.Error != nil {
+		global.Logger.Error("productDelete Error", zap.Any("id", product.ID), zap.Any("error", result.Error))
+		return errors.New("产品删除失败")
+	} else {
+		global.Logger.Info("productDelete Success", zap.Any("id", product.ID))
+		return nil
+	}
+}
+
+//更新产品
+func UpdateProduct(updateMap map[string]interface{}, id int) error {
+	//移除map中为空串的key
+	for k, v := range updateMap {
+		if v == "" {
+			delete(updateMap, k)
+		} else if k == "unit_price" || k == "min_unit" || k == "product_type" || k == "test_num" {
+			strV, _ := strconv.Atoi(v.(string))
+			updateMap[k] = strV
+		}
+	}
+	result := db.GetSFISDB().Table("product").Where("id = ?", id).Updates(updateMap)
+	if result.Error != nil {
+		global.Logger.Error("productUpdate Error", zap.Any("updateMap", updateMap), zap.Any("error", result.Error))
+		return errors.New("更新失败")
+	} else {
+		global.Logger.Info("productUpdate Success", zap.Any("updateMap", updateMap))
+		return nil
+	}
+}
+
+// 查询产品
+func ListProduct(condMap map[string]interface{}, page int, limit int) ([]model.Product, int64, error) {
 	// 拼查询sql
 	var products []model.Product
 	var key []string
@@ -21,25 +74,32 @@ func ListProduct(condMap map[string]interface{},page int,limit int,context *gin.
 			continue
 		}
 		var kStr string
-		if k=="name" || k=="url"{
-			kStr = fmt.Sprintf("%s like ?",k)
-			v = "%"+v.(string)+"%"
-		}else {
+		if k == "name" || k == "url" {
+			kStr = fmt.Sprintf("%s like ?", k)
+			v = "%" + v.(string) + "%"
+		} else {
 			kStr = fmt.Sprintf("%s = ?", k)
 		}
-		key = append(key,kStr)
-		param = append(param,v)
+		key = append(key, kStr)
+		param = append(param, v)
 	}
-	sql := strings.Join(key," and ")
+	sql := strings.Join(key, " and ")
 	var totalCount int64
-	result := db.GetSFISDB().Table("product").Where(sql,param...).Limit(limit).Offset((page - 1) * limit).Find(&products)
-	db.GetSFISDB().Table("product").Where(sql,param...).Count(&totalCount)
+	// 查询
+	err := db.GetSFISDB().Table("product").Where(sql, param...).Find(&products).Count(&totalCount).Error
+	if err != nil {
+		global.Logger.Error("productList search count Error", zap.Any("condMap", condMap), zap.Any("error", err))
+		return products, 0, errors.New("产品信息查询失败")
+	}
+	if totalCount == 0 {
+		return products, 0, nil
+	}
+	result := db.GetSFISDB().Table("product").Where(sql, param...).Limit(limit).Offset((page - 1) * limit).Find(&products)
 	if result.Error != nil {
 		global.Logger.Error("productList Error", zap.Any("condMap", condMap), zap.Any("error", result.Error))
-		response.Fail(context)
+		return products, 0, errors.New("产品信息查询失败")
 	} else {
 		global.Logger.Info("productList Success", zap.Any("condMap", condMap))
-		response.OkWithData(products, context)
+		return products, totalCount, nil
 	}
-
-}
+}

+ 52 - 3
service/user.go

@@ -1,7 +1,10 @@
 package service
 
 import (
+	"errors"
+	"github.com/gin-gonic/gin"
 	"go.uber.org/zap"
+	"gorm.io/gorm"
 	"log"
 	"sfbase/global"
 	"sfbase/utils"
@@ -10,10 +13,8 @@ import (
 	"sfis/model"
 	"sfis/model/response"
 	"strconv"
+	"sync"
 	"time"
-
-	"github.com/gin-gonic/gin"
-	"gorm.io/gorm"
 )
 
 func CreateUserProduct(appId string, productArr []map[string]interface{}, buyType int) (status int, haveProductId string, err error) {
@@ -140,3 +141,51 @@ func UserProductList(appId string, c *gin.Context) {
 		response.OkWithData(userProduct, c)
 	}
 }
+
+//创建用户
+func CreateUser(user model.User) (model.User, error) {
+	var tempUser []model.User
+	// 判断用户名是否重复
+	db.GetSFISDB().Where("name = ?", user.Name).Find(&tempUser)
+	if len(tempUser) > 0 {
+		global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", "用户名已存在"))
+		return user, errors.New("用户名已存在")
+	}
+	// 判断手机号是否重复
+	var tempUser_ []model.User
+	db.GetSFISDB().Where("phone = ?", user.Phone).Find(&tempUser_)
+	if len(tempUser_) > 0 {
+		global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", "手机号已存在"))
+		return user, errors.New("手机号已存在")
+	}
+	errs := db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
+		// 新增用户
+		err := tx.Create(&user).Error
+		if err != nil {
+			global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", err))
+			tx.Rollback()
+			return err
+		}
+		// 初始化用户账户
+		userAccount := model.UserAccount{AppID: user.AppID, Money: 0}
+		err = tx.Create(&userAccount).Error
+		if err != nil {
+			global.Logger.Error("userAccountInit Error", zap.Any("user", user), zap.Any("userAccount", userAccount), zap.Any("error", err))
+			tx.Rollback()
+			return err
+		}
+		return nil
+	})
+	if errs != nil {
+		global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", errs))
+		return user, errors.New("创建失败")
+	} else {
+		global.Logger.Info("userCreate Success", zap.Any("user", user))
+		// 生全局内存锁
+		lock.MainLock.Lock()
+		lock.UserLockMap[user.AppID] = &sync.Mutex{}
+		lock.MainLock.Unlock()
+		return user, nil
+	}
+
+}

+ 5 - 18
service/userRecharge.go

@@ -1,11 +1,9 @@
 package service
 
 import (
-	"sfbase/global"
 	"sfis/db"
 	"sfis/lock"
 	"sfis/model"
-	"sfis/model/response"
 
 	"github.com/gin-gonic/gin"
 
@@ -13,11 +11,10 @@ import (
 	"sfis/utils"
 	"time"
 
-	"go.uber.org/zap"
 	"gorm.io/gorm"
 )
 
-func MoneyRecharge(appid string, money int, context *gin.Context) {
+func MoneyRecharge(appid string, money int, context *gin.Context) error {
 	//取出用户锁
 	lock.MainLock.Lock()
 	userLock := lock.UserLockMap[appid]
@@ -46,15 +43,10 @@ func MoneyRecharge(appid string, money int, context *gin.Context) {
 		}
 		return nil
 	})
-	if errs == nil {
-		response.Ok(context)
-	} else {
-		global.Logger.Error("数据库操作失败", zap.Any("error:", errs))
-		response.FailWithMessage("充值失败", context)
-	}
+	return errs
 }
 
-func ProductRecharge(appid string, productId, rechargeNum int, endTime string, context *gin.Context) {
+func ProductRecharge(appid string, productId, rechargeNum int, endTime string, context *gin.Context) error {
 	//取出用户锁
 	lock.MainLock.Lock()
 	userLock := lock.UserLockMap[appid]
@@ -96,7 +88,7 @@ func ProductRecharge(appid string, productId, rechargeNum int, endTime string, c
 				return err
 			}
 		}
-		//生充值记录
+		//生购买记录
 		err = tx.Exec("insert into user_buy_record (app_id,product_id,user_product_id,`before`,`after`,trade_money,buy_type,history_unit_price) values (?,?,?,?,?,?,?,?)", appid, productId, userProduct.ID, before, after, product.UnitPrice*rechargeNum, 1, product.UnitPrice).Error
 		if err != nil {
 			log.Printf("appID:[%s],product_id:[%d],user_product_id:[%d],after:[%d],trade_money:[%d] execute insert into user_buy_record error:[%v]", appid, productId, userProduct.ID, after, product.UnitPrice*rechargeNum, err)
@@ -105,10 +97,5 @@ func ProductRecharge(appid string, productId, rechargeNum int, endTime string, c
 		}
 		return nil
 	})
-	if errs == nil {
-		response.Ok(context)
-	} else {
-		global.Logger.Error("数据库操作失败", zap.Any("error:", errs))
-		response.FailWithMessage("充值失败", context)
-	}
+	return errs
 }

+ 68 - 1
static/templates/login.html

@@ -3,10 +3,77 @@
     <html lang="en">
     <head>
         <meta charset="UTF-8">
+        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
+        <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.js"></script>
         <title>接口服务平台后台管理系统</title>
     </head>
+    <style>
+      
+    </style>
     <body>
-    接口服务平台后台管理系统
+        <dev id="main">
+            <h1>对外接口</h1>
+            <dev>
+                <a onclick="$('#projectList').show();$('#main').hide();">1.项目列表</a>
+                <a>2.项目详情</a>
+                <a>3.项目列表及详情</a>
+            </dev>
+            <h1>充值接口</h1>
+            <dev>
+                <a>1.余额充值</a>
+                <a>2.产品充值</a>
+            </dev>
+            <h1>内部接口</h1>
+            <dev>
+            </dev>
+        </dev>
+        <dev id="projectList" style="display: none;">
+            <input type="text" id="projectName" placeholder="请输入项目名">
+            <input type="text" id="winner" placeholder="请输入中标企业名">
+            <input type="text" id="bidTime" placeholder="请输入中标日期">
+            <button type="button" id="projectListBtn">提交</button>
+        </dev>
+        <dev id="resultContent"></dev>
+        <script>
+            var appid = "sfGSVYRQMAAgkGBAUBJg4f";
+            var key = "364xw909";
+            function submit(param,rType,url,hearders){
+                $.ajax({
+                    url: url,
+                    type: rType,
+                    headers: hearders,
+                    data: param,
+                    success:function(r){
+                    	if(r.code === 1000){
+                            $("#resultContent").text(r.msg);
+                    	}else{
+                    		$("#resultContent").text(r.msg);
+                    	}
+                    }
+                })
+            }
+            console.log(md5(appid+"1610611965"+key))
+            $("#projectListBtn").on("click", function(){
+                var param = {
+                    "app_id": appid,
+                    "project_name": $("#projectName").val(),
+                    "winner": $("#winner").val(),
+                    "bid_time": $("#bidTime").val()
+                };
+                var url = "/sfis/api/v1/projectList";
+                var rType = "post";
+                var now = new Date().getTime();
+                var token = md5(appid+Math.round(now/1000)+key);
+                // var token = "6f6d4434cc424a44360ce1b27939500e";
+                console.log(token)
+                var hearders = {
+                    "timestamp": ""+Math.round(now/1000),
+                    // "timestamp": "1610610260",
+                    "token": token
+                }
+                submit(param,rType,url,hearders);
+            })
+        </script>
     </body>
     </html>
 {{end}}

+ 5 - 1
sword_base/elastic/elasticSim.go

@@ -2,6 +2,7 @@ package elastic
 
 import (
 	"encoding/json"
+	"errors"
 	"fmt"
 	"log"
 	"runtime"
@@ -104,7 +105,7 @@ func (e *Elastic) Get(index, itype, query string) (*[]map[string]interface{}, er
 		searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
 		if err != nil {
 			log.Println("从ES查询出错", err.Error())
-			return nil, err
+			return nil, errors.New("Es查询出错")
 		}
 		if searchResult.Hits != nil {
 			resNum := len(searchResult.Hits.Hits)
@@ -117,9 +118,12 @@ func (e *Elastic) Get(index, itype, query string) (*[]map[string]interface{}, er
 					}
 				}
 			} else {
+				return nil, errors.New("查询数量超过限制")
 				log.Println("查询结果太多,查询到:", resNum, "条")
 			}
 		}
+	} else {
+		return nil, errors.New("Es查询出错")
 	}
 	return &res, nil
 }

+ 23 - 26
test/manage/product_test.go

@@ -12,8 +12,8 @@ import (
 // 新增产品测试用例
 func Test_CreateProduct(t *testing.T) {
 	product1 := &model.Product{
-		ID:          2006,
-		Name:        "行业中标数据",
+		ID:          2012,
+		Name:        "招标详细信息",
 		Path:        "/path2002",
 		UnitPrice:   50, //单价精确到分  5毛
 		MinUnit:     1,  //最小单位1,即 5毛/条
@@ -36,7 +36,7 @@ func Test_CreateProduct(t *testing.T) {
 
 // 删除产品 测试用例
 func Test_DeleteProduct(t *testing.T) {
-	productId := "2002"
+	productId := "2013"
 	log.Println("productDelete testing......")
 	data := make(url.Values)
 	data["id"] = []string{productId}
@@ -48,23 +48,22 @@ func Test_DeleteProduct(t *testing.T) {
 func Test_UpdateProduct(t *testing.T) {
 	log.Println("productUpdate testing......")
 	product1 := &model.Product{
-		ID:          2001,
-		Name:        "行业中标数据",
-		Path:        "/pathUpdate1",
+		ID:          2013,
+		Name:        "医疗行业数据",
+		Path:        "/pathUpdate2",
 		UnitPrice:   50, //单价精确到分  5毛
 		MinUnit:     1,  //最小单位1,即 5毛/条
-		ProductType: 0,  //产品类型 0-按次 1-按条
-		TestNum:     200,
+		ProductType: 1,  //产品类型 0-按次 1-按条
+		TestNum:     500,
 	}
 	data := make(url.Values)
 	data["id"] = []string{strconv.Itoa(product1.ID)}
 	data["name"] = []string{product1.Name}
 	data["url"] = []string{product1.Path}
-	data["unit_price"] = []string{strconv.Itoa(product1.UnitPrice)}
-	data["min_unit"] = []string{strconv.Itoa(product1.MinUnit)}
-	data["product_type"] = []string{strconv.Itoa(product1.ProductType)}
-	data["test_num"] = []string{strconv.Itoa(product1.TestNum)}
-
+	//data["unit_price"] = []string{strconv.Itoa(product1.UnitPrice)}
+	//data["min_unit"] = []string{strconv.Itoa(product1.MinUnit)}
+	//data["product_type"] = []string{strconv.Itoa(product1.ProductType)}
+	//data["test_num"] = []string{strconv.Itoa(product1.TestNum)}
 
 	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/product/update", map[string]string{}, data)
 	log.Print(string(bs))
@@ -72,26 +71,24 @@ func Test_UpdateProduct(t *testing.T) {
 
 func Test_ListProduct(t *testing.T) {
 	log.Println("productList testing......")
-	//product1 := &model.Product{
-	//	ID:          2001,
-	//	Name:        "行业中标",
-	//	Path:        "/pathUpdate1",
-	//	UnitPrice:   50, //单价精确到分  5毛
-	//	MinUnit:     1,  //最小单位1,即 5毛/条
-	//	ProductType: 0,  //产品类型 0-按次 1-按条
-	//	TestNum:     200,
-	//}
+	product1 := &model.Product{
+		ID:          2001,
+		Name:        "接口",
+		Path:        "/pathUpdate1",
+		UnitPrice:   50, //单价精确到分  5毛
+		MinUnit:     1,  //最小单位1,即 5毛/条
+		ProductType: 0,  //产品类型 0-按次 1-按条
+		TestNum:     200,
+	}
 	data := make(url.Values)
 	//data["id"] = []string{strconv.Itoa(product1.ID)}
 	//data["name"] = []string{product1.Name}
 	//data["url"] = []string{product1.Path}
-	//data["unit_price"] = []string{strconv.Itoa(product1.UnitPrice)}
+	data["unit_price"] = []string{strconv.Itoa(product1.UnitPrice)}
 	//data["min_unit"] = []string{strconv.Itoa(product1.MinUnit)}
 	//data["product_type"] = []string{strconv.Itoa(product1.ProductType)}
 	//data["test_num"] = []string{strconv.Itoa(product1.TestNum)}
 
-
-	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/product/list?page=1&&limit=3", map[string]string{}, data)
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/product/list", map[string]string{}, data)
 	log.Print(string(bs))
 }
-

+ 1 - 1
test/manage/user_test.go

@@ -43,7 +43,7 @@ func Test_CreateUser(t *testing.T) {
 	//secretKey := sutil.GetComplexRandom(8, 3, 5)
 
 	data := make(url.Values)
-	data["name"] = []string{"河南拓普"}
+	data["name"] = []string{"拓普公司测试3"}
 	data["phone"] = []string{"18238182402"}
 	data["ip_white_list"] = []string{"*"}
 

+ 20 - 0
utils/api_util.go

@@ -6,6 +6,7 @@ import (
 	"log"
 	"sfbase/global"
 	"sfbase/redis"
+	"sfbase/utils"
 	"sfis/db"
 	"sfis/lock"
 	"sfis/model"
@@ -40,6 +41,25 @@ func Check(appID string, productID int, c *gin.Context, getData func() ([]map[st
 		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口暂不提供服务", c)
 		return
 	}
+	//校验是否过期
+	now := time.Now().Unix()
+	end := userProduct.EndAt
+	if now > end.Unix() {
+		response.FailWithDetailed(response.InterfaceExpired, nil, "剩余量已过期", c)
+		return
+	}
+	//校验每日调用上限
+	limittodaykey := fmt.Sprintf("limittoday_%d_%d_%s", time.Now().Day(), productID, appID)
+	limittoday := redis.GetInt("limit", limittodaykey)
+	if limittoday >= userProduct.CallTimesLimitDay { //当天调用超过次数
+		response.FailWithDetailed(response.MoreThanEveryDayDataNumberLimit, nil, "请求超过每日调用总量限制", c)
+		return
+	} else {
+		if limittoday == 0 {
+			_, max := utils.GetDayMinMax(time.Now())
+			redis.Put("limit", limittodaykey, 0, int(max-now))
+		}
+	}
 	//2.2 取用户(产品余量|钱包账户余额)校验-必须加锁
 	costModel := userProduct.CostModel //扣费模式 0扣余量,1-扣余额
 	product := GetProductByID(productID)