test.go 10 KB

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