jiaojiao7 4 жил өмнө
parent
commit
79caf09f26

+ 10 - 11
manage/user/user.go

@@ -24,8 +24,8 @@ func DevUserManageRegister(router *gin.Engine) {
 	userGroup.Use()
 	{
 		userGroup.POST("/create", userCreate)
-		userGroup.POST("/userProjectChoose", userProjectChoose)
-		userGroup.POST("/userProjectList", userProjectList)
+		userGroup.POST("/userProductChoose", userProductChoose)
+		userGroup.POST("/userProductList", userProductList)
 	}
 }
 
@@ -56,9 +56,9 @@ func userCreate(context *gin.Context) {
 
 }
 
-func userProjectChoose(c *gin.Context) {
+func userProductChoose(c *gin.Context) {
 	appId := c.PostForm("appId")
-	projectIds := c.PostForm("projectIds")
+	productIds := c.PostForm("productIds")
 	startTime := c.PostForm("startTime") //时间格式2021-01-11 16:50:06
 	endTime := c.PostForm("endTime")
 	leftNum, _ := strconv.Atoi(c.PostForm("leftNum"))
@@ -69,11 +69,10 @@ func userProjectChoose(c *gin.Context) {
 	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,
+		"ProductIds":        productIds,
 		"startTime":         startTime,
 		"endTime":           endTime,
 		"leftNum":           leftNum,
@@ -84,12 +83,12 @@ func userProjectChoose(c *gin.Context) {
 	}
 	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)
+	global.Logger.Info("api userProductChoose参数:", zap.Any("param", param))
+	service.UserProduct(productIds, appId, startTime, endTime, leftNum, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, tradeMoney, buyType, c)
 }
 
-func userProjectList(c *gin.Context) {
+func userProductList(c *gin.Context) {
 	appId := c.PostForm("appId")
-	global.Logger.Info("manage userProjectList接口参数:", zap.Any("appId", appId))
-	service.UserProjectList(appId, c)
+	global.Logger.Info("manage userProductList接口参数:", zap.Any("appId", appId))
+	service.UserProductList(appId, c)
 }

+ 1 - 0
model/product.go

@@ -29,6 +29,7 @@ type UserProduct struct {
 	InterfaceStatus      int       `json:"interface_status"`         //接口状态(0开启|-1停用|-2异常|-3维护)
 	CallTimesLimitDay    int       `json:"call_times_limit_day"`     //接口调用次数每日上限
 	DataNumLimitOneTimes int       `json:"data_num_limit_one_times"` //接口每次返回数据量上限
+	UpdateAt             time.Time `json:"-" gorm:"autoUpdateTime"`
 }
 
 func (p *UserProduct) TableName() string {

+ 128 - 38
service/user.go

@@ -5,6 +5,7 @@ import (
 	"gorm.io/gorm"
 	"log"
 	"sfis/db"
+	"sfis/lock"
 	"sfis/model"
 	"sfis/model/response"
 	"strconv"
@@ -12,71 +13,160 @@ import (
 	"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 {
+func UserProduct(productIds, appId, startTime, endTime string, leftNum, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, tradeMoney, buyType int, c *gin.Context) {
+	//取出用户锁
+	lock.MainLock.Lock()
+	userLock := lock.UserLockMap[appId]
+	lock.MainLock.Unlock()
+	userLock.Lock()
+	defer userLock.Unlock()
+	productIdsArr := strings.Split(productIds, ",")
+	if len(productIdsArr) > 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
+		for _, v := range productIdsArr {
+			productId, _ := strconv.Atoi(v)
+			userProduct := &model.UserProduct{}
+			userProduct.AppID = appId
+			userProduct.StartAt, _ = time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
+			userProduct.EndAt, _ = time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
+			userProduct.LeftNum = leftNum
+			userProduct.CostModel = costModel
+			userProduct.InterfaceStatus = interfaceStatus
+			userProduct.CallTimesLimitDay = callTimesLimitDay
+			userProduct.DataNumLimitOneTimes = dataNumOneTimes
+			userProduct.ProductID = productId
+			userProductInfo := model.UserProduct{}
+			product := model.Product{}
+			//查询产品信息,获取购买时候产品单价、试用次数
+			err := db.GetSFISDB().Where("id = ?", productId).Find(&product).Error
+			if err != nil {
+				response.FailWithMessage("查询产品信息出错", c)
+				return
+			}
+			historyUnitPrice := product.UnitPrice
+			err = db.GetSFISDB().Where("product_id = ? and app_id = ?", productId, appId).Find(&userProductInfo).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
+			//已选择过该产品--更新用户产品信息
+			if userProductInfo.ID != 0 {
+				before := userProductInfo.LeftNum
+				after := userProductInfo.LeftNum + leftNum
+				userProductId := userProductInfo.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
+					userProduct.LeftNum = userProductInfo.LeftNum + leftNum
+					userProduct.UpdateAt = time.Now()
+					log.Println(userProduct.UpdateAt, "++++++++++++++++++++")
+					err := tx.Exec("update user_product set 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 = ?", after, startTime, endTime, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, productId, appId).Error
 					if err != nil {
-						log.Printf("appID:[%s],projectId:[%d] execute cost user_account error:[%v]", appId, id, err)
+						log.Printf("appID:[%s],productId:[%d] update user_product error:[%v]", appId, productId, 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
+					//扣费类型为扣余额,user_buy_record中tradeMoney金额为0
+					rechargeAmount := 0
+					if costModel == 0 {
+						rechargeAmount = tradeMoney
+					}
+					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, userProductId, before, after, rechargeAmount, 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)
+						log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute insert into user_buy_record error:[%v]", appId, productId, tradeMoney, err)
 						tx.Rollback()
 						return err
 					}
+					//扣费类型是扣余额,充值用户余额
+					if costModel == 1 {
+						userAccount := model.UserAccount{}
+						err = tx.First(&userAccount, model.UserAccount{AppID: appId}).Error
+						if err != nil {
+							log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute find user_account error:[%v]", appId, productId, tradeMoney, err)
+							tx.Rollback()
+							return err
+						}
+						moneyBefore := userAccount.Money
+						moneyAfter := userAccount.Money + tradeMoney
+						//充值
+						err := tx.Exec("update user_account set money = ? WHERE `app_id` = ?", moneyAfter, appId).Error
+						if err != nil {
+							log.Printf("appID:[%s],money:[%d] execute cost user_account error:[%v]", appId, moneyAfter, err)
+							tx.Rollback()
+							return err
+						}
+						//生充值记录
+						err = tx.Exec("insert into user_money_record (app_id,`before`,`after`,trade_money) values (?,?,?,?)", appId, moneyBefore, moneyAfter, tradeMoney).Error
+						if err != nil {
+							log.Printf("appID:[%s],trade_money:[%d] execute insert into user_money_record error:[%v]", appId, tradeMoney, err)
+							tx.Rollback()
+							return err
+						}
+					}
 					return nil
 				})
-			} else {
+			} else { //用户没有购买过改产品
 				errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
+					//扣费类型为扣余额,user_buy_record中tradeMoney金额为0
+					rechargeAmount := 0
+					//第一次购买产品赠送试用量
+					testNum := product.TestNum
+					remark := ""
+					if costModel == 0 {
+						rechargeAmount = tradeMoney
+						leftNum += testNum
+					} else if costModel == 1 {
+						//扣余额,把赠送量转化成金额
+						freeMoney := testNum * product.UnitPrice
+						tradeMoney += freeMoney
+						remark = "充值金额为:" + strconv.Itoa(tradeMoney) + "赠送金额为:" + strconv.Itoa(freeMoney)
+					}
+					userProduct.LeftNum = leftNum
 					//生用户产品
-					err := tx.Create(userProject).Error
+					err := tx.Create(userProduct).Error
 					if err != nil {
-						log.Printf("appID:[%s],projectId:[%d] insert user_project error:[%v]", appId, id, err)
+						log.Printf("appID:[%s],productId:[%d] insert user_product error:[%v]", appId, productId, err)
 						tx.Rollback()
 						return tx.Error
 					}
-					userProjectId := userProject.ID
+					userProductId := userProduct.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
+					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, userProductId, 0, leftNum, rechargeAmount, 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)
+						log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute insert into user_buy_record error:[%v]", appId, productId, tradeMoney, err)
 						tx.Rollback()
 						return err
 					}
+					//扣费类型是扣余额,充值用户余额
+					if costModel == 1 {
+						//第一次购买产品赠送免费次数
+						userAccount := model.UserAccount{}
+						err = tx.First(&userAccount, model.UserAccount{AppID: appId}).Error
+						if err != nil {
+							log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute find user_account error:[%v]", appId, productId, tradeMoney, err)
+							tx.Rollback()
+							return err
+						}
+						moneyBefore := userAccount.Money
+						moneyAfter := userAccount.Money + tradeMoney
+						//充值
+						err := tx.Exec("update user_account set money = ? WHERE `app_id` = ?", moneyAfter, appId).Error
+						if err != nil {
+							log.Printf("appID:[%s],money:[%d] execute cost user_account error:[%v]", appId, moneyAfter, err)
+							tx.Rollback()
+							return err
+						}
+						//生充值记录
+						err = tx.Exec("insert into user_money_record (app_id,`before`,`after`,trade_money,remark) values (?,?,?,?,?)", appId, moneyBefore, moneyAfter, tradeMoney, remark).Error
+						if err != nil {
+							log.Printf("appID:[%s],trade_money:[%d] execute insert into user_money_record error:[%v]", appId, tradeMoney, err)
+							tx.Rollback()
+							return err
+						}
+					}
 					return nil
 				})
 			}
-
 		}
 		if errs == nil {
 			response.Ok(c)
@@ -90,13 +180,13 @@ func UserProject(projectIds, appId, startTime, endTime string, leftNum, costMode
 	response.FailWithMessage("缺少参数", c)
 }
 
-func UserProjectList(appId string, c *gin.Context) {
-	userProject := []model.UserProduct{}
-	err := db.GetSFISDB().Where("app_id = ? and ", appId).Find(&userProject).Error
+func UserProductList(appId string, c *gin.Context) {
+	userProduct := []model.UserProduct{}
+	err := db.GetSFISDB().Where("app_id = ? and ", appId).Find(&userProduct).Error
 	if err != nil {
-		log.Printf("appID:[%s] find into user_project error:[%v]", appId, err)
+		log.Printf("appID:[%s] find into user_product error:[%v]", appId, err)
 		response.FailWithMessage("查询出错", c)
 	} else {
-		response.OkWithData(userProject, c)
+		response.OkWithData(userProduct, c)
 	}
 }

+ 12 - 15
test/manage/user_test.go

@@ -61,18 +61,18 @@ func Test_CreateUser(t *testing.T) {
 	//tradeMoney := 1 * 100 * 10000 //充值1万块钱
 }
 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"
+	appId := "sfGSRYRQMABwMAAgcBHjQt"
+	productIds := "1000"
+	startTime := "2022-01-11 00:00:00"
+	endTime := "2024-01-11 00:00:00"
+	leftNum := "0"
+	costModel := "1"
 	interfaceStatus := "0"
 	callTimesLimitDay := "100"
 	dataNumOneTimes := "100"
 	data := make(url.Values)
 	data["appId"] = []string{appId}
-	data["projectIds"] = []string{projectIds}
+	data["productIds"] = []string{productIds}
 	data["startTime"] = []string{startTime}
 	data["endTime"] = []string{endTime}
 	data["leftNum"] = []string{leftNum}
@@ -80,23 +80,20 @@ func Test_UserProductChoose(t *testing.T) {
 	data["interfaceStatus"] = []string{interfaceStatus}
 	data["callTimesLimitDay"] = []string{callTimesLimitDay}
 	data["dataNumOneTimes"] = []string{dataNumOneTimes}
-	data["tradeMoney"] = []string{"1000"}
+	data["tradeMoney"] = []string{"10000"}
 	data["buyType"] = []string{"1"}
-	data["historyUnitPrice"] = []string{"18"}
-	now := time.Now().Unix()
+	//data["historyUnitPrice"] = []string{"18"}
 
-	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/user/userProjectChoose", map[string]string{
-		"timestamp": fmt.Sprint(now),
-	}, data)
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/user/userProductChoose", map[string]string{}, data)
 	log.Print(string(bs))
 }
 
-func Test_UserProjectList(t *testing.T) {
+func Test_UserProductList(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{
+	bs, _ := sutil.HttpPostForm("http://localhost:8080/manage/user/userProductList", map[string]string{
 		"timestamp": fmt.Sprint(now),
 	}, data)
 	log.Print(string(bs))