xuzhiheng il y a 4 ans
Parent
commit
7e957a5a7d
8 fichiers modifiés avec 131 ajouts et 54 suppressions
  1. 27 18
      api/v1/projects.go
  2. 0 1
      db/es.go
  3. 4 3
      main.go
  4. 20 1
      model/response/response.go
  5. 25 16
      service/projects.go
  6. 13 7
      utils/api_util.go
  7. 2 1
      utils/cost_by_account_balance.go
  8. 40 7
      utils/cost_by_left_num.go

+ 27 - 18
api/v1/projects.go

@@ -2,13 +2,14 @@ package v1
 
 import (
 	"encoding/json"
-	"github.com/gin-gonic/gin"
-	"go.uber.org/zap"
 	"net/http"
 	"sfbase/global"
 	"sfis/middleware"
 	"sfis/service"
 	"sfis/utils"
+
+	"github.com/gin-gonic/gin"
+	"go.uber.org/zap"
 )
 
 /**
@@ -40,31 +41,39 @@ func getProjectsList(c *gin.Context) {
 	bs, _ := json.Marshal(p)
 	param := string(bs)
 	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)
-	/*data := &map[string]interface{}{}
+	// utils.Check(appID, productID, c, func() ([]interface{}, int, error) {
+	// 	return projectList(projectName, winner, zbRq)
+	// }, param, requestIP)
 	if projectName != "" || winner != "" {
-		global.Logger.Info("666")
-		data = service.ProjectListData(projectName, winner, zbRq)
-	}*/
+		utils.Check(appID, productID, c, func() ([]map[string]interface{}, int, error) {
+			return service.ProjectListData(projectName, winner, zbRq, false)
+		}, param, requestIP)
+	}
 	c.JSON(http.StatusOK, nil)
 }
 
-func projectList(name string, winner string, rq string) ([]interface{}, int, error) {
-	return nil, 0, nil
-}
+// func projectList(name string, winner string, rq string) ([]interface{}, int, error) {
+// 	return nil, 0, nil
+// }
 
 //获取项目列表及详情接口
 func getProjectsListDetail(c *gin.Context) {
-	winner := c.PostForm("s_winner")
-	global.Logger.Info("winner " + winner)
-	data := &map[string]interface{}{}
+	productID := c.MustGet("productID").(int)
+	appID := c.MustGet("appID").(string)
+	requestIP := c.MustGet("requestIP").(string)
+	winner := c.PostForm("winner")
+	p := gin.H{
+		"winner": winner,
+	}
+	bs, _ := json.Marshal(p)
+	param := string(bs)
+	global.Logger.Info("api getProjectList:", zap.Any("productID:", productID), zap.Any("appID", appID), zap.Any("param:", param))
 	if winner != "" {
-		data = service.ProjectListData("", winner, "", true)
-
+		utils.Check(appID, productID, c, func() ([]map[string]interface{}, int, error) {
+			return service.ProjectListData("", winner, "", true)
+		}, param, requestIP)
 	}
-	c.JSON(http.StatusOK, data)
+	c.JSON(http.StatusOK, nil)
 }
 
 //获取项目详情

+ 0 - 1
db/es.go

@@ -29,7 +29,6 @@ func InitEs() {
 		log.Println("EsConfig:", err)
 		return
 	}
