xuzhiheng 4 lat temu
rodzic
commit
ae54ff16aa

+ 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() {
 
+func (a *AccountBalanceCost) Before() bool {
+	return false
 }
+
 func (a *AccountBalanceCost) After() {
 
 }

+ 102 - 0
manage/product/product.go

@@ -1 +1,103 @@
 package product
+
+import (
+	"github.com/gin-gonic/gin"
+	"go.uber.org/zap"
+	"sfbase/global"
+	"sfis/db"
+	"sfis/model"
+	"sfis/model/response"
+	"sfis/service"
+	"strconv"
+)
+
+func ProductManageRegister(router *gin.Engine) {
+	productGroup := router.Group("/manage/product/")
+	productGroup.Use()
+	{
+		productGroup.POST("/create", productCreate)
+		productGroup.POST("/delete", productDelete)
+		productGroup.POST("/update", productUpdate)
+		productGroup.POST("/list", productList)
+	}
+}
+
+// 创建产品
+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)
+		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)
+	} else {
+		global.Logger.Info("productCreate Success", zap.Any("product", product))
+		response.OkWithData(product, context)
+	}
+
+}
+
+// 删除产品
+func productDelete(context *gin.Context) {
+	var product model.Product
+	if err := context.ShouldBind(&product); err != nil {
+		response.Fail(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)
+	} else {
+		global.Logger.Info("productDelete Success", zap.Any("id", product.ID))
+		response.OkWithData(product, 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)
+		return
+	}
+
+	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)
+	} else {
+		global.Logger.Info("productUpdate Success", zap.Any("product", product))
+		response.OkWithData(product, context)
+	}
+}
+
+// 产品信息列表
+func productList(context *gin.Context) {
+
+	page, _ := strconv.Atoi(context.Query("page"))
+	limit, _ := strconv.Atoi(context.Query("limit"))
+	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")
+	condMap := map[string]interface{}{
+		"id":           id,
+		"name":         name,
+		"url":          url,
+		"unit_price":   unitPrice,
+		"min_unit":     minUnit,
+		"product_type": productType,
+		"test_num":     testNum,
+	}
+	service.ListProduct(condMap,page,limit,context)
+}

+ 77 - 1
manage/user/user.go

@@ -1,9 +1,22 @@
 package user
 
 import (
+	"encoding/json"
 	"github.com/gin-gonic/gin"
 	"go.uber.org/zap"
+	"log"
 	"sfbase/global"
+
+	sutils "sfbase/utils"
+	"sfis/db"
+	"sfis/lock"
+	"sfis/model"
+	"sfis/model/response"
+	"sfis/service"
+	"sfis/utils"
+	"strconv"
+	"sync"
+	"time"
 )
 
 func DevUserManageRegister(router *gin.Engine) {
@@ -11,9 +24,72 @@ func DevUserManageRegister(router *gin.Engine) {
 	userGroup.Use()
 	{
 		userGroup.POST("/create", userCreate)
+		userGroup.POST("/userProjectChoose", userProjectChoose)
+		userGroup.POST("/userProjectList", userProjectList)
 	}
 }
 
+// 创建用户
 func userCreate(context *gin.Context) {
-	global.Logger.Info("创建user", zap.Any("app_id:", "yhet6332h"), zap.Any("secret_key", "ffh2273hjd"))
+	var user model.User
+	if err := context.ShouldBind(&user); err != nil {
+		response.Fail(context)
+		return
+	}
+	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)
+	} 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)
+	}
+
+}
+
+func userProjectChoose(c *gin.Context) {
+	appId := c.PostForm("appId")
+	projectIds := c.PostForm("projectIds")
+	startTime := c.PostForm("startTime") //时间格式2021-01-11 16:50:06
+	endTime := c.PostForm("endTime")
+	leftNum, _ := strconv.Atoi(c.PostForm("leftNum"))
+	costModel, _ := strconv.Atoi(c.PostForm("costModel"))
+	interfaceStatus, _ := strconv.Atoi(c.PostForm("interfaceStatus"))
+	callTimesLimitDay, _ := strconv.Atoi(c.PostForm("callTimesLimitDay"))
+	dataNumOneTimes, _ := strconv.Atoi(c.PostForm("dataNumOneTimes"))
+	tradeMoney, _ := strconv.Atoi(c.PostForm("tradeMoney"))
+	tradeMoney = tradeMoney * 100
+	buyType, _ := strconv.Atoi(c.PostForm("buyType"))
+	historyUnitPrice, _ := strconv.Atoi(c.PostForm("historyUnitPrice"))
+	log.Println("tradeMoney", tradeMoney)
+	p := gin.H{
+		"appId":             appId,
+		"projectIds":        projectIds,
+		"startTime":         startTime,
+		"endTime":           endTime,
+		"leftNum":           leftNum,
+		"costModel":         costModel,
+		"interfaceStatus":   interfaceStatus,
+		"callTimesLimitDay": callTimesLimitDay,
+		"dataNumOneTimes":   dataNumOneTimes,
+	}
+	bs, _ := json.Marshal(p)
+	param := string(bs)
+	global.Logger.Info("api userProjectChoose参数:", zap.Any("param", param))
+	service.UserProject(projectIds, appId, startTime, endTime, leftNum, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, tradeMoney, buyType, historyUnitPrice, c)
+}
+
+func userProjectList(c *gin.Context) {
+	appId := c.PostForm("appId")
+	global.Logger.Info("manage userProjectList接口参数:", zap.Any("appId", appId))
+	service.UserProjectList(appId, c)
 }

