test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. package v1
  2. import (
  3. "context"
  4. "designs/config"
  5. "designs/global"
  6. "designs/model"
  7. "designs/response"
  8. "designs/service"
  9. "fmt"
  10. "github.com/gin-gonic/gin"
  11. "go.mongodb.org/mongo-driver/v2/bson"
  12. "os"
  13. "strconv"
  14. "time"
  15. )
  16. type logData struct {
  17. LogTime time.Time `json:"logTime" gorm:"column:logTime;"`
  18. Type int `json:"Type"`
  19. }
  20. func calculateUserOnlineTime(logData []logData) int64 {
  21. var lastLog int64
  22. var isStart bool
  23. var onlineTimeTotal int64
  24. for k, v := range logData {
  25. logTime := v.LogTime.Unix()
  26. //如果跟上一次的记录隔的时间超过6分钟,就认为是之前断线了,属于无效数据
  27. if k > 0 && logData[k-1].LogTime.Unix()+60*6 < logTime {
  28. isStart = false
  29. continue
  30. }
  31. if v.Type == 1 && isStart == false {
  32. isStart = true
  33. lastLog = v.LogTime.Unix()
  34. continue
  35. }
  36. if v.Type == 1 && isStart == true {
  37. //logTime := v.LogTime.Unix()
  38. onlineTimeTotal = onlineTimeTotal + (logTime - lastLog)
  39. lastLog = logTime
  40. //如果下一次的心跳,间隔时间大于6分钟了,就可以认为,这次就算是结束了
  41. if k+1 == len(logData) || logData[k+1].LogTime.Unix() > logTime+60*6 {
  42. isStart = false
  43. }
  44. continue
  45. }
  46. if v.Type == 2 && isStart == true {
  47. //logTime := v.LogTime.Unix()
  48. onlineTimeTotal = onlineTimeTotal + (logTime - lastLog)
  49. isStart = false
  50. continue
  51. }
  52. }
  53. return onlineTimeTotal
  54. }
  55. func SetUserBehaviorBak(c *gin.Context) {
  56. //读取出来user数据
  57. var users []model.User
  58. global.App.DB.Table("user").
  59. Where("pf", "=", "tt").
  60. Where("gid", "=", "linkup").
  61. Where("createdAt", ">=", "2024-11-12").
  62. Where("createdAt", "<=", "2024-11-13").Scan(&users)
  63. collection := global.App.MongoDB.Database("chunhao").Collection("adRelated")
  64. for _, user := range users {
  65. //查询出reids中的openId
  66. userIdKeys := fmt.Sprintf("%s:%s:%s:%v", user.Gid, user.Pf, config.Get("app.user_table_id"), strconv.Itoa(user.UserId))
  67. userIdData, _ := global.App.Redis.HGetAll(context.Background(), userIdKeys).Result()
  68. openId := userIdData["openId"]
  69. //openId = strconv.Itoa(user.UserId)
  70. //查询出在线时长数据
  71. var LogData []logData
  72. global.App.DB.Table("user_online").
  73. Where("pf", user.Pf).
  74. Where("gid", user.Gid).
  75. Where("userId", user.UserId).Scan(&LogData)
  76. duration := calculateUserOnlineTime(LogData)
  77. //查询出看广告数据
  78. var req_count int64
  79. var exp_count int64
  80. global.App.DB.Table("user_see_ads").
  81. Where("pf", user.Pf).
  82. Where("gid", user.Gid).
  83. Where("userId", user.UserId).Count(&req_count)
  84. global.App.DB.Table("user_see_ads").
  85. Where("pf", user.Pf).
  86. Where("gid", user.Gid).
  87. Where("adState", 2).
  88. Where("userId", user.UserId).Count(&exp_count)
  89. //查询出启动次数
  90. var start_num int64
  91. global.App.DB.Table("user_login").
  92. Where("pf", user.Pf).
  93. Where("gid", user.Gid).
  94. Where("userId", user.UserId).Count(&start_num)
  95. //存入mongo
  96. adData := struct {
  97. Id string `bson:"_id" json:"_id"`
  98. UserId string `bson:"userId" json:"userId"`
  99. Aid int64 `json:"aid" bson:"aid"` //广告的推广计划id,即广告ID,广告平台配置落地页参数
  100. Cid string `json:"cid" bson:"cid"` //openid的用户点击aid广告进入游戏时的唯一标识,广告平台提供
  101. Pid int64 `json:"pid" bson:"pid"` //广告的项目id(仅巨量引擎存在,腾讯广告时不存在该值),广告平台配置落地页参数
  102. CreateTime int64 `bson:"create_time"` //当前计划的创建时间
  103. StartNum int `bson:"startNum" json:"startNum"` //启动次数
  104. Revenue float32 `bson:"revenue" json:"revenue"` //当日预估收益
  105. Duration int64 `bson:"duration" json:"duration"` //当日在线时长
  106. ReqCount int `bson:"req_count" json:"req_count"` //当日的激励视频广告请求次数
  107. ExpCount int `bson:"exp_count" json:"exp_count"` //当日的激励视频广告曝光次数
  108. }{
  109. UserId: user.Gid + "|" + user.Pf + "|" + openId,
  110. Id: user.Gid + "|" + user.Pf + "|" + openId + "|" + "7436301890621997000",
  111. Aid: 7436301890621997000,
  112. Pid: 0,
  113. Cid: "",
  114. Duration: duration,
  115. StartNum: int(start_num),
  116. Revenue: 0,
  117. ReqCount: int(req_count),
  118. ExpCount: int(exp_count),
  119. CreateTime: user.CreatedAt.Unix(),
  120. }
  121. collection.InsertOne(context.Background(), adData)
  122. fmt.Println(user.Gid+"|"+user.Pf+"|"+openId, "数据写入完成\n")
  123. }
  124. }
  125. func DeleteUserBehaviorBak(c *gin.Context) {
  126. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  127. filter := bson.M{"create_time": bson.M{"$gt": 1}}
  128. collection.DeleteMany(context.Background(), filter)
  129. response.Success(c, gin.H{})
  130. }
  131. func GetUserNickName(c *gin.Context) {
  132. //读取user表
  133. var count int64
  134. err := global.App.DB.Table("user").Count(&count).Error
  135. if err != nil {
  136. response.Fail(c, 1001, err.Error())
  137. return
  138. }
  139. var i int64
  140. for i = 1; i <= count; i++ {
  141. var user model.User
  142. err = global.App.DB.Table("user").Where("id", i).Find(&user).Error
  143. if err != nil {
  144. response.Fail(c, 1001, err.Error())
  145. return
  146. }
  147. if user.Pf == "web" {
  148. //web跳过
  149. continue
  150. }
  151. userKey := user.Gid + ":" + user.Pf + ":" + config.Get("app.user_table_key") + user.OpenId
  152. userData, err := global.App.Redis.HGetAll(context.Background(), userKey).Result()
  153. if err != nil {
  154. global.App.Log.Error("GetUserData err")
  155. response.Fail(c, 1003, "GetUserData err"+err.Error())
  156. return
  157. }
  158. if userData["head"] != "" {
  159. //有意义的数据
  160. //data := struct {
  161. // ID int `json:"id" gorm:"not null;"`
  162. // Head string `json:"head" gorm:"not null;"`
  163. // NickName string `json:"nickName" gorm:"not null;column:nickName;"`
  164. //}{
  165. // Head: userData["head"],
  166. // NickName: userData["nickName"],
  167. //}
  168. //err = global.App.DB.Table("nickname").Create(&data).Error
  169. //if err != nil {
  170. // response.Fail(c, 1003, "nickname err"+err.Error())
  171. // return
  172. //}
  173. }
  174. }
  175. response.Success(c, gin.H{})
  176. }
  177. // 定义一个函数来执行任务
  178. func WriteDBDataToFile(c *gin.Context) {
  179. // 打开文件准备写入
  180. file, err := os.Create("./nickname.txt")
  181. if err != nil {
  182. response.Fail(c, 1001, fmt.Errorf("无法创建文件: %v", err))
  183. }
  184. defer file.Close()
  185. // 查询数据库
  186. var data []struct {
  187. ID int `json:"id" gorm:"not null;"`
  188. Head string `json:"head" gorm:"not null;"`
  189. NickName string `json:"nickName" gorm:"not null;column:nickName;"`
  190. }
  191. global.App.DB.Table("nickname").Scan(&data)
  192. // 写入列名到文件(可选)
  193. for _, v := range data {
  194. fmt.Println(v)
  195. fmt.Fprintf(file, "%s\t%s\n", v.NickName, v.Head)
  196. }
  197. response.Success(c, gin.H{})
  198. }
  199. // 对打点数据进行汇算
  200. func ActionDataSummary(c *gin.Context) {
  201. now := time.Now()
  202. for i := 1; i <= 30; i++ {
  203. lastDay := now.AddDate(0, 0, -i).Format("20060102")
  204. service.SeeAdsSummary(lastDay)
  205. fmt.Println("用时", time.Since(now))
  206. }
  207. response.Success(c, gin.H{})
  208. }
  209. func BehaviorSummary(c *gin.Context) {
  210. //先查出所有gid
  211. ActiveGid := GetActiveGid()
  212. now := time.Now()
  213. start := now.AddDate(0, 0, -30)
  214. pf := "wx"
  215. //循环一下,查出userId 跟相关的在线数据
  216. for _, gid := range ActiveGid {
  217. start1 := time.Now()
  218. fmt.Println("处理数据开始,gid :", gid)
  219. //查询 30天内的在线数据
  220. SummaryData, err := service.UserOnlineSummary(gid, pf, "", start.Format("2006-01-02 15:04:05"), now.Format("2006-01-02 15:04:05"))
  221. if err != nil {
  222. response.Fail(c, 1001, err.Error())
  223. return
  224. }
  225. //aaa, _ := json.Marshal(SummaryData)
  226. //global.App.Log.Error(string(aaa))
  227. //
  228. //return
  229. fmt.Println("查询在线数据完成:", time.Since(start1))
  230. //查询用户的登录次数
  231. var loginData []struct {
  232. UserId int `json:"userId" gorm:"not null;column:userId;"`
  233. LoginCount int `json:"loginCount" gorm:"not null;column:loginCount;"`
  234. }
  235. loginDataMap := make(map[int]int)
  236. err = global.App.DB.Table("user_login").
  237. Where("gid", gid).
  238. Where("pf", pf).
  239. Group("userId").
  240. Select("count(*) as loginCount", "userId").
  241. Scan(&loginData).Error
  242. if err != nil {
  243. response.Fail(c, 1002, err.Error())
  244. return
  245. }
  246. for _, login := range loginData {
  247. loginDataMap[login.UserId] = login.LoginCount
  248. }
  249. fmt.Println("查询登录数据完成:", time.Since(start1))
  250. //查询用户的看广告次数,广告看完次数
  251. var seeAdsData []struct {
  252. UserId int `json:"userId" gorm:"not null;column:userId;"`
  253. SeeAdsCount int `json:"seeAdsCount" gorm:"not null;column:seeAdsCount;"`
  254. State2Count int `json:"state2Count" gorm:"not null;column:state2Count;"`
  255. }
  256. seeAdsDataMap := make(map[int]int)
  257. seeAdsDataMap2 := make(map[int]int)
  258. err = global.App.DB.Table("user_see_ads").
  259. Where("gid", gid).
  260. Where("pf", pf).
  261. Group("userId").
  262. Select("count(*) as seeAdsCount", "SUM(CASE WHEN adsState = 2 THEN 1 ELSE 0 END) AS state2Count", "userId").
  263. Scan(&seeAdsData).Error
  264. if err != nil {
  265. response.Fail(c, 1003, err.Error())
  266. return
  267. }
  268. for _, ads := range seeAdsData {
  269. seeAdsDataMap[ads.UserId] = ads.SeeAdsCount
  270. seeAdsDataMap2[ads.UserId] = ads.State2Count
  271. }
  272. fmt.Println("查询广告数据完成:", time.Since(start1))
  273. //格式化,存入数据库
  274. var userIdList []model.User
  275. err = global.App.DB.Table("user").Where("gid", gid).
  276. Select("id", "userId").
  277. Where("pf", pf).Scan(&userIdList).Error
  278. if err != nil {
  279. response.Fail(c, 1004, err.Error())
  280. return
  281. }
  282. //fmt.Println(len(userIdList))
  283. userBehavior := make(map[int]model.UserBehavior)
  284. for _, users := range userIdList {
  285. userBehavior[users.UserId] = model.UserBehavior{
  286. ID: users.ID,
  287. Duration: int(SummaryData[users.UserId]),
  288. StartNum: loginDataMap[users.UserId],
  289. AdCount: seeAdsDataMap[users.UserId],
  290. AdExpCount: seeAdsDataMap2[users.UserId],
  291. }
  292. }
  293. //aaa, _ := json.Marshal(userBehavior)
  294. //global.App.Log.Error(string(aaa))
  295. //
  296. //return
  297. var userBehaviorList []model.UserBehavior
  298. for _, Behavior := range userBehavior {
  299. userBehaviorList = append(userBehaviorList, Behavior)
  300. }
  301. err = global.App.DB.Table("user_behavior").CreateInBatches(&userBehaviorList, 1000).Error
  302. if err != nil {
  303. //global.App.Log.Error(userBehavior)
  304. response.Fail(c, 1005, err.Error())
  305. return
  306. }
  307. fmt.Println("存入汇总完成:", time.Since(start1))
  308. }
  309. }