Browse Source

代码上传

wucan 1 year ago
parent
commit
6444f9c7e9
4 changed files with 178 additions and 19 deletions
  1. 149 0
      controller/v1/test.go
  2. 24 17
      controller/v1/userBehavior.go
  3. 3 0
      route/api.go
  4. 2 2
      utils/time.go

+ 149 - 0
controller/v1/test.go

@@ -0,0 +1,149 @@
+package v1
+
+import (
+	"context"
+	"designs/config"
+	"designs/global"
+	"designs/model"
+	"designs/response"
+	"fmt"
+	"github.com/gin-gonic/gin"
+	"go.mongodb.org/mongo-driver/v2/bson"
+	"strconv"
+	"time"
+)
+
+type logData struct {
+	LogTime time.Time `json:"logTime" gorm:"column:logTime;"`
+	Type    int       `json:"Type"`
+}
+
+func calculateUserOnlineTime(logData []logData) int64 {
+
+	var lastLog int64
+	var isStart bool
+	var onlineTimeTotal int64
+	for k, v := range logData {
+		logTime := v.LogTime.Unix()
+		//如果跟上一次的记录隔的时间超过6分钟,就认为是之前断线了,属于无效数据
+		if k > 0 && logData[k-1].LogTime.Unix()+60*6 < logTime {
+			isStart = false
+			continue
+		}
+
+		if v.Type == 1 && isStart == false {
+			isStart = true
+			lastLog = v.LogTime.Unix()
+			continue
+		}
+
+		if v.Type == 1 && isStart == true {
+			//logTime := v.LogTime.Unix()
+			onlineTimeTotal = onlineTimeTotal + (logTime - lastLog)
+			lastLog = logTime
+			//如果下一次的心跳,间隔时间大于6分钟了,就可以认为,这次就算是结束了
+			if k+1 == len(logData) || logData[k+1].LogTime.Unix() > logTime+60*6 {
+				isStart = false
+			}
+			continue
+		}
+
+		if v.Type == 2 && isStart == true {
+			//logTime := v.LogTime.Unix()
+			onlineTimeTotal = onlineTimeTotal + (logTime - lastLog)
+
+			isStart = false
+			continue
+		}
+
+	}
+
+	return onlineTimeTotal
+}
+
+func SetUserBehaviorBak(c *gin.Context) {
+	//读取出来user数据
+	var users []model.User
+	global.App.DB.Table("user").
+		Where("pf", "=", "tt").
+		Where("gid", "=", "linkup").
+		Where("createdAt", ">=", "2024-11-12").
+		Where("createdAt", "<=", "2024-11-13").Scan(&users)
+
+	collection := global.App.MongoDB.Database("chunhao").Collection("adRelated")
+	for _, user := range users {
+		//查询出reids中的openId
+		userIdKeys := fmt.Sprintf("%s:%s:%s:%v", user.Gid, user.Pf, config.Get("app.user_table_id"), strconv.Itoa(user.UserId))
+
+		userIdData, _ := global.App.Redis.HGetAll(context.Background(), userIdKeys).Result()
+
+		openId := userIdData["openId"]
+		//openId = strconv.Itoa(user.UserId)
+		//查询出在线时长数据
+		var LogData []logData
+		global.App.DB.Table("user_online").
+			Where("pf", user.Pf).
+			Where("gid", user.Gid).
+			Where("userId", user.UserId).Scan(&LogData)
+
+		duration := calculateUserOnlineTime(LogData)
+		//查询出看广告数据
+		var req_count int64
+		var exp_count int64
+		global.App.DB.Table("user_see_ads").
+			Where("pf", user.Pf).
+			Where("gid", user.Gid).
+			Where("userId", user.UserId).Count(&req_count)
+		global.App.DB.Table("user_see_ads").
+			Where("pf", user.Pf).
+			Where("gid", user.Gid).
+			Where("adState", 2).
+			Where("userId", user.UserId).Count(&exp_count)
+		//查询出启动次数
+		var start_num int64
+		global.App.DB.Table("user_login").
+			Where("pf", user.Pf).
+			Where("gid", user.Gid).
+			Where("userId", user.UserId).Count(&start_num)
+
+		//存入mongo
+		adData := struct {
+			Id         string `bson:"_id" json:"_id"`
+			UserId     string `bson:"userId" json:"userId"`
+			Aid        int64  `json:"aid" bson:"aid"` //广告的推广计划id,即广告ID,广告平台配置落地页参数
+			Cid        string `json:"cid" bson:"cid"` //openid的用户点击aid广告进入游戏时的唯一标识,广告平台提供
+			Pid        int64  `json:"pid" bson:"pid"` //广告的项目id(仅巨量引擎存在,腾讯广告时不存在该值),广告平台配置落地页参数
+			CreateTime int64  `bson:"create_time"`    //当前计划的创建时间
+
+			StartNum int     `bson:"startNum" json:"startNum"`   //启动次数
+			Revenue  float32 `bson:"revenue" json:"revenue"`     //当日预估收益
+			Duration int64   `bson:"duration" json:"duration"`   //当日在线时长
+			ReqCount int     `bson:"req_count" json:"req_count"` //当日的激励视频广告请求次数
+			ExpCount int     `bson:"exp_count" json:"exp_count"` //当日的激励视频广告曝光次数
+
+		}{
+			UserId:     user.Gid + "|" + user.Pf + "|" + openId,
+			Id:         user.Gid + "|" + user.Pf + "|" + openId + "|" + "7436301890621997000",
+			Aid:        7436301890621997000,
+			Pid:        0,
+			Cid:        "",
+			Duration:   duration,
+			StartNum:   int(start_num),
+			Revenue:    0,
+			ReqCount:   int(req_count),
+			ExpCount:   int(exp_count),
+			CreateTime: user.CreatedAt.Unix(),
+		}
+		collection.InsertOne(context.Background(), adData)
+		fmt.Println(user.Gid+"|"+user.Pf+"|"+openId, "数据写入完成\n")
+	}
+
+}
+
+func DeleteUserBehaviorBak(c *gin.Context) {
+	collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
+	filter := bson.M{"create_time": bson.M{"$gt": 1}}
+	collection.DeleteMany(context.Background(), filter)
+
+	response.Success(c, gin.H{})
+}