-	log.Println("EsConfigs", EsConfigs)
 	Es = &elastic.Elastic{
 		S_esurl: EsConfigs.Project.Addr,
 		I_size:  EsConfigs.Project.Pool,

+ 4 - 3
main.go

@@ -1,7 +1,6 @@
 package main
 
 import (
-	"go.uber.org/zap"
 	"log"
 	"sfbase/core"
 	"sfbase/global"
@@ -12,6 +11,8 @@ import (
 	"sfis/router"
 	"sfis/utils"
 	"sync"
+
+	"go.uber.org/zap"
 )
 
 func main() {
@@ -24,8 +25,8 @@ func main() {
 		log.Println("zap日志初始化异常,清检查后重试")
 	}
 	db.InitDB()
-	//db.InitEs()
-	//db.InitMongo()
+	db.InitEs()
+	db.InitMongo()
 	if db.GetSFISDB() != nil {
 		//todo other caches service or init operation
 		users := make([]*model.User, 0)

+ 20 - 1
model/response/response.go

@@ -1,8 +1,9 @@
 package response
 
 import (
-	"github.com/gin-gonic/gin"
 	"net/http"
+
+	"github.com/gin-gonic/gin"
 )
 
 const (
@@ -42,6 +43,12 @@ type Response struct {
 	Msg  string      `json:"msg"`
 }
 
+type ResponseArr struct {
+	Code int                      `json:"code"`
+	Data []map[string]interface{} `json:"data"`
+	Msg  string                   `json:"msg"`
+}
+
 func Result(code int, data interface{}, msg string, c *gin.Context) {
 	c.JSON(http.StatusOK, Response{
 		code,
@@ -50,6 +57,14 @@ func Result(code int, data interface{}, msg string, c *gin.Context) {
 	})
 }
 
+func ResultArr(code int, data []map[string]interface{}, msg string, c *gin.Context) {
+	c.JSON(http.StatusOK, ResponseArr{
+		code,
+		data,
+		msg,
+	})
+}
+
 func Ok(c *gin.Context) {
 	Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
 }
@@ -62,6 +77,10 @@ func OkWithData(data interface{}, c *gin.Context) {
 	Result(SUCCESS, data, "操作成功", c)
 }
 
+func OkWithDatas(data []map[string]interface{}, c *gin.Context) {
+	Result(SUCCESS, data, "操作成功", c)
+}
+
 func OkWithDetailed(data interface{}, message string, c *gin.Context) {
 	Result(SUCCESS, data, message, c)
 }

+ 25 - 16
service/projects.go

@@ -1,6 +1,7 @@
 package service
 
 import (
+	"errors"
 	"fmt"
 	"sfbase/core"
 	"sfbase/elastic"
@@ -8,6 +9,7 @@ import (
 	"sfis/db"
 	"strconv"
 	"strings"
+	"time"
 )
 
 var (
@@ -23,27 +25,33 @@ var (
 	highlightStr = `%s: {"fragment_size": %d,"number_of_fragments": 1}`
 )
 
-func ProjectListData(projectName, winner, time string, isDetail bool) (data *map[string]interface{}) {
-	global.Logger.Info("projectName " + projectName)
-	global.Logger.Info("winner " + winner)
-	global.Logger.Info("time " + time)
-	time = strings.TrimSpace(time)
+func ProjectListData(projectName, winner, times string, isDetail bool) (data []map[string]interface{}, httpStatus int, err error) {
+	times = strings.TrimSpace(times)
 	winner = strings.TrimSpace(winner)
 	pjt_name := strings.TrimSpace(projectName)
 	pjt_len := len([]rune(pjt_name))
-	data = &map[string]interface{}{}
+	httpStatus = 200
 	qstr := ""
 	timestr := ""
-	if time != "" {
-		start := strings.Split(time, "_")[0]
-		end := strings.Split(time, "_")[1]
-		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": ` + start + `,"lte": ` + end + `}}}`
+	if times != "" {
+		start := times + " 00:00:00"
+		end := times + " 23:59:59"
+		loc, _ := time.LoadLocation("Local")
+		startTimes := ""
+		endTimes := ""
+		if startTime, err := time.ParseInLocation("2006-01-02 15:04:05", start, loc); err == nil {
+			startTimes = fmt.Sprint(startTime.Unix())
 		}
+		if endTime, err := time.ParseInLocation("2006-01-02 15:04:05", end, loc); err == nil {
+			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 + `}}}`
+		// }
 	}
 	if pjt_len >= 4 && winner == "" {
 		qstr = fmt.Sprintf(query, "", fmt.Sprintf(query_string, pjt_name, pjt_name))
@@ -61,6 +69,7 @@ func ProjectListData(projectName, winner, time string, isDetail bool) (data *map
 			qstr = fmt.Sprintf(query, fmt.Sprintf(query_winner, winner)+","+timestr, "")
 		}
 	} else {
+		err = errors.New("项目名长度小于4")
 		return
 	}
 	INDEX := core.GetStringConf("es.project.index")
@@ -76,7 +85,7 @@ func ProjectListData(projectName, winner, time string, isDetail bool) (data *map
 	}
 	repl := GetAllByNgram(Es, INDEX, TYPE, qstr, "", pjt_sort, fields, 0, pjt_count, 0, false)
 	if repl != nil && len(*repl) > 0 {
-		(*data)["data"] = repl
+		data = *repl
 	}
 	return
 }

+ 13 - 7
utils/api_util.go

@@ -1,18 +1,21 @@
 package utils
 
 import (
-	"github.com/gin-gonic/gin"
 	"log"
 	"sfis/db"
 	"sfis/lock"
 	"sfis/model"
 	"sfis/model/response"
+
+	"github.com/gin-gonic/gin"
 )
 
-func Check(appID string, productID int, context *gin.Context, getData func() ([]interface{}, int, error), param, ip string) {
+func Check(appID string, productID int, context *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{}{}
 	/**
 	第二步:用户接口产品校验-加锁处理
 	*/
@@ -23,7 +26,6 @@ func Check(appID string, productID int, context *gin.Context, getData func() ([]
 	//userLock.Unlock()
 	if userProduct.InterfaceStatus != 0 {
 		response.FailWithDetailed(response.InterfaceDeleted, nil, "该用户接口暂不提供服务", context)
-		return
 	}
 	//2.2 取用户(产品余量|钱包账户余额)校验-必须加锁
 	costModel := userProduct.CostModel //扣费模式 0扣余量,1-扣余额
@@ -31,18 +33,22 @@ func Check(appID string, productID int, context *gin.Context, getData func() ([]
 	userLock.Lock()
 	log.Println(param + "锁住......")
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
-	costModel = 0
+	costModel = 0 //
 	switch costModel {
 	case 0:
 		//按剩余量扣费
-		costByLeftNum(getData, appID, productID, userProduct, product, param, ip)
+		datas, err = costByLeftNum(getData, appID, productID, userProduct, product, param, ip)
 	case 1:
 		//按账户钱包余额扣费
-		costByAccountBalance(getData, appID, userProduct, product)
+		datas, err = costByAccountBalance(getData, appID, userProduct, product)
 	case 2:
 		//优先扣剩余量,剩余量为0,扣钱包余额
 	}
 	userLock.Unlock()
 	log.Println(param + "解锁......")
-
+	if err == nil {
+		response.OkWithDatas(datas, context)
+	} else {
+		response.FailWithDetailed(response.InterfaceDeleted, nil, "查询失败", context)
+	}
 }

+ 2 - 1
utils/cost_by_account_balance.go

@@ -5,7 +5,7 @@ import "sfis/model"
 /**
 扣账户余额
 */
-func costByAccountBalance(getData func() ([]interface{},int, error), appID string, userProduct *model.UserProduct, product *model.Product) {
+func costByAccountBalance(getData func() ([]map[string]interface{}, int, error), appID string, userProduct *model.UserProduct, product *model.Product) ([]map[string]interface{}, error) {
 	productType := product.ProductType
 	//productUnit := product.UnitPrice
 	if productType == 0 {
@@ -15,4 +15,5 @@ func costByAccountBalance(getData func() ([]interface{},int, error), appID strin
 		//按条扣费-每调一次
 		//todo 账户余额表user_account的余额 减去 product单价*len(getDataList)
 	}
+	return nil, nil
 }

+ 40 - 7
utils/cost_by_left_num.go

@@ -1,24 +1,40 @@
 package utils
 
 import (
-	"gorm.io/gorm"
+	"errors"
 	"log"
 	"sfbase/global"
 	"sfbase/utils"
 	"sfis/db"
 	"sfis/model"
+
+	"gorm.io/gorm"
 )
 
 /**
 扣产品剩余量
 */
-func costByLeftNum(getData func() ([]interface{}, int, error), appID string, productID int, userProduct *model.UserProduct, product *model.Product, param, ip string) {
+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{}, error) {
 	productType := product.ProductType
+	datas := []map[string]interface{}{}
+	var err error
 	beforeJudge := before(productType, userProduct)
 	if beforeJudge {
 		data, statusCode, _ := execute(getData, appID, productID)
-		after(productType, len(data), userProduct, statusCode, param, ip)
+		err = after(productType, len(data), userProduct, statusCode, param, ip)
+		if err == nil && data != nil && len(data) > 0 {
+			datas = data
+		} else {
+			if err != nil {
+				global.Logger.Error("数据库操作失败", getUserProductError(appID, productID, err)...)
+			} else {
+				global.Logger.Info("无数据", getUserProductError(appID, productID, err)...)
+			}
+		}
+	} else {
+		err = errors.New("剩余量不足")
 	}
+	return datas, err
 }
 
 /**
@@ -45,7 +61,7 @@ func before(productType int, userProduct *model.UserProduct) bool {
 /**
 执行接口查询
 */
-func execute(getData func() ([]interface{}, int, error), appID string, productID int) ([]interface{}, int, error) {
+func execute(getData func() ([]map[string]interface{}, int, error), appID string, productID int) ([]map[string]interface{}, int, error) {
 	data, statusCode, err := getData()
 	if err != nil {
 		global.Logger.Error("调用数据出错:", getUserProductError(appID, productID, err)...)
@@ -56,14 +72,15 @@ func execute(getData func() ([]interface{}, int, error), appID string, productID
 	return data, statusCode, nil
 }
 
-func after(productType int, dataLen int, userProduct *model.UserProduct, statusCode int, param, ip string) {
+func after(productType int, dataLen int, userProduct *model.UserProduct, statusCode int, param, ip string) error {
 	appID := userProduct.AppID
 	productID := userProduct.ProductID
 	userProductID := userProduct.ID
+	var errs error
 	switch productType {
 	case 0:
 		//按次扣费-(每调一次剩余量-1)
-		_ = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
+		errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
 			orderBefore := userProduct.LeftNum
 			orderAfter := userProduct.LeftNum - 1
 			//扣费
@@ -93,13 +110,29 @@ func after(productType int, dataLen int, userProduct *model.UserProduct, statusC
 		})
 	case 1:
 		//按条扣费-(每调一次剩余量-len(getDataList))
-		_ = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
+		errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
+			orderBefore := userProduct.LeftNum
+			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("insert into user_call_record (app_id,user_product_id,status,ip,param) values (?,?,?,?,?)", appID, userProductID, statusCode, ip, param).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
+			}
 			//生订单
+			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
+			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
 }