瀏覽代碼

Merge branch 'master' of http://192.168.3.207:10080/group3/SwordFish_Interface_Service

wanghuidong 4 年之前
父節點
當前提交
582ea5807f

+ 18 - 19
api/v1/projects.go

@@ -2,7 +2,6 @@ package v1
 
 
 import (
 import (
 	"encoding/json"
 	"encoding/json"
-	"net/http"
 	"sfbase/global"
 	"sfbase/global"
 	"sfis/middleware"
 	"sfis/middleware"
 	"sfis/service"
 	"sfis/service"
@@ -30,32 +29,24 @@ func getProjectsList(c *gin.Context) {
 	productID := c.MustGet("productID").(int)
 	productID := c.MustGet("productID").(int)
 	appID := c.MustGet("appID").(string)
 	appID := c.MustGet("appID").(string)
 	requestIP := c.MustGet("requestIP").(string)
 	requestIP := c.MustGet("requestIP").(string)
-	projectName := c.PostForm("projectName")
+	projectName := c.PostForm("project_name")
 	winner := c.PostForm("winner")
 	winner := c.PostForm("winner")
-	zbRq := c.PostForm("zbRq")
+	bidTime := c.PostForm("bid_time")
 	p := gin.H{
 	p := gin.H{
 		"projectName": projectName,
 		"projectName": projectName,
 		"winner":      winner,
 		"winner":      winner,
-		"zbRq":        zbRq,
+		"bidTime":     bidTime,
 	}
 	}
 	bs, _ := json.Marshal(p)
 	bs, _ := json.Marshal(p)
 	param := string(bs)
 	param := string(bs)
 	global.Logger.Info("api getProjectList:", zap.Any("productID:", productID), zap.Any("appID", appID), zap.Any("param:", param))
 	global.Logger.Info("api getProjectList:", zap.Any("productID:", productID), zap.Any("appID", appID), zap.Any("param:", param))
-	// utils.Check(appID, productID, c, func() ([]interface{}, int, error) {
-	// 	return projectList(projectName, winner, zbRq)
-	// }, param, requestIP)
 	if projectName != "" || winner != "" {
 	if projectName != "" || winner != "" {
 		utils.Check(appID, productID, c, func() ([]map[string]interface{}, int, error) {
 		utils.Check(appID, productID, c, func() ([]map[string]interface{}, int, error) {
-			return service.ProjectListData(projectName, winner, zbRq, false)
+			return service.ProjectListData(projectName, winner, bidTime, false)
 		}, param, requestIP)
 		}, param, requestIP)
 	}
 	}
-	c.JSON(http.StatusOK, nil)
 }
 }
 
 
-// func projectList(name string, winner string, rq string) ([]interface{}, int, error) {
-// 	return nil, 0, nil
-// }
-
 //获取项目列表及详情接口
 //获取项目列表及详情接口
 func getProjectsListDetail(c *gin.Context) {
 func getProjectsListDetail(c *gin.Context) {
 	productID := c.MustGet("productID").(int)
 	productID := c.MustGet("productID").(int)
@@ -73,16 +64,24 @@ func getProjectsListDetail(c *gin.Context) {
 			return service.ProjectListData("", winner, "", true)
 			return service.ProjectListData("", winner, "", true)
 		}, param, requestIP)
 		}, param, requestIP)
 	}
 	}
-	c.JSON(http.StatusOK, nil)
 }
 }
 
 
 //获取项目详情
 //获取项目详情
 func getProjectDetail(c *gin.Context) {
 func getProjectDetail(c *gin.Context) {
-	id := c.PostForm("projectid")
-	global.Logger.Info("projectid " + id)
-	data := map[string]interface{}{}
+	productID := c.MustGet("productID").(int)
+	appID := c.MustGet("appID").(string)
+	requestIP := c.MustGet("requestIP").(string)
+	_id := c.PostForm("project_id")
+	id := service.SE.DecodeString(_id)
+	p := gin.H{
+		"id": id,
+	}
+	bs, _ := json.Marshal(p)
+	param := string(bs)
+	global.Logger.Info("api getProjectDetail:", zap.Any("productID:", productID), zap.Any("appID", appID), zap.Any("param:", param))
 	if id != "" {
 	if id != "" {
-		data = service.ProjectDetailData(id)
+		utils.Check(appID, productID, c, func() ([]map[string]interface{}, int, error) {
+			return service.ProjectDetailData(id)
+		}, param, requestIP)
 	}
 	}
-	c.JSON(200, data)
 }
 }

