jiaojiao7 4 gadi atpakaļ
vecāks
revīzija
b407c191dc

+ 1 - 4
manage/user/user.go

@@ -91,16 +91,13 @@ func userProductChoose(c *gin.Context) {
 	json.Unmarshal([]byte(bs), &dataMap)
 	//log.Println("获取前端参数:", dataMap)
 	appId := sutils.ObjToString(dataMap["appId"])
-	buyType := sutils.IntAll(dataMap["buyType"])
 	products := dataMap["products"]
 	productArr := make([]map[string]interface{}, 0)
 	if _products, ok := products.([]interface{}); ok {
 		productArr = sutils.ObjArrToMapArr(_products)
-		//log.Println(productArr)
 	}
 	if appId != "" && len(productArr) > 0 {
-		status, haveProductId, err := service.CreateUserProduct(appId, productArr, buyType)
-		//log.Println(status, haveProductId, err)
+		status, haveProductId, err := service.CreateUserProduct(appId, productArr)
 		if status == 1 && len(err) == 0 {
 			if haveProductId != "" {
 				response.OkWithMessage("用户已购买过"+haveProductId+"产品,请去充值", c)

+ 18 - 0
model/product.go

@@ -37,3 +37,21 @@ type UserProduct struct {
 func (p *UserProduct) TableName() string {
 	return "user_product"
 }
+
+type UserProductModel struct {
+	ID                   int       `json:"id" gorm:"primaryKey"`
+	AppID                string    `json:"app_id"`
+	ProductID            int       `json:"product_id"`
+	CreateAt             time.Time `json:"-" gorm:"autoCreateTime"` //标签autoCreateTime设置如果字段名字不为CreatAt时候自动插入当前时间
+	CostModel            int       `json:"cost_model"`               //扣费模式(0-按剩余量扣,1-按账户余额扣,2-优先扣剩余量,量为0扣余额)
+	LeftNum              int       `json:"left_num"`                 //剩余量  加锁处理
+	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 *UserProductModel) TableName() string {
+	return "user_product"
+}
+

+ 11 - 85
service/user.go

@@ -3,6 +3,9 @@ package service
 import (
 	"errors"
 	"fmt"
+	"github.com/gin-gonic/gin"
+	"go.uber.org/zap"
+	"gorm.io/gorm"
 	"log"
 	"sfbase/global"
 	"sfbase/utils"
@@ -12,14 +15,9 @@ import (
 	"strconv"
 	"strings"
 	"sync"
-	"time"
-
-	"github.com/gin-gonic/gin"
-	"go.uber.org/zap"
-	"gorm.io/gorm"
 )
 
-func CreateUserProduct(appId string, productArr []map[string]interface{}, buyType int) (status int, haveProductId string, errArr []error) {
+func CreateUserProduct(appId string, productArr []map[string]interface{}) (status int, haveProductId string, errArr []error) {
 	//取出用户锁
 	lock.MainLock.Lock()
 	userLock := lock.UserLockMap[appId]
@@ -32,29 +30,17 @@ func CreateUserProduct(appId string, productArr []map[string]interface{}, buyTyp
 	for _, val := range productArr {
 		productId := utils.IntAll(val["productId"])
 		costModel := utils.IntAll(val["costModel"])
-		leftNum := utils.IntAll(val["leftNum"])
-		tradeMoney := utils.IntAll(val["tradeMoney"]) * 100
-		userProduct := &model.UserProduct{}
+		userProduct := &model.UserProductModel{}
 		userProduct.AppID = appId
-		userProduct.StartAt, _ = time.ParseInLocation("2006-01-02 15:04:05", utils.ObjToString(val["startTime"]), time.Local)
-		userProduct.EndAt, _ = time.ParseInLocation("2006-01-02 15:04:05", utils.ObjToString(val["endTime"]), time.Local)
-		userProduct.LeftNum = leftNum
 		userProduct.CostModel = costModel
+		userProduct.LeftNum = 0
 		userProduct.InterfaceStatus = utils.IntAll(val["interfaceStatus"])
 		userProduct.CallTimesLimitDay = utils.IntAll(val["callTimesLimitDay"])
 		userProduct.DataNumLimitOneTimes = utils.IntAll(val["dataNumOneTimes"])
 		userProduct.ProductID = productId
+		//查询产品是否购买过
 		userProductInfo := model.UserProduct{}
-		product := model.Product{}
-		//查询产品信息,获取购买时候产品单价、试用次数
-		err := db.GetSFISDB().Where("id = ?", productId).Find(&product).Error
-		if err != nil {
-			errArr = append(errArr, err)
-			global.Logger.Error("CreateUserProduct查询product表出错:", zap.Any("err:", err))
-			return 0, haveProductId, errArr
-		}
-		historyUnitPrice := product.UnitPrice
-		err = db.GetSFISDB().Where("product_id = ? and app_id = ?", productId, appId).Find(&userProductInfo).Error
+		err := db.GetSFISDB().Where("product_id = ? and app_id = ?", productId, appId).Find(&userProductInfo).Error
 		if err != nil {
 			errArr = append(errArr, err)
 			global.Logger.Error("CreateUserProduct查询user_product表出错:", zap.Any("err:", err))
@@ -62,70 +48,10 @@ func CreateUserProduct(appId string, productArr []map[string]interface{}, buyTyp
 		}
 		//用户第一次购买产品
 		if userProductInfo.ID == 0 {
-			errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
-				rechargeAmount := 0
-				remark := ""
-				//第一次购买产品赠送试用量
-				testNum := product.TestNum
-				//扣费类型为扣余额,user_buy_record中tradeMoney金额为0
-				if costModel == 0 {
-					rechargeAmount = tradeMoney
-					leftNum += testNum
-				} else if costModel == 1 {
-					leftNum = 0
-					//扣余额,把赠送量转化成金额
-					freeMoney := testNum * product.UnitPrice
-					log.Println(freeMoney, "freeMoney")
-					remark = "充值金额为:" + strconv.Itoa(tradeMoney) + ",赠送金额为:" + strconv.Itoa(freeMoney)
-					tradeMoney += freeMoney
-				}
-				userProduct.LeftNum = leftNum
-				//生用户产品
-				err := tx.Create(userProduct).Error
-				if err != nil {
-					log.Printf("appID:[%s],productId:[%d] execute insert user_product error:[%v]", appId, productId, err)
-					tx.Rollback()
-					return err
-				}
-				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, productId, userProductId, 0, leftNum, rechargeAmount, buyType, historyUnitPrice).Error
-				if err != nil {
-					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 update 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 {
+			err := db.GetSFISDB().Create(userProduct).Error
+			if err != nil {
 				errArr = append(errArr, errs)
-				global.Logger.Info("用户购买产品失败:", zap.Any("appId:", appId), zap.Any("productId:", productId))
+				global.Logger.Info("用户购买产品失败:", zap.Any("appId:", appId), zap.Any("productId:", productId))
 				continue
 			}
 		} else {

+ 20 - 25
static/templates/chooseProduct.html

@@ -16,7 +16,7 @@
             <th style="width: 5%">序号</th>
             <th style="width: 25%">产品名称</th>
             <th style="width: 20%">url</th>
-            <th style="width: 10%">产品单价</th>
+            <th style="width: 10%">产品单价(元)</th>
             <th style="width: 10%">产品类型</th>
             <th style="width: 10%">最小单位</th>
             <th style="width: 10%">试用次数</th>
@@ -27,24 +27,20 @@
         </tbody>
     </table>
     <div class="productInfo" style="margin-top: 40px;margin-left: 20px">
+        <div class="always"></div>
         <span>用户appid:</span><input id="appId" type="text"><br>
-        <span>开始时间:</span><input id="startTime" type="text">
-        <span>结束时间:</span><input id="endTime" type="text" name="" id=""><br>
-        <span>充值量:</span><input id="leftNum" type="text">
         <span>扣费模式:</span>
         <select id="costModel" style="width: 165px;height: 25px;margin-top: 10px">
             <option value="0">剩余量</option>
-            <option value="1">余额</option>
-        </select>
-        <br>
-        <span>充值金额:</span><input id="money" type="text">
+            <option value="1">账户余额</option>
+        </select><br>
         <span>产品状态:</span>
         <select id="interfaceStatus" style="width: 165px;height: 25px;margin-top: 10px">
             <option value="0">开启</option>
             <option value="1">关闭</option>
         </select><br>
         <sapn>每日调用次数:</sapn>
-        <input id="dayLimit" type="text">
+        <input id="dayLimit" type="text"><br>
         <span>每次获取数据量:</span><input id="oneLimit" type="text">
     </div>
     <div style="margin-top: 10px;margin-left: 20px;">
@@ -74,8 +70,10 @@
     <script>
 
         var appid = getParam("appId");
-        if (appid!=""){
+        if (appid != "") {
             $("#appId").val(appid);
+            $("#dayLimit").val(1000);
+            $("#oneLimit").val(100);
         }
         productList();
 
@@ -96,7 +94,7 @@
                             str += '<td style="width: 50px">' + (i + 1) + '</td>';
                             str += '<td style="width: 100px">' + item.name + '</td>';
                             str += '<td style="width: 200px">' + item.url + '</td>';
-                            str += '<td style="width: 100px">' + item.unit_price + '</td>';
+                            str += '<td style="width: 100px">' + (item.unit_price / 100) + '</td>';
                             if (item.product_type === 0) {
                                 str += '<td style="width: 100px">按次</td>';
                             } else {
@@ -118,10 +116,6 @@
         function submit() {
             $(".result").html("");
             var productId = $("input[name='item']:checked").val();
-            var startTime = $("#startTime").val();
-            var endTime = $("#endTime").val();
-            var leftNum = $("#leftNum").val();
-            var money = $("#money").val();
             var costModel = $("#costModel").find("option:selected").val();
             var interfaceStatus = $("#interfaceStatus").find("option:selected").val();
             var dayLimit = $("#dayLimit").val();
@@ -129,25 +123,26 @@
             var appId = $("#appId").val();
             var product = {}
             product["productId"] = productId
-            product["startTime"] = startTime
-            product["endTime"] = endTime
-            product["leftNum"] = leftNum
-            product["tradeMoney"] = money
+            if (productId === "" || productId === undefined) {
+                alert("请选择购买的产品")
+                return
+            }
+            if (appId === "" || appId === undefined) {
+                alert("用户APPID不能为空");
+                return
+            }
             product["costModel"] = costModel
             product["interfaceStatus"] = interfaceStatus
             product["callTimesLimitDay"] = dayLimit
             product["dataNumOneTimes"] = oneLimit
             var products = []
             products.push(product)
-            param = {
+            var param = {
                 "products": products,
                 "appId": appId,
                 "buyType": 1,
-            }
-            console.log("参数:", param)
-            /*if (productId === undefined || productId === "") {
-                return
-            }*/
+            };
+            console.log("参数:", param);
             $.ajax({
                 url: "/manage/user/userProductChoose",
                 data: JSON.stringify(param),

+ 1 - 1
static/templates/login.html

@@ -127,7 +127,7 @@
                                 str += "<td style='width: 100px'>" + item.secret_key + "</td>";
                                 str += "<td style='width: 100px'>" + item.phone + "</td>";
                                 str += "<td style='width: 100px'>" + (item.money / 100) + "</td>";
-                                str += "<td class='handle' style='width: 100px'><a href=\"/page/moneyRechargePage?appId=" + item.app_id + "\">余额充值</a><a href=\"/page/chooseProductPage?appId=" + item.app_id + "\">购买产品</a></td>";
+                                str += "<td class='handle' style='width: 100px'><a href=\"/page/moneyRechargePage?appId=" + item.app_id + "\">账户余额充值</a><a href=\"/page/chooseProductPage?appId=" + item.app_id + "\">购买产品</a></td>";
 
                                 str += "</tr>";
                             }