瀏覽代碼

合并冲突

fuwencai 4 年之前
父節點
當前提交
a804214910

+ 3 - 0
api/v1/projects.go

@@ -4,6 +4,7 @@ import (
 	"encoding/json"
 	"sfbase/global"
 	"sfis/middleware"
+	"sfis/model/response"
 	"sfis/service"
 	"sfis/utils"
 
@@ -44,6 +45,8 @@ func getProjectsList(c *gin.Context) {
 		utils.Check(appID, productID, c, func() ([]map[string]interface{}, int, error) {
 			return service.ProjectListData(productID, appID, projectName, winner, bidTime, false)
 		}, param, requestIP)
+	} else {
+		response.FailWithDetailed(response.ParamError, nil, "参数错误", c)
 	}
 }
 

+ 10 - 4
api/v1/userRecharge.go

@@ -3,6 +3,7 @@ package v1
 import (
 	"encoding/json"
 	"sfbase/global"
+	"sfis/model/response"
 	"sfis/service"
 	"strconv"
 
@@ -23,7 +24,10 @@ func RechargeApiRegister(router *gin.Engine) {
 //余额充值接口
 func moneyRecharge(c *gin.Context) {
 	appid := c.PostForm("appid")
-	money, _ := strconv.Atoi(c.PostForm("money"))
+	money, err := strconv.Atoi(c.PostForm("money"))
+	if err != nil {
+		response.FailWithDetailed(response.ParamError, nil, "参数错误", c)
+	}
 	p := gin.H{
 		"appid": appid,
 		"money": money,
@@ -37,10 +41,12 @@ func moneyRecharge(c *gin.Context) {
 //产品剩余量充值接口
 func productRecharge(c *gin.Context) {
 	appid := c.PostForm("appid")
-	productId, _ := strconv.Atoi(c.PostForm("productId"))
-	rechargeNum, _ := strconv.Atoi(c.PostForm("rechargeNum"))
+	productId, err := strconv.Atoi(c.PostForm("productId"))
+	rechargeNum, errs := strconv.Atoi(c.PostForm("rechargeNum"))
 	endTime := c.PostForm("endTime")
-
+	if err != nil || errs != nil {
+		response.FailWithDetailed(response.ParamError, nil, "参数错误", c)
+	}
 	p := gin.H{
 		"appid":       appid,
 		"productId":   productId,

+ 1 - 1
conf/dev/base.toml

@@ -18,4 +18,4 @@
     stacktrace-key= 'stacktrace'
     log-in-console= true
 [session]
-    redis_token = "token=39.107.203.162:10079"
+    redis_token = "token=39.107.203.162:10079,limit=192.168.3.128:1712"

+ 10 - 1
lock/interface.go

@@ -7,6 +7,7 @@ type Cost interface {
 	Deduction() //扣费(剩余量|账户余额)
 	Before() bool
 	After()
+	GetData() (interface{}, int, error)
 }
 
 type LeftNumCost struct {
@@ -15,6 +16,7 @@ type LeftNumCost struct {
 	LeftNum              int
 	ProductType          int
 	DataNumLimitOneTimes int
+	GetData1             func() (interface{}, int, error)
 }
 type AccountBalanceCost struct {
 	AppID          string
@@ -23,6 +25,7 @@ type AccountBalanceCost struct {
 }
 
 func (l *LeftNumCost) Deduction() {
+
 }
 
 func (l *LeftNumCost) Before() bool {
@@ -41,6 +44,10 @@ func (l *LeftNumCost) Before() bool {
 	return true
 }
 
+func (l *LeftNumCost) GetData() (interface{}, int, error) {
+	return l.GetData1()
+}
+
 func (l *LeftNumCost) After() {
 	switch l.ProductType {
 	case 0:
@@ -51,9 +58,11 @@ func (l *LeftNumCost) After() {
 func (a *AccountBalanceCost) Deduction() {
 
 }
-func (a *AccountBalanceCost) Before() bool {
 
+func (a *AccountBalanceCost) Before() bool {
+	return false
 }
+
 func (a *AccountBalanceCost) After() {
 
 }

+ 2 - 3
main.go

@@ -33,6 +33,7 @@ func main() {
 		db.GetSFISDB().Find(&users)
 		for _, user := range users {
 			utils.UserCaches.Map.Store(user.AppID, user)
+			lock.UserLockMap[user.AppID] = &sync.Mutex{}
 		}
 		global.Logger.Info("初始化用户缓存信息,", zap.Any("用户数量:", len(users)))
 
@@ -40,12 +41,10 @@ func main() {
 		db.GetSFISDB().Find(&apis)
 		for _, api := range apis {
 			utils.ProductCaches.Map.Store(api.ID, api)
-			utils.ApiUrlCache.Store(api.Path, *api)
+			utils.ApiUrlCache.Store(api.Path, api.ID)
 		}
 		global.Logger.Info("初始化产品缓存信息,", zap.Any("产品数量:", len(apis)))
 	}
-	lock.UserLockMap["sfGSVYRQMAAgkGBAUBJg4f"] = &sync.Mutex{}
-	lock.UserLockMap["sfPQRYRQMAAwcGBwYBCgcA"] = &sync.Mutex{}
 	//全局redis的使用?
 	redis.InitRedis(global.BaseConfig.RedisSession.RedisToken)
 	//启动web server

+ 43 - 12
middleware/auth.go

@@ -2,15 +2,19 @@ package middleware
 
 import (
 	"fmt"
-	"github.com/gin-gonic/gin"
-	"go.uber.org/zap"
 	"sfbase/global"
+	"sfbase/redis"
 	sutils "sfbase/utils"
+	"sfis/db"
+	"sfis/model"
 	"sfis/model/response"
 	"sfis/utils"
 	"strconv"
 	"strings"
 	"time"
+
+	"github.com/gin-gonic/gin"
+	"go.uber.org/zap"
 )
 
 const TimestampExpireTime = 600 //单位秒,header里的时间戳超时时间 10分钟
@@ -26,17 +30,19 @@ func TokenAuth() gin.HandlerFunc {
 			requestIP  string
 		)
 		requestUrl = context.Request.URL.String()
-		requestUrl = strings.Split(requestUrl, "?")[0]
-		a := strings.Split(requestUrl, "/")
-		requestUrl = a[4]
-		/*if p, ok := utils.ApiUrlCache.Load(requestUrl); ok {
-			productID = p.(*model.Product).ID
+		global.Logger.Info(requestUrl)
+		requestUrl = strings.Split(requestUrl, "v1")[1]
+		global.Logger.Info(requestUrl)
+		// a := strings.Split(requestUrl, "/")
+		// requestUrl = a[4]
+		if p, ok := utils.ApiUrlCache.Load(requestUrl); ok {
+			productID = p.(int)
 		} else {
 			response.FailWithDetailed(response.ParamError, nil, "url错误", context)
 			context.Abort()
 			return
-		}*/
-		productID = 1000
+		}
+		// productID = 1000
 		token = context.Request.Header.Get("token")
 		timestamp = context.Request.Header.Get("timestamp")
 		appID = context.PostForm("app_id")
@@ -53,7 +59,11 @@ func TokenAuth() gin.HandlerFunc {
 			return
 		}
 		now := time.Now().Unix()
-		if now-_timestamp > TimestampExpireTime {
+		TimestampExpire := now - _timestamp
+		if TimestampExpire < 0 {
+			TimestampExpire = -TimestampExpire
+		}
+		if TimestampExpire > TimestampExpireTime {
 			//token时间验证 十分钟
 			response.FailWithDetailed(response.TokenExpired, nil, "签名过期", context)
 			context.Abort()
@@ -68,8 +78,8 @@ func TokenAuth() gin.HandlerFunc {
 		/**
 		第一步:ip白名单校验
 		*/
+		requestIP = utils.GetIp(context.Request)
 		if ipWhiteList != "*" {
-			requestIP = utils.GetIp(context.Request)
 			if strings.Index(ipWhiteList, requestIP) < 0 {
 				response.FailWithDetailed(response.IpInvalid, nil, "ip不在白名单", context)
 				context.Abort()
@@ -86,9 +96,30 @@ func TokenAuth() gin.HandlerFunc {
 			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)
-
 	}
 }

+ 3 - 1
model/product.go

@@ -1,6 +1,8 @@
 package model
 
-import "time"
+import (
+	"time"
+)
 
 type Product struct {
 	BaseModel

+ 15 - 12
model/response/response.go

@@ -8,16 +8,16 @@ import (
 
 const (
 	ERROR   int = -1
-	SUCCESS int = 0
+	SUCCESS int = 1000
 	//服务级错误码
-	EmptyResult                  int = 201 //查询无结果
-	ParamError                   int = 202 //参数错误
-	ParamEmpty                       = 203 //参数为空
-	ParamLenInValid              int = 204 //参数长度小于4
-	Waiting                      int = 205 //等待处理中
-	MoreThanQueryDataNumberLimit int = 206 //请求数据的条数超过上限
-	LeftNumEmpty                     = 207 //余额不足
-	QueryError                   int = 299 //系统查询异常,请联系客服
+	EmptyResult                  int = 201  //查询无结果
+	ParamError                   int = 4001 //参数错误
+	ParamEmpty                       = 203  //参数为空
+	ParamLenInValid              int = 204  //参数长度小于4
+	Waiting                      int = 205  //等待处理中
+	MoreThanQueryDataNumberLimit int = 206  //请求数据的条数超过上限
+	LeftNumEmpty                     = 4003 //余额不足
+	QueryError                   int = 4004 //系统查询异常,请联系客服
 
 	//系统级错误码
 	InValidKey    = 101 //当前KEY无效
@@ -27,14 +27,17 @@ const (
 	TokenExpired  = 107 //身份验证已过期
 
 	//105非法请求过多,请联系管理员
-	IpInvalid                       = 108 //被禁止的IP
-	MoreThanEveryDayQueryTimesLimit = 109 //请求超过每日系统限制
+	IpInvalid                       = 4005 //被禁止的IP
+	MoreThanEveryDayQueryTimesLimit = 109  //请求超过每日系统限制
 	//108当前相同查询连续出错,请等2小时后重试
 	InterfaceRightInvalid           = 110 //接口权限未开通
 	InterfaceExpired                = 111 //您的账号剩余使用量已过期
 	InterfaceDeleted                = 112 //接口已停用,请联系管理员
 	MoreThanEveryDayDataNumberLimit = 113 //请求超过每日调用总量限制
 	OtherError                      = 199 //系统未知错误,请联系技术客服
+	//
+	SignError   = 4000 //签名错误
+	SignExpired = 4002 //签名过期
 )
 
 type Response struct {
@@ -93,6 +96,6 @@ func FailWithMessage(message string, c *gin.Context) {
 	Result(ERROR, map[string]interface{}{}, message, c)
 }
 
-func FailWithDetailed(code int, data interface{}, message string, c *gin.Context) {
+func FailWithDetailed(code int, data []map[string]interface{}, message string, c *gin.Context) {
 	Result(code, data, message, c)
 }

+ 4 - 1
service/projectDetail.go

@@ -16,7 +16,10 @@ func ProjectDetailData(id string) (data []map[string]interface{}, httpStatus int
 	query := fmt.Sprintf(_query, id, fields)
 	INDEX := core.GetStringConf("es.project.index")
 	TYPE := core.GetStringConf("es.project.itype")
-	infos := db.Es.Get(INDEX, TYPE, query)
+	infos, err := db.Es.Get(INDEX, TYPE, query)
+	if err != nil {
+		return nil, 200, err
+	}
 	if infos != nil && len(*infos) > 0 {
 		data = *infos
 		for _, val := range data {

+ 7 - 4
service/projects.go

@@ -81,8 +81,11 @@ func ProjectListData(productId int, appid, projectName, winner, times string, is
 	}
 	userProduct := &model.UserProduct{}
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appid, ProductID: productId})
-	repl := GetAllByNgram(Es, INDEX, TYPE, qstr, "", pjt_sort, fields, 0, userProduct.DataNumLimitOneTimes, 0, false)
-	if repl != nil && len(*repl) > 0 {
+	repl, err := GetAllByNgram(Es, INDEX, TYPE, qstr, "", pjt_sort, fields, 0, userProduct.DataNumLimitOneTimes, 0, false)
+	if err != nil {
+		err = errors.New("查询失败")
+		return
+	} else if repl != nil && len(*repl) > 0 {
 		data = *repl
 		for _, i := range data {
 			i["project_id"] = SE.EncodeString(utils.ObjToString(i["_id"]))
@@ -92,7 +95,7 @@ func ProjectListData(productId int, appid, projectName, winner, times string, is
 	return
 }
 
-func GetAllByNgram(Es *elastic.Elastic, index, itype, qstr, findfields, order, fields string, start, limit, count int, highlight bool) *[]map[string]interface{} {
+func GetAllByNgram(Es *elastic.Elastic, index, itype, qstr, findfields, order, fields string, start, limit, count int, highlight bool) (*[]map[string]interface{}, error) {
 	if qstr != "" {
 		if highlight {
 			ws := []string{}
@@ -113,6 +116,6 @@ func GetAllByNgram(Es *elastic.Elastic, index, itype, qstr, findfields, order, f
 		global.Logger.Info("GetAllByNgram方法es查询", zap.Any("es语句", qstr))
 		return Es.Get(index, itype, qstr)
 	} else {
-		return nil
+		return nil, nil
 	}
 }

+ 3 - 3
sword_base/elastic/elasticSim.go

@@ -82,7 +82,7 @@ func (e *Elastic) GetEsConn() *es.Client {
 	}
 }
 
-func (e *Elastic) Get(index, itype, query string) *[]map[string]interface{} {
+func (e *Elastic) Get(index, itype, query string) (*[]map[string]interface{}, error) {
 	client := e.GetEsConn()
 	defer func() {
 		go e.DestoryEsConn(client)
@@ -104,7 +104,7 @@ func (e *Elastic) Get(index, itype, query string) *[]map[string]interface{} {
 		searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
 		if err != nil {
 			log.Println("从ES查询出错", err.Error())
-			return nil
+			return nil, err
 		}
 		if searchResult.Hits != nil {
 			resNum := len(searchResult.Hits.Hits)
@@ -121,7 +121,7 @@ func (e *Elastic) Get(index, itype, query string) *[]map[string]interface{} {
 			}
 		}
 	}
-	return &res
+	return &res, nil
 }
 
 //关闭elastic

+ 12 - 0
sword_base/utils/stringutil.go

@@ -148,3 +148,15 @@ func ObjToString(old interface{}) string {
 		return r
 	}
 }
+
+/**
+产生一般订单编号方法
+*/
+func CreateOrderCode() string {
+	return fmt.Sprint(time.Now().Unix()) + fmt.Sprint(GetRandom(6))
+}
+
+func GetDayMinMax(t time.Time) (int64, int64) {
+	min := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local).Unix()
+	return min, min + 86400
+}

+ 41 - 7
test/project/project_interface_test.go

@@ -1,17 +1,51 @@
 package project
 
 import (
+	"sfis/db"
 	"sfis/lock"
+	"sfis/model"
+	"sfis/service"
 	"testing"
 )
 
+var (
+	projectNameArray = []string{"河南大学", "工程建设", "医疗器械"}
+	winnerArray      = []string{""}
+	zbRqArray        = []string{""}
+)
+
 func Test_ProjectInterface(t *testing.T) {
-	leftNumCost := &lock.LeftNumCost{
-		AppID:                "sfPQRYRQMAAwcGBwYBCgcA",
-		ProductID:            1003,
-		LeftNum:              199999,
-		ProductType:          1,
-		DataNumLimitOneTimes: 100,
+	appID := "sfPQRYRQMAAwcGBwYBCgcA"
+	//userName := "赛博英杰"
+	productID := 1003
+	lock.MainLock.Lock()
+	userLock := lock.UserLockMap[appID]
+	lock.MainLock.Unlock()
+	userLock.Lock()
+	userProduct := &model.UserProduct{}
+	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
+
+	check(&lock.LeftNumCost{
+		AppID:                appID,
+		ProductID:            productID,
+		LeftNum:              userProduct.LeftNum,
+		ProductType:          0,
+		DataNumLimitOneTimes: userProduct.DataNumLimitOneTimes,
+		GetData1: func() (i interface{}, i2 int, err error) {
+			return service.ProjectListData("", "", "", false)
+		},
+	})
+}
+
+func check(cost1 lock.Cost) {
+	if b := cost1.Before(); b {
+		data, status, _ := cost1.GetData()
+		if data != nil {
+			data := data.([]map[string]interface{})
+			if len(data) > 0 {
+				cost1.Deduction()
+				cost1.After()
+			}
+		}
 	}
-	leftNumCost.Before()
 }

+ 40 - 9
utils/api_util.go

@@ -1,25 +1,30 @@
 package utils
 
 import (
+	// "context"
+	"fmt"
 	"log"
 	"sfbase/global"
+	"sfbase/redis"
 	"sfis/db"
 	"sfis/lock"
 	"sfis/model"
 	"sfis/model/response"
+	"strings"
 	"time"
 
 	"github.com/gin-gonic/gin"
 	"go.uber.org/zap"
 )
 
-func Check(appID string, productID int, context *gin.Context, getData func() ([]map[string]interface{}, int, error), param, ip string) {
+func Check(appID string, productID int, c *gin.Context, getData func() ([]map[string]interface{}, int, error), param, ip string) {
 	lock.MainLock.Lock()
 	userLock := lock.UserLockMap[appID]
 	lock.MainLock.Unlock()
 	var err error
 	datas := []map[string]interface{}{}
 	orderCode := ""
+	errStr := ""
 	/**
 	第二步:用户接口产品校验-加锁处理
 	*/
@@ -29,10 +34,10 @@ func Check(appID string, productID int, context *gin.Context, getData func() ([]
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
 	//userLock.Unlock()
 	if userProduct.ID == 0 {
-		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口未购买", context)
+		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口未购买", c)
 		return
 	} else if userProduct.InterfaceStatus != 0 {
-		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口暂不提供服务", context)
+		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口暂不提供服务", c)
 		return
 	}
 	//2.2 取用户(产品余量|钱包账户余额)校验-必须加锁
@@ -40,16 +45,36 @@ func Check(appID string, productID int, context *gin.Context, getData func() ([]
 	product := GetProductByID(productID)
 	userLock.Lock()
 	log.Println(param + "锁住......")
-
+	//
+	// ctx, _ := context.WithTimeout(c, 20*time.Second)
+	// go func() {
+	// 	var i = 0
+	// 	for {
+	// 		select {
+	// 		case <-ctx.Done():
+	// 			userLock.Unlock()
+	// 			return
+	// 		case <-time.After(time.Second * time.Duration(2)):
+	// 			i++
+	// 			if i == 10 {
+	// 				userLock.Unlock()
+	// 				return
+	// 			}
+	// 			continue
+	// 		}
+	// 	}
+	// }()
+	// time.Sleep(time.Second * time.Duration(25))
+	//
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
 	// costModel = 0
 	switch costModel {
 	case 0:
 		//按剩余量扣费
-		datas, orderCode, err = costByLeftNum(getData, appID, productID, userProduct, product, param, ip)
+		datas, orderCode, err, errStr = costByLeftNum(getData, appID, productID, userProduct, product, param, ip)
 	case 1:
 		//按账户钱包余额扣费
-		datas, orderCode, err = costByAccountBalance(getData, appID, productID, userProduct, product, param, ip)
+		datas, orderCode, err, errStr = costByAccountBalance(getData, appID, productID, userProduct, product, param, ip)
 	case 2:
 		//优先扣剩余量,剩余量为0,扣钱包余额
 	}
@@ -65,9 +90,15 @@ func Check(appID string, productID int, context *gin.Context, getData func() ([]
 			"user_product_id": userProduct.ID,
 			"create_at":       time.Now().Unix(),
 		})
-		response.OkWithDatas(datas, context)
+		limittodaykey := fmt.Sprintf("limittoday_%d_%d_%s", time.Now().Day(), userProduct.ProductID, userProduct.AppID)
+		redis.Incr("limit", limittodaykey)
+		response.FailWithDetailed(response.SUCCESS, datas, "OK", c)
 	} else {
-		global.Logger.Error("数据库操作失败", zap.Any("error:", err))
-		response.FailWithDetailed(response.InterfaceDeleted, nil, "查询失败", context)
+		if strings.Contains(errStr, "不足") {
+			response.FailWithDetailed(response.LeftNumEmpty, nil, errStr, c)
+		} else {
+			global.Logger.Error("数据库操作失败", zap.Any("error:", err))
+			response.FailWithDetailed(response.QueryError, nil, "内部错误", c)
+		}
 	}
 }

+ 16 - 8
utils/cost_by_account_balance.go

@@ -2,14 +2,12 @@ package utils
 
 import (
 	"errors"
+	"fmt"
 	"log"
 	"sfbase/global"
 	"sfbase/utils"
 	"sfis/db"
 	"sfis/model"
-	"time"
-
-	"fmt"
 
 	"go.uber.org/zap"
 	"gorm.io/gorm"
@@ -18,7 +16,7 @@ import (
 /**
 扣账户余额
 */
-func costByAccountBalance(getData func() ([]map[string]interface{}, int, error), appID string, productID int, userProduct *model.UserProduct, product *model.Product, param, ip string) ([]map[string]interface{}, string, error) {
+func costByAccountBalance(getData func() ([]map[string]interface{}, int, error), appID string, productID int, userProduct *model.UserProduct, product *model.Product, param, ip string) ([]map[string]interface{}, string, error, string) {
 	productType := product.ProductType
 	//productUnit := product.UnitPrice
 	// if productType == 0 {
@@ -30,21 +28,31 @@ func costByAccountBalance(getData func() ([]map[string]interface{}, int, error),
 	// }
 	datas := []map[string]interface{}{}
 	var err error
+	errStr := ""
 	orderCode := ""
-	data, statusCode, _ := execute(getData, appID, productID)
+	data, statusCode, errs := execute(getData, appID, productID)
+	if errs != nil {
+		return nil, "", errs, "查询失败"
+	}
 	beforeJudge, payMoney := beforeCheck(productType, product.UnitPrice, len(data), userProduct)
 	if beforeJudge {
 		global.Logger.Info("交易金额", zap.Any("payMoney:", payMoney))
-		orderCode, err = afterCheck(len(data), payMoney, userProduct, statusCode, param, ip)
 		if err != nil {
+			errStr = "内部错误"
 			global.Logger.Error("数据库操作失败", getUserProductError(appID, productID, err)...)
 		} else {
 			datas = data
+			if len(datas) == 0 {
+				global.Logger.Info("无数据", getUserProductError(appID, productID, err)...)
+			} else {
+				orderCode, err = afterCheck(len(data), payMoney, userProduct, statusCode, param, ip)
+			}
 		}
 	} else {
+		errStr = "余额不足"
 		err = errors.New("剩余余额不足")
 	}
-	return datas, orderCode, err
+	return datas, orderCode, err, errStr
 }
 
 func beforeCheck(productType, unitPrice, dataLen int, userProduct *model.UserProduct) (bool, int) {
@@ -75,7 +83,7 @@ func afterCheck(dataLen, payMoney int, userProduct *model.UserProduct, statusCod
 	userAccount := &model.UserAccount{}
 	db.GetSFISDB().First(userAccount, &model.UserAccount{AppID: userProduct.AppID})
 	var errs error
-	orderCode := fmt.Sprint(time.Now().Year()) + fmt.Sprint(utils.GetRandom(8))
+	orderCode := utils.CreateOrderCode()
 	//按次扣费-(每调一次剩余量-1)
 	errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
 		orderBefore := userAccount.Money

+ 15 - 11
utils/cost_by_left_num.go

@@ -2,13 +2,11 @@ package utils
 
 import (
 	"errors"
-	"fmt"
 	"log"
 	"sfbase/global"
 	"sfbase/utils"
 	"sfis/db"
 	"sfis/model"
-	"time"
 
 	"gorm.io/gorm"
 )
@@ -16,28 +14,34 @@ import (
 /**
 扣产品剩余量
 */
-func costByLeftNum(getData func() ([]map[string]interface{}, int, error), appID string, productID int, userProduct *model.UserProduct, product *model.Product, param, ip string) ([]map[string]interface{}, string, error) {
+func costByLeftNum(getData func() ([]map[string]interface{}, int, error), appID string, productID int, userProduct *model.UserProduct, product *model.Product, param, ip string) ([]map[string]interface{}, string, error, string) {
 	productType := product.ProductType
 	datas := []map[string]interface{}{}
 	var err error
+	errStr := ""
 	orderCode := ""
 	beforeJudge := before(productType, userProduct)
 	if beforeJudge {
-		data, statusCode, _ := execute(getData, appID, productID)
-		orderCode, err = after(productType, len(data), userProduct, statusCode, param, ip)
-		if err == nil && data != nil && len(data) > 0 {
+		data, statusCode, errs := execute(getData, appID, productID)
+		if errs == nil {
 			datas = data
-		} else {
+			if len(datas) == 0 {
+				global.Logger.Info("无数据", getUserProductError(appID, productID, err)...)
+			}
+			orderCode, err = after(productType, len(data), userProduct, statusCode, param, ip)
 			if err != nil {
+				errStr = "内部错误"
 				global.Logger.Error("数据库操作失败", getUserProductError(appID, productID, err)...)
-			} else {
-				global.Logger.Info("无数据", getUserProductError(appID, productID, err)...)
 			}
+		} else {
+			errStr = "查询错误"
+			global.Logger.Error("查询错误", getUserProductError(appID, productID, err)...)
 		}
 	} else {
+		errStr = "剩余量不足"
 		err = errors.New("剩余量不足")
 	}
-	return datas, orderCode, err
+	return datas, orderCode, err, errStr
 }
 
 /**
@@ -80,7 +84,7 @@ func after(productType int, dataLen int, userProduct *model.UserProduct, statusC
 	productID := userProduct.ProductID
 	userProductID := userProduct.ID
 	var errs error
-	orderCode := fmt.Sprint(time.Now().Year()) + fmt.Sprint(utils.GetRandom(8))
+	orderCode := utils.CreateOrderCode()
 	switch productType {
 	case 0:
 		//按次扣费-(每调一次剩余量-1)