+ 1 - 0
main.go

@@ -45,6 +45,7 @@ func main() {
 		global.Logger.Info("初始化产品缓存信息,", zap.Any("产品数量:", len(apis)))
 		global.Logger.Info("初始化产品缓存信息,", zap.Any("产品数量:", len(apis)))
 	}
 	}
 	lock.UserLockMap["sfGSVYRQMAAgkGBAUBJg4f"] = &sync.Mutex{}
 	lock.UserLockMap["sfGSVYRQMAAgkGBAUBJg4f"] = &sync.Mutex{}
+	lock.UserLockMap["sfPQRYRQMAAwcGBwYBCgcA"] = &sync.Mutex{}
 	//全局redis的使用?
 	//全局redis的使用?
 	redis.InitRedis(global.BaseConfig.RedisSession.RedisToken)
 	redis.InitRedis(global.BaseConfig.RedisSession.RedisToken)
 	//启动web server
 	//启动web server

+ 10 - 0
model/product.go

@@ -33,3 +33,13 @@ type UserProduct struct {
 func (p *UserProduct) TableName() string {
 func (p *UserProduct) TableName() string {
 	return "user_product"
 	return "user_product"
 }
 }
+
+type UserAccount struct {
+	ID    int    `json:"id" gorm:"primaryKey"`
+	AppID string `json:"app_id"`
+	Money int    `json:"money"`
+}
+
+func (p *UserAccount) TableName() string {
+	return "user_account"
+}

+ 12 - 8
service/projectDetail.go

@@ -3,22 +3,26 @@ package service
 import (
 import (
 	"fmt"
 	"fmt"
 	"sfbase/core"
 	"sfbase/core"
-	"sfbase/global"
+	"sfbase/utils"
 	"sfis/db"
 	"sfis/db"
 )
 )
 
 
-func ProjectDetailData(id string) map[string]interface{} {
-	global.Logger.Info("id " + id)
-	data := map[string]interface{}{}
+var SE = utils.SimpleEncrypt{Key: "topJYBX2019"}
+
+func ProjectDetailData(id string) (data []map[string]interface{}, httpStatus int, err error) {
+	httpStatus = 200
 	_query := `{"query":{"bool":{"must":[{"term":{"id":"%s"}}],"must_not":[],"should":[]}},"_source":[%s]}`
 	_query := `{"query":{"bool":{"must":[{"term":{"id":"%s"}}],"must_not":[],"should":[]}},"_source":[%s]}`
-	fields := `"s_winner","projectname","projectcode","buyer","buyertel","buyerperson","jgtime","zbtime","bidamount","budget","buyerclass","area","city","list"`
+	fields := `"_id","s_winner","projectname","projectcode","buyer","buyertel","buyerperson","jgtime","zbtime","bidamount","budget","buyerclass","area","city","sourceinfourl"`
 	query := fmt.Sprintf(_query, id, fields)
 	query := fmt.Sprintf(_query, id, fields)
-	global.Logger.Info("query " + query)
 	INDEX := core.GetStringConf("es.project.index")
 	INDEX := core.GetStringConf("es.project.index")
 	TYPE := core.GetStringConf("es.project.itype")
 	TYPE := core.GetStringConf("es.project.itype")
 	infos := db.Es.Get(INDEX, TYPE, query)
 	infos := db.Es.Get(INDEX, TYPE, query)
 	if infos != nil && len(*infos) > 0 {
 	if infos != nil && len(*infos) > 0 {
-		data = (*infos)[0]
+		data = *infos
+		for _, val := range data {
+			val["project_id"] = SE.EncodeString(utils.ObjToString(val["_id"]))
+			delete(val, "_id")
+		}
 	}
 	}
-	return data
+	return data, httpStatus, nil
 }
 }

+ 9 - 11
service/projects.go

@@ -3,9 +3,11 @@ package service
 import (
 import (
 	"errors"
 	"errors"
 	"fmt"
 	"fmt"
+	"go.uber.org/zap"
 	"sfbase/core"
 	"sfbase/core"
 	"sfbase/elastic"
 	"sfbase/elastic"
 	"sfbase/global"
 	"sfbase/global"
+	"sfbase/utils"
 	"sfis/db"
 	"sfis/db"
 	"strconv"
 	"strconv"
 	"strings"
 	"strings"
@@ -16,7 +18,7 @@ var (
 	pjt_count    = 100
 	pjt_count    = 100
 	pjt_field    = `"_id","jgtime","zbtime","projectname","buyer","buyerclass"`
 	pjt_field    = `"_id","jgtime","zbtime","projectname","buyer","buyerclass"`
 	pjt_fields   = `"_id","area","city","bidamount","budget","zbtime","jgtime","projectname","projectcode","s_winner","buyer","buyerclass","buyerperson","buyertel","sourceinfourl"`
 	pjt_fields   = `"_id","area","city","bidamount","budget","zbtime","jgtime","projectname","projectcode","s_winner","buyer","buyerclass","buyerperson","buyertel","sourceinfourl"`
-	pjt_sort     = `{"firsttime":-1}`
+	pjt_sort     = `{"jgtime":-1}`
 	query        = `{"query": {"bool": {"must":[%s],"should":[%s],"minimum_should_match": 1}}}`
 	query        = `{"query": {"bool": {"must":[%s],"should":[%s],"minimum_should_match": 1}}}`
 	query_string = `{"constant_score": {"boost": 2,"query": {"match_phrase": {"projectname.pname": {"analyzer": "my_ngram","query": "%s","slop": 6}}}}},{"multi_match": {"query": "%s","fields": ["projectname.pname"],"analyzer": "ik","minimum_should_match": "100%%"}}`
 	query_string = `{"constant_score": {"boost": 2,"query": {"match_phrase": {"projectname.pname": {"analyzer": "my_ngram","query": "%s","slop": 6}}}}},{"multi_match": {"query": "%s","fields": ["projectname.pname"],"analyzer": "ik","minimum_should_match": "100%%"}}`
 	query_winner = `{"term": {"s_winner": "%s"}}`
 	query_winner = `{"term": {"s_winner": "%s"}}`
@@ -45,13 +47,7 @@ func ProjectListData(projectName, winner, times string, isDetail bool) (data []m
 		if endTime, err := time.ParseInLocation("2006-01-02 15:04:05", end, loc); err == nil {
 		if endTime, err := time.ParseInLocation("2006-01-02 15:04:05", end, loc); err == nil {
 			endTimes = fmt.Sprint(endTime.Unix())
 			endTimes = fmt.Sprint(endTime.Unix())
 		}
 		}
-		// if start == "" && end != "" {
-		// 	timestr = `{"range": {"firsttime": {"lte": ` + end + `}}}`
-		// } else if start != "" && end == "" {
-		// 	timestr = `{"range": {"firsttime": {"gte": ` + start + `}}}`
-		// } else if start != "" && end != "" {
-		timestr = `{"range": {"firsttime": {"gte": ` + startTimes + `,"lte": ` + endTimes + `}}}`
-		// }
+		timestr = `{"range": {"jgtime": {"gte": ` + startTimes + `,"lte": ` + endTimes + `}}}`
 	}
 	}
 	if pjt_len >= 4 && winner == "" {
 	if pjt_len >= 4 && winner == "" {
 		qstr = fmt.Sprintf(query, "", fmt.Sprintf(query_string, pjt_name, pjt_name))
 		qstr = fmt.Sprintf(query, "", fmt.Sprintf(query_string, pjt_name, pjt_name))
@@ -75,8 +71,6 @@ func ProjectListData(projectName, winner, times string, isDetail bool) (data []m
 	INDEX := core.GetStringConf("es.project.index")
 	INDEX := core.GetStringConf("es.project.index")
 	TYPE := core.GetStringConf("es.project.itype")
 	TYPE := core.GetStringConf("es.project.itype")
 	Es := db.GetEs()
 	Es := db.GetEs()
-	global.Logger.Info("INDEX " + INDEX)
-	global.Logger.Info("TYPE " + TYPE)
 	fields := ""
 	fields := ""
 	if isDetail {
 	if isDetail {
 		fields = pjt_fields
 		fields = pjt_fields
@@ -86,6 +80,10 @@ func ProjectListData(projectName, winner, times string, isDetail bool) (data []m
 	repl := GetAllByNgram(Es, INDEX, TYPE, qstr, "", pjt_sort, fields, 0, pjt_count, 0, false)
 	repl := GetAllByNgram(Es, INDEX, TYPE, qstr, "", pjt_sort, fields, 0, pjt_count, 0, false)
 	if repl != nil && len(*repl) > 0 {
 	if repl != nil && len(*repl) > 0 {
 		data = *repl
 		data = *repl
+		for _, i := range data {
+			i["project_id"] = SE.EncodeString(utils.ObjToString(i["_id"]))
+			delete(i, "_id")
+		}
 	}
 	}
 	return
 	return
 }
 }
@@ -108,7 +106,7 @@ func GetAllByNgram(Es *elastic.Elastic, index, itype, qstr, findfields, order, f
 		if start > -1 {
 		if start > -1 {
 			qstr = qstr[:len(qstr)-1] + `,"from":` + strconv.Itoa(start) + `,"size":` + strconv.Itoa(limit) + "}"
 			qstr = qstr[:len(qstr)-1] + `,"from":` + strconv.Itoa(start) + `,"size":` + strconv.Itoa(limit) + "}"
 		}
 		}
-		global.Logger.Info("GetAllByNgram:" + qstr)
+		global.Logger.Info("GetAllByNgram方法es查询",zap.Any("es语句",qstr))
 		return Es.Get(index, itype, qstr)
 		return Es.Get(index, itype, qstr)
 	} else {
 	} else {
 		return nil
 		return nil

+ 22 - 4
sword_base/utils/stringutil.go

@@ -5,11 +5,12 @@ import (
 	cryptoRand "crypto/rand"
 	cryptoRand "crypto/rand"
 	"encoding/hex"
 	"encoding/hex"
 	"fmt"
 	"fmt"
-	"github.com/dchest/captcha"
 	"io"
 	"io"
 	"math/rand"
 	"math/rand"
 	"strings"
 	"strings"
 	"time"
 	"time"
+
+	"github.com/dchest/captcha"
 )
 )
 
 
 func FilterXSS(str string) string {
 func FilterXSS(str string) string {
@@ -58,9 +59,8 @@ func GenerateSimpleToken() string {
 	h.Write([]byte(str))
 	h.Write([]byte(str))
 	return hex.EncodeToString(h.Sum(nil))
 	return hex.EncodeToString(h.Sum(nil))
 }
 }
-//var pool = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@#$"
-
 
 
+//var pool = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@#$"
 
 
 //获取复杂的随机数
 //获取复杂的随机数
 func GetLetterRandom(length int, flag ...bool) string {
 func GetLetterRandom(length int, flag ...bool) string {
@@ -129,4 +129,22 @@ func GetComplexRandom(c, n, l int) string {
 		array[r2] = o
 		array[r2] = o
 	}
 	}
 	return strings.Join(array, "")
 	return strings.Join(array, "")
-}
+}
+
+func GetRandom(n int) string {
+	var idChars = []byte("0123456789")
+	b := captcha.RandomDigits(n)
+	for i, c := range b {
+		b[i] = idChars[c]
+	}
+	return string(b)
+}
+
+func ObjToString(old interface{}) string {
+	if nil == old {
+		return ""
+	} else {
+		r, _ := old.(string)
+		return r
+	}
+}

+ 82 - 14
test/project/project_test.go

@@ -17,6 +17,7 @@ import (
 var (
 var (
 	apiurl = "http://127.0.0.1:8080/sfis/api/v1/projectList"
 	apiurl = "http://127.0.0.1:8080/sfis/api/v1/projectList"
 	// apiurl = "http://127.0.0.1:8080/sfis/api/v1/projectListDetail"
 	// apiurl = "http://127.0.0.1:8080/sfis/api/v1/projectListDetail"
+	SE = utils.SimpleEncrypt{Key: "topJYBX2019"}
 )
 )
 
 
 func Test_ProjectListApi(t *testing.T) {
 func Test_ProjectListApi(t *testing.T) {
@@ -47,13 +48,13 @@ func Test_Project(t *testing.T) {
 func getData1(n int) {
 func getData1(n int) {
 	appID := "sfGSVYRQMAAgkGBAUBJg4f"
 	appID := "sfGSVYRQMAAgkGBAUBJg4f"
 	secretKey := "364xw909"
 	secretKey := "364xw909"
-	projectName := "河南省地税局2021年信息化建设招标项目"
-	winner := "河南拓普计算机" + fmt.Sprint(n)
-	zbRq := "2020-12-02"
+	projectName := "郑州航空港区富士"
+	winner := "中铁十五局集团有限公司"
+	zbRq := "2019-07-15"
 	data := make(url.Values)
 	data := make(url.Values)
-	data["projectName"] = []string{projectName}
+	data["project_name"] = []string{projectName}
 	data["winner"] = []string{winner}
 	data["winner"] = []string{winner}
-	data["zbRq"] = []string{zbRq}
+	data["bid_time"] = []string{zbRq}
 	data["app_id"] = []string{appID}
 	data["app_id"] = []string{appID}
 	now := time.Now().Unix()
 	now := time.Now().Unix()
 	bs, _ := utils.HttpPostForm("http://localhost:8080/sfis/api/v1/projectList", map[string]string{
 	bs, _ := utils.HttpPostForm("http://localhost:8080/sfis/api/v1/projectList", map[string]string{
@@ -63,6 +64,68 @@ func getData1(n int) {
 	log.Print(string(bs))
 	log.Print(string(bs))
 }
 }
 
 
+func Test_ProjectList(t *testing.T) {
+	appID := "sfGSVYRQMAAgkGBAUBJg4f"
+	secretKey := "364xw909"
+	projectName := "洛阳市东环路"
+	winner := "中铁十五局集团有限公司"
+	bidTime1 := "2020-01-14"
+	bidTime := "2020-06-30"
+	bidTime3 := "2020-09-01"
+	// 中标日期 项目名称 中标单位
+	data := make(url.Values)
+	data["project_name"] = []string{projectName}
+	data["winner"] = []string{winner}
+	data["bid_time"] = []string{bidTime1}
+	data["app_id"] = []string{appID}
+	now := time.Now().Unix()
+	bs, _ := utils.HttpPostForm("http://localhost:8080/sfis/api/v1/projectList", map[string]string{
+		"token":     utils.MD5(fmt.Sprintf("%s%d%s", appID, now, secretKey)),
+		"timestamp": fmt.Sprint(now),
+	}, data)
+	log.Print(string(bs))
+	// 中标日期 项目名称
+	data2 := make(url.Values)
+	data2["project_name"] = []string{projectName}
+	data2["bid_time"] = []string{bidTime}
+	data2["app_id"] = []string{appID}
+	now2 := time.Now().Unix()
+	bs2, _ := utils.HttpPostForm("http://localhost:8080/sfis/api/v1/projectList", map[string]string{
+		"token":     utils.MD5(fmt.Sprintf("%s%d%s", appID, now2, secretKey)),
+		"timestamp": fmt.Sprint(now2),
+	}, data2)
+	log.Print(string(bs2))
+	// 中标日期 中标单位
+	data3 := make(url.Values)
+	data3["winner"] = []string{winner}
+	data3["bid_time"] = []string{bidTime3}
+	data3["app_id"] = []string{appID}
+	now3 := time.Now().Unix()
+	bs3, _ := utils.HttpPostForm("http://localhost:8080/sfis/api/v1/projectList", map[string]string{
+		"token":     utils.MD5(fmt.Sprintf("%s%d%s", appID, now3, secretKey)),
+		"timestamp": fmt.Sprint(now2),
+	}, data3)
+	log.Print(string(bs3))
+
+}
+// 列表详情测试用例
+func Test_ProjectListDetail(t *testing.T) {
+	appID := "sfGSVYRQMAAgkGBAUBJg4f"
+	secretKey := "364xw909"
+	data1 := make(url.Values)
+	data1["app_id"] = []string{appID}
+	data1["winner"] = []string{"中铁十五局集团有限公司"}
+
+	now := time.Now().Unix()
+	bs, _ := utils.HttpPostForm("http://localhost:8080/sfis/api/v1/projectListDetail", map[string]string{
+		"token":     utils.MD5(fmt.Sprintf("%s%d%s", appID, now, secretKey)),
+		"timestamp": fmt.Sprint(now),
+	}, data1)
+	log.Print(string(bs))
+
+}
+
+
 func getData() {
 func getData() {
 	data := post(apiurl, map[string]string{
 	data := post(apiurl, map[string]string{
 		"projectname": "河南大学",
 		"projectname": "河南大学",
@@ -73,15 +136,20 @@ func getData() {
 }
 }
 
 
 //获取项目详情测试用例
 //获取项目详情测试用例
-// func Test_ProjectDetails(t *testing.T) {
-// 	data := post("http://127.0.0.1:8080/sfis/api/v1/projectDetail", map[string]string{
-// 		"projectid": "5f6b4e12499cb0822d39c68f",
-// 	})
-// 	res := map[string]interface{}{}
-// 	s, _ := json.Marshal(data)
-// 	json.Unmarshal(s, &res)
-// 	log.Println("数据:", res)
-// }
+func Test_ProjectDetails(t *testing.T) {
+	appID := "sfPQRYRQMAAwcGBwYBCgcA"
+	secretKey := "a8Iws4mE"
+	data := make(url.Values)
+	projectId := SE.EncodeString("5f6b4e12499cb0822d39c68f")
+	data["project_id"] = []string{projectId}
+	data["app_id"] = []string{appID}
+	now := time.Now().Unix()
+	bs, _ := utils.HttpPostForm("http://localhost:8080/sfis/api/v1/projectDetail", map[string]string{
+		"token":     utils.MD5(fmt.Sprintf("%s%d%s", appID, now, secretKey)),
+		"timestamp": fmt.Sprint(now),
+	}, data)
+	log.Print(string(bs))
+}
 
 
 func post(url string, form map[string]string) (data map[string]interface{}) {
 func post(url string, form map[string]string) (data map[string]interface{}) {
 	str := ""
 	str := ""

+ 8 - 3
utils/api_util.go

@@ -24,23 +24,28 @@ func Check(appID string, productID int, context *gin.Context, getData func() ([]
 	userProduct := &model.UserProduct{}
 	userProduct := &model.UserProduct{}
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
 	//userLock.Unlock()
 	//userLock.Unlock()
-	if userProduct.InterfaceStatus != 0 {
+	if userProduct.ID == 0 {
+		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口未购买", context)
+		return
+	}else if userProduct.InterfaceStatus != 0 {
 		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口暂不提供服务", context)
 		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口暂不提供服务", context)
+		return
 	}
 	}
 	//2.2 取用户(产品余量|钱包账户余额)校验-必须加锁
 	//2.2 取用户(产品余量|钱包账户余额)校验-必须加锁
 	costModel := userProduct.CostModel //扣费模式 0扣余量,1-扣余额
 	costModel := userProduct.CostModel //扣费模式 0扣余量,1-扣余额
 	product := GetProductByID(productID)
 	product := GetProductByID(productID)
 	userLock.Lock()
 	userLock.Lock()
 	log.Println(param + "锁住......")
 	log.Println(param + "锁住......")
+
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
-	costModel = 0 //
+	// costModel = 0
 	switch costModel {
 	switch costModel {
 	case 0:
 	case 0:
 		//按剩余量扣费
 		//按剩余量扣费
 		datas, err = costByLeftNum(getData, appID, productID, userProduct, product, param, ip)
 		datas, err = costByLeftNum(getData, appID, productID, userProduct, product, param, ip)
 	case 1:
 	case 1:
 		//按账户钱包余额扣费
 		//按账户钱包余额扣费
-		datas, err = costByAccountBalance(getData, appID, userProduct, product)
+		datas, err = costByAccountBalance(getData, appID, productID, userProduct, product, param, ip)
 	case 2:
 	case 2:
 		//优先扣剩余量,剩余量为0,扣钱包余额
 		//优先扣剩余量,剩余量为0,扣钱包余额
 	}
 	}

+ 97 - 9
utils/cost_by_account_balance.go

@@ -1,19 +1,107 @@
 package utils
 package utils
 
 
-import "sfis/model"
+import (
+	"errors"
+	"log"
+	"sfbase/global"
+	"sfbase/utils"
+	"sfis/db"
+	"sfis/model"
+	"time"
+
+	"fmt"
+
+	"go.uber.org/zap"
+	"gorm.io/gorm"
+)
 
 
 /**
 /**
 扣账户余额
 扣账户余额
 */
 */
-func costByAccountBalance(getData func() ([]map[string]interface{}, int, error), appID string, userProduct *model.UserProduct, product *model.Product) ([]map[string]interface{}, 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{}, error) {
 	productType := product.ProductType
 	productType := product.ProductType
 	//productUnit := product.UnitPrice
 	//productUnit := product.UnitPrice
-	if productType == 0 {
-		//按次扣费-每调一次
-		//todo 账户余额表user_account的余额 减去 product单价*1
-	} else if productType == 1 {
-		//按条扣费-每调一次
-		//todo 账户余额表user_account的余额 减去 product单价*len(getDataList)
+	// if productType == 0 {
+	//按次扣费-每调一次
+	//todo 账户余额表user_account的余额 减去 product单价*1
+	// } else if productType == 1 {
+	//按条扣费-每调一次
+	//todo 账户余额表user_account的余额 减去 product单价*len(getDataList)
+	// }
+	datas := []map[string]interface{}{}
+	var err error
+	data, statusCode, _ := execute(getData, appID, productID)
+	beforeJudge, payMoney := beforeCheck(productType, product.UnitPrice, len(data), userProduct)
+	if beforeJudge {
+		global.Logger.Info("交易金额", zap.Any("payMoney:", payMoney))
+		err = afterCheck(len(data), payMoney, userProduct, statusCode, param, ip)
+		if err != nil {
+			global.Logger.Error("数据库操作失败", getUserProductError(appID, productID, err)...)
+		} else {
+			datas = data
+		}
+	} else {
+		err = errors.New("剩余余额不足")
 	}
 	}
-	return nil, nil
+	return datas, err
+}
+
+func beforeCheck(productType, unitPrice, dataLen int, userProduct *model.UserProduct) (bool, int) {
+	userAccount := &model.UserAccount{}
+	db.GetSFISDB().First(userAccount, &model.UserAccount{AppID: userProduct.AppID})
+	money := 0
+	switch productType {
+	case 0:
+		money = unitPrice
+		//按次扣费-判断left_num
+		if money > userAccount.Money {
+			return false, money
+		}
+	case 1:
+		money = unitPrice * dataLen
+		//按条扣费-判断单次调用的limit
+		if money > userAccount.Money {
+			return false, money
+		}
+	}
+	return true, money
+}
+
+func afterCheck(dataLen, payMoney int, userProduct *model.UserProduct, statusCode int, param, ip string) error {
+	appID := userProduct.AppID
+	productID := userProduct.ProductID
+	userProductID := userProduct.ID
+	userAccount := &model.UserAccount{}
+	db.GetSFISDB().First(userAccount, &model.UserAccount{AppID: userProduct.AppID})
+	var errs error
+	//按次扣费-(每调一次剩余量-1)
+	errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
+		orderBefore := userAccount.Money
+		orderAfter := userAccount.Money - payMoney
+		//扣费
+		err := tx.Exec("update user_account set money = money - ? WHERE `app_id` = ?", fmt.Sprint(payMoney), appID).Error
+		if err != nil {
+			log.Printf("appID:[%s],money:[%d] execute cost money error:[%v]", appID, payMoney, err)
+			tx.Rollback()
+			return err
+		}
+		orderCode := fmt.Sprint(time.Now().Year()) + fmt.Sprint(utils.GetRandom(8))
+		//生调用记录
+		err = tx.Exec("insert into user_call_record (app_id,user_product_id,status,ip,param,order_code) values (?,?,?,?,?,?)", appID, userProductID, statusCode, ip, param, orderCode).Error
+		if err != nil {
+			log.Printf("appID:[%s],productID:[%d] execute insert into user_call_record error:[%v]", appID, productID, err)
+			tx.Rollback()
+			return err
+		}
+		//生订单
+		err = tx.Exec("insert into interface_order (order_code,app_id,user_product_id,`before`,`after`,cost_model,trade_num) values (?,?,?,?,?,?,?)", orderCode, appID, userProductID, orderBefore, orderAfter, 1, payMoney).Error
+		if err != nil {
+			log.Printf("appID:[%s],productID:[%d] execute insert into interface_order error:[%v]", appID, productID, err)
+			tx.Rollback()
+			return err
+		}
+		//存历史数据
+		return nil
+	})
+	return errs
 }
 }

+ 12 - 5
utils/cost_by_left_num.go

@@ -2,11 +2,13 @@ package utils
 
 
 import (
 import (
 	"errors"
 	"errors"
+	"fmt"
 	"log"
 	"log"
 	"sfbase/global"
 	"sfbase/global"
 	"sfbase/utils"
 	"sfbase/utils"
 	"sfis/db"
 	"sfis/db"
 	"sfis/model"
 	"sfis/model"
+	"time"
 
 
 	"gorm.io/gorm"
 	"gorm.io/gorm"
 )
 )
@@ -77,6 +79,7 @@ func after(productType int, dataLen int, userProduct *model.UserProduct, statusC
 	productID := userProduct.ProductID
 	productID := userProduct.ProductID
 	userProductID := userProduct.ID
 	userProductID := userProduct.ID
 	var errs error
 	var errs error
+	orderCode := fmt.Sprint(time.Now().Year()) + fmt.Sprint(utils.GetRandom(8))
 	switch productType {
 	switch productType {
 	case 0:
 	case 0:
 		//按次扣费-(每调一次剩余量-1)
 		//按次扣费-(每调一次剩余量-1)
@@ -91,7 +94,7 @@ func after(productType int, dataLen int, userProduct *model.UserProduct, statusC
 				return err
 				return err
 			}
 			}
 			//生调用记录
 			//生调用记录
-			err = tx.Exec("insert into user_call_record (app_id,user_product_id,status,ip,param) values (?,?,?,?,?)", appID, userProductID, statusCode, ip, param).Error
+			err = tx.Exec("insert into user_call_record (app_id,user_product_id,status,ip,param,order_code) values (?,?,?,?,?,?)", appID, userProductID, statusCode, ip, param, orderCode).Error
 			if err != nil {
 			if err != nil {
 				log.Printf("appID:[%s],productID:[%d] execute insert into user_call_record error:[%v]", appID, productID, err)
 				log.Printf("appID:[%s],productID:[%d] execute insert into user_call_record error:[%v]", appID, productID, err)
 				tx.Rollback()
 				tx.Rollback()
@@ -114,17 +117,21 @@ func after(productType int, dataLen int, userProduct *model.UserProduct, statusC
 			orderBefore := userProduct.LeftNum
 			orderBefore := userProduct.LeftNum
 			orderAfter := userProduct.LeftNum - dataLen
 			orderAfter := userProduct.LeftNum - dataLen
 			//扣费
 			//扣费
-			tx.Exec("update user_product set left_num = IF(`left_num`<1, 0, `left_num`-?) WHERE `app_id` = ? and product_id=?", dataLen, appID, productID)
+			err := tx.Exec("update user_product set left_num = IF(`left_num`<1, 0, `left_num`-?) WHERE `app_id` = ? and product_id=?", dataLen, appID, productID).Error
+			if err != nil {
+				log.Printf("appID:[%s],productID:[%d] execute cost money error:[%v]", appID, productID, err)
+				tx.Rollback()
+				return err
+			}
 			//生调用记录
 			//生调用记录
-			err := tx.Exec("insert into user_call_record (app_id,user_product_id,status,ip,param) values (?,?,?,?,?)", appID, userProductID, statusCode, ip, param).Error
+			err = tx.Exec("insert into user_call_record (app_id,user_product_id,status,ip,param,order_code) values (?,?,?,?,?,?)", appID, userProductID, statusCode, ip, param, orderCode).Error
 			if err != nil {
 			if err != nil {
 				log.Printf("appID:[%s],productID:[%d] execute insert into user_call_record error:[%v]", appID, productID, err)
 				log.Printf("appID:[%s],productID:[%d] execute insert into user_call_record error:[%v]", appID, productID, err)
 				tx.Rollback()
 				tx.Rollback()
 				return err
 				return err
 			}
 			}
 			//生订单
 			//生订单
-			orderCode := utils.GenerateSimpleToken()
-			err = tx.Exec("insert into interface_order (order_code,app_id,user_product_id,`before`,`after`,cost_model,trade_num) values (?,?,?,?,?,?,?)", orderCode, appID, userProductID, orderBefore, orderAfter, 0, 1).Error
+			err = tx.Exec("insert into interface_order (order_code,app_id,user_product_id,`before`,`after`,cost_model,trade_num) values (?,?,?,?,?,?,?)", orderCode, appID, userProductID, orderBefore, orderAfter, 0, dataLen).Error
 			if err != nil {
 			if err != nil {
 				log.Printf("appID:[%s],productID:[%d] execute insert into interface_order error:[%v]", appID, productID, err)
 				log.Printf("appID:[%s],productID:[%d] execute insert into interface_order error:[%v]", appID, productID, err)
 				tx.Rollback()
 				tx.Rollback()