+ 24 - 17
controller/v1/userBehavior.go

@@ -66,24 +66,31 @@ func Summary(c *gin.Context) {
 		return
 	}
 
-	//查询 近7日单设备日均使用时长
-	res, err := service.UserOnlineSummary(form.Gid, form.Pf, "", sevenDayAgo.Format("2006-01-02 15:04:05"), now.Format("2006-01-02 15:04:05"))
-	if err != nil {
-		response.Fail(c, 1001, err.Error())
-		return
-	}
-	var avgTime int
-	for _, v := range res {
-		avgTime = avgTime + int(v)
-	}
+	//从redis中读取缓存
 	var avgTimeString string
-	if avgTime != 0 {
-		avgTime = int(math.Round(float64(avgTime / len(res))))
-		avgTimeString = utils.TimeStampToMDS(avgTime)
-	} else {
-		avgTimeString = "00.00"
-	}
+	avgTimeKey := fmt.Sprintf("%s|%s|avgTime", form.Gid, form.Pf)
+	avgTimeString, _ = global.App.Redis.Get(context.Background(), avgTimeKey).Result()
+	if avgTimeString == "" {
+		//查询 近7日单设备日均使用时长
+		res, err := service.UserOnlineSummary(form.Gid, form.Pf, "", sevenDayAgo.Format("2006-01-02 15:04:05"), now.Format("2006-01-02 15:04:05"))
+		if err != nil {
+			response.Fail(c, 1001, err.Error())
+			return
+		}
+		var avgTime int
+		for _, v := range res {
+			avgTime = avgTime + int(v)
+		}
 
+		if avgTime != 0 {
+			avgTime = int(math.Round(float64(avgTime / len(res))))
+
+			avgTimeString = utils.TimeStampToMDS(avgTime)
+		} else {
+			avgTimeString = "00.00"
+		}
+		global.App.Redis.Set(context.Background(), avgTimeKey, avgTimeString, time.Second*3000)
+	}
 	response.Success(c, gin.H{
 		"data": map[string]interface{}{
 			"userCount":            userCount,
@@ -788,7 +795,7 @@ func SetGameCondition(c *gin.Context) {
 	form := request.Check(c, &struct {
 		Gid              string  `form:"gid" json:"gid" binding:"required"`
 		Pid              int64   `form:"pid" json:"pid" binding:""`
-		Aid              int64   `form:"aid" json:"aid" binding:"required"`
+		Aid              int64   `form:"aid" json:"aid" binding:""`
 		Type             string  `form:"type" json:"type" binding:"required"`
 		StartNum         int     `form:"start_num" json:"start_num" binding:""`
 		EstimatedRevenue float32 `form:"revenue" json:"revenue" binding:""`

+ 3 - 0
route/api.go

@@ -64,4 +64,7 @@ func SetApiGroupRoutes(router *gin.RouterGroup) {
 		GroupV1.POST("/user/setGameCondition", v1.SetGameCondition)
 		GroupV1.POST("/user/gameConditionList", v1.GameConditionList)
 	}
+
+	router.POST("/SetUserBehaviorBak", v1.SetUserBehaviorBak)       //测试接口
+	router.POST("/DeleteUserBehaviorBak", v1.DeleteUserBehaviorBak) //测试接口
 }

+ 2 - 2
utils/time.go

@@ -84,9 +84,9 @@ func GetTimeDayDateFormat(startDate string, endDate string) []string {
 // 时间戳转化为 00:02:37 格式
 func TimeStampToMDS(timestamp int) string {
 
-	hours := timestamp / (60 * 24)
+	hours := timestamp / (60 * 60)
 
-	remainingMinutes := timestamp % (60 * 24)
+	remainingMinutes := timestamp % (60 * 60)
 
 	minutes := remainingMinutes / 60
 	remainingSeconds := timestamp % 60