+ 7 - 6
model/product.go

@@ -4,12 +4,13 @@ import "time"
 
 type Product struct {
 	BaseModel
-	Name        string `json:"name"`
-	Path        string `json:"url" gorm:"column:url"`
-	UnitPrice   int    `json:"unit_price"`   //单价
-	MinUnit     int    `json:"min_unit"`     //最小单位
-	ProductType int    `json:"product_type"` //产品类型 按次-0,按条-1
-	TestNum     int    `json:"test_num"`     //试用量
+	ID          int    `json:"id" form:"id" gorm:"primaryKey" binding:"required"`
+	Name        string `json:"name" form:"name"`
+	Path        string `json:"url" gorm:"column:url" form:"url"`
+	UnitPrice   int    `json:"unit_price" form:"unit_price"`     //单价
+	MinUnit     int    `json:"min_unit" form:"min_unit"`         //最小单位
+	ProductType int    `json:"product_type" form:"product_type"` //产品类型 按次-0,按条-1
+	TestNum     int    `json:"test_num" form:"test_num"`         //试用量
 }
 
 func (p *Product) TableName() string {

+ 3 - 3
model/user.go

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

+ 2 - 0
router/route.go

@@ -2,6 +2,7 @@ package router
 
 import (
 	v1 "sfis/api/v1"
+	"sfis/manage/product"
 	"sfis/manage/user"
 
 	"github.com/gin-gonic/gin"
@@ -18,5 +19,6 @@ func InitRouter(middleware ...gin.HandlerFunc) *gin.Engine {
 	v1.ProjectApiRegister(router)
 	v1.RechargeApiRegister(router)
 	user.DevUserManageRegister(router)
+	product.ProductManageRegister(router)
 	return router
 }

+ 45 - 0
service/product.go

@@ -0,0 +1,45 @@
+package service
+
+import (
+	"fmt"
+	"github.com/gin-gonic/gin"
+	"go.uber.org/zap"
+	"sfbase/global"
+	"sfis/db"
+	"sfis/model"
+	"sfis/model/response"
+	"strings"
+)
+
+func ListProduct(condMap map[string]interface{},page int,limit int,context *gin.Context) {
+	// 拼查询sql
+	var products []model.Product
+	var key []string
+	var param []interface{}
+	for k, v := range condMap {
+		if v == "" {
+			continue
+		}
+		var kStr string
+		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)
+	}
+	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)
+	if result.Error != nil {
+		global.Logger.Error("productList Error", zap.Any("condMap", condMap), zap.Any("error", result.Error))
+		response.Fail(context)
+	} else {
+		global.Logger.Info("productList Success", zap.Any("condMap", condMap))
+		response.OkWithData(products, context)
+	}
+
+}

+ 102 - 0
service/user.go

@@ -0,0 +1,102 @@
+package service
+
+import (
+	"github.com/gin-gonic/gin"
+	"gorm.io/gorm"
+	"log"
+	"sfis/db"
+	"sfis/model"
+	"sfis/model/response"
+	"strconv"
+	"strings"
+	"time"
+)
+
+func UserProject(projectIds, appId, startTime, endTime string, leftNum, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, tradeMoney, buyType, historyUnitPrice int, c *gin.Context) {
+	projectIdsArr := strings.Split(projectIds, ",")
+	if len(projectIdsArr) > 0 {
+		var errs error
+		for _, v := range projectIdsArr {
+			userProject := &model.UserProduct{}
+			userProject.AppID = appId
+			userProject.StartAt, _ = time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
+			userProject.EndAt, _ = time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
+			userProject.LeftNum = leftNum
+			userProject.CostModel = costModel
+			userProject.InterfaceStatus = interfaceStatus
+			userProject.CallTimesLimitDay = callTimesLimitDay
+			userProject.DataNumLimitOneTimes = dataNumOneTimes
+			id, _ := strconv.Atoi(v)
+			userProject.ProductID = id
+			userProjectInfo := []model.UserProduct{}
+			err := db.GetSFISDB().Where("product_id = ? and app_id = ?", id, appId).Find(&userProjectInfo).Error
+			if err != nil {
+				response.FailWithMessage("查询用户产品信息出错", c)
+				return
+			}
+			if len(userProjectInfo) > 0 {
+				before := userProjectInfo[0].LeftNum
+				after := userProjectInfo[0].LeftNum + leftNum
+				userProjectId := userProjectInfo[0].ID
+				errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
+					//更新用户产品信息
+					userProject.LeftNum = userProjectInfo[0].LeftNum + leftNum
+					err := tx.Exec("update user_product set left_num = left_num + ?, start_at = ?,end_at = ?,cost_model = ?,interface_status = ?,call_times_limit_day=?,data_num_limit_one_times=? where product_id = ? and app_id = ?", leftNum, startTime, endTime, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, id, appId).Error
+					if err != nil {
+						log.Printf("appID:[%s],projectId:[%d] execute cost user_account error:[%v]", appId, id, err)
+						tx.Rollback()
+						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, id, userProjectId, before, after, tradeMoney, buyType, historyUnitPrice).Error
+					if err != nil {
+						log.Printf("appID:[%s],projectId[%d],trade_money:[%d] execute insert into user_buy_record error:[%v]", appId, id, tradeMoney, err)
+						tx.Rollback()
+						return err
+					}
+					return nil
+				})
+			} else {
+				errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
+					//生用户产品
+					err := tx.Create(userProject).Error
+					if err != nil {
+						log.Printf("appID:[%s],projectId:[%d] insert user_project error:[%v]", appId, id, err)
+						tx.Rollback()
+						return tx.Error
+					}
+					userProjectId := userProject.ID
+					//生成购买产品记录
+					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, id, userProjectId, 0, leftNum, tradeMoney, buyType, historyUnitPrice).Error
+					if err != nil {
+						log.Printf("appID:[%s],projectId[%d],trade_money:[%d] execute insert into user_buy_record error:[%v]", appId, id, tradeMoney, err)
+						tx.Rollback()
+						return err
+					}
+					return nil
+				})
+			}
+
+		}
+		if errs == nil {
+			response.Ok(c)
+			return
+		} else {
+			response.FailWithMessage("购买产品失败", c)
+			return
+		}
+
+	}
+	response.FailWithMessage("缺少参数", c)
+}
+
+func UserProjectList(appId string, c *gin.Context) {
+	userProject := []model.UserProduct{}
+	err := db.GetSFISDB().Where("app_id = ? and ", appId).Find(&userProject).Error
+	if err != nil {
+		log.Printf("appID:[%s] find into user_project error:[%v]", appId, err)
+		response.FailWithMessage("查询出错", c)
+	} else {
+		response.OkWithData(userProject, c)
+	}
+}

+ 97 - 0
test/manage/product_test.go

@@ -0,0 +1,97 @@
+package manage
+
+import (
+	"log"
+	"net/url"
+	sutil "sfbase/utils"
+	"sfis/model"
+	"strconv"
+	"testing"
+)
+
+// 新增产品测试用例
+func Test_CreateProduct(t *testing.T) {
+	product1 := &model.Product{
+		ID:          2006,
+		Name:        "行业中标数据",
+		Path:        "/path2002",
+		UnitPrice:   50, //单价精确到分  5毛
+		MinUnit:     1,  //最小单位1,即 5毛/条
+		ProductType: 1,  //产品类型 0-按次 1-按条
+		TestNum:     200,
+	}
+	log.Println("productCreate testing......")
+	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)}
+
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/product/create", map[string]string{}, data)
+	log.Print(string(bs))
+}
+
+// 删除产品 测试用例
+func Test_DeleteProduct(t *testing.T) {
+	productId := "2002"
+	log.Println("productDelete testing......")
+	data := make(url.Values)
+	data["id"] = []string{productId}
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/product/delete", map[string]string{}, data)
+	log.Print(string(bs))
+}
+
+// 修改产品信息测试
+func Test_UpdateProduct(t *testing.T) {
+	log.Println("productUpdate testing......")
+	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["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))
+}
+
+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,
+	//}
+	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)}
+
+
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/product/list?page=1&&limit=3", map[string]string{}, data)
+	log.Print(string(bs))
+}
+

+ 74 - 6
test/manage/user_test.go

@@ -1,9 +1,14 @@
 package manage
 
 import (
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
 	"log"
+	"net/http"
+	"net/url"
 	sutil "sfbase/utils"
-	"sfis/utils"
+	"strings"
 	"testing"
 	"time"
 )
@@ -33,11 +38,19 @@ func init() {
 	//todo init connection db operation
 }
 func Test_CreateUser(t *testing.T) {
-	//log.Println("devUserCreate testing......")
-	appID := utils.GetAppID(time.Now().Unix())
-	secretKey := sutil.GetComplexRandom(8, 3, 5)
+	log.Println("devUserCreate testing......")
+	//appID := utils.GetAppID(time.Now().Unix())
+	//secretKey := sutil.GetComplexRandom(8, 3, 5)
 
-	log.Printf("create successful appID:[%s],secretKey:[%s]", appID, secretKey)
+	data := make(url.Values)
+	data["name"] = []string{"河南拓普"}
+	data["phone"] = []string{"18238182402"}
+	data["ip_white_list"] = []string{"*"}
+
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/user/create", map[string]string{}, data)
+	log.Print(string(bs))
+
+	//log.Printf("create successful appID:[%s],secretKey:[%s]", appID, secretKey)
 
 	//创建用户、给用户开通接口产品时候有以下几种情况
 	//1.线上给账户充值10000块(user_account),不去实际购买产品,无购买记录,用户产品表无剩余量(left_num为0).此时又分两种情况
@@ -47,6 +60,61 @@ func Test_CreateUser(t *testing.T) {
 	//appID := ""
 	//tradeMoney := 1 * 100 * 10000 //充值1万块钱
 }
-func chooseUserProduct(appID string, tradeMoney int) {
+func Test_UserProductChoose(t *testing.T) {
+	appId := "sfPQRYRQMAAwcGBwYBCgcA"
+	projectIds := "1009"
+	startTime := "2021-01-11 00:00:00"
+	endTime := "2022-01-11 00:00:00"
+	leftNum := "10000"
+	costModel := "0"
+	interfaceStatus := "0"
+	callTimesLimitDay := "100"
+	dataNumOneTimes := "100"
+	data := make(url.Values)
+	data["appId"] = []string{appId}
+	data["projectIds"] = []string{projectIds}
+	data["startTime"] = []string{startTime}
+	data["endTime"] = []string{endTime}
+	data["leftNum"] = []string{leftNum}
+	data["costModel"] = []string{costModel}
+	data["interfaceStatus"] = []string{interfaceStatus}
+	data["callTimesLimitDay"] = []string{callTimesLimitDay}
+	data["dataNumOneTimes"] = []string{dataNumOneTimes}
+	data["tradeMoney"] = []string{"1000"}
+	data["buyType"] = []string{"1"}
+	data["historyUnitPrice"] = []string{"18"}
+	now := time.Now().Unix()
+
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/user/userProjectChoose", map[string]string{
+		"timestamp": fmt.Sprint(now),
+	}, data)
+	log.Print(string(bs))
+}
 
+func Test_UserProjectList(t *testing.T) {
+	appId := "sfPQRYRQMAAwcGBwYBCgcA"
+	data := make(url.Values)
+	data["appId"] = []string{appId}
+	now := time.Now().Unix()
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/user/userProjectList", map[string]string{
+		"timestamp": fmt.Sprint(now),
+	}, data)
+	log.Print(string(bs))
+}
+
+func post(url string, form map[string]string) (data map[string]interface{}) {
+	str := ""
+	for k, v := range form {
+		str += "&" + k + "=" + v
+	}
+	log.Println(str)
+	res, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(str))
+	if err != nil {
+		log.Println("post err:", err.Error())
+	} else if res.Body != nil {
+		defer res.Body.Close()
+		bs, _ := ioutil.ReadAll(res.Body)
+		json.Unmarshal(bs, &data)
+	}
+	return
 }

+ 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()
 }