behavior.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. package v1
  2. import (
  3. "context"
  4. "designs/app/common/response"
  5. "designs/config"
  6. "designs/global"
  7. "designs/model"
  8. "designs/service"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "github.com/gin-gonic/gin"
  13. "go.mongodb.org/mongo-driver/v2/bson"
  14. "strconv"
  15. "time"
  16. )
  17. //func ReceiveUserBehavior(c *gin.Context) {
  18. // form := request.Check(c, &struct {
  19. // Gid string `form:"gid" json:"gid" binding:"required"`
  20. // Pf string `form:"pf" json:"pf" binding:"required"`
  21. // OpenId string `form:"openId" json:"openId" binding:"required"`
  22. // AdData interface{} `form:"adData" json:"adData" binding:""`
  23. // AdFromCount int `form:"adFromCount" json:"adFromCount" binding:""`
  24. // TotalDuration int `form:"totalDuration" json:"totalDuration" binding:""`
  25. // TotalAdReqCount int `form:"totalAdReqCount" json:"totalAdReqCount" binding:""`
  26. // TotalAdEposedCount int `form:"totalAdEposedCount" json:"totalAdEposedCount" binding:""`
  27. // }{})
  28. //
  29. // //if form.AdData != nil {
  30. // // var AdData map[string]interface{}
  31. // //}
  32. // behavior := UserBehavior{
  33. // Id: form.Gid + "|" + form.Pf + "|" + form.OpenId,
  34. // Gid: form.Gid,
  35. // Pf: form.Pf,
  36. // OpenId: form.OpenId,
  37. // AdData: form.AdData,
  38. // AdFromCount: form.AdFromCount,
  39. // TotalDuration: form.TotalDuration,
  40. // TotalAdReqCount: form.TotalAdReqCount,
  41. // TotalAdEposedCount: form.TotalAdEposedCount,
  42. // }
  43. //
  44. // collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  45. //
  46. // filter := bson.M{"_id": behavior.Id}
  47. // result := make(map[string]interface{})
  48. // err := collection.FindOne(context.Background(), filter).Decode(&result)
  49. //
  50. // if len(result) == 0 {
  51. // //新增
  52. // _, err = collection.InsertOne(context.Background(), behavior)
  53. // if err != nil {
  54. // response.Fail(c, 1003, "写入数据失败"+err.Error())
  55. // return
  56. // }
  57. // } else {
  58. // var newAdData AdData
  59. // adData, _ := json.Marshal(form.AdData)
  60. // json.Unmarshal(adData, &newAdData)
  61. //
  62. // var oldAdData AdData
  63. // oldAdDatas, _ := json.Marshal(result["adData"])
  64. // json.Unmarshal(oldAdDatas, &oldAdData)
  65. //
  66. // newAdData.Reported = oldAdData.Reported
  67. //
  68. // //更新到MongoDB 中
  69. // update := bson.M{
  70. // "$set": struct {
  71. // Gid string `bson:"gid" json:"gid"`
  72. // Pf string `bson:"pf" json:"pf"`
  73. // OpenId string `bson:"openId" json:"openId"`
  74. // AdData interface{} `bson:"adData" json:"adData"`
  75. // AdFromCount int `bson:"adFromCount" json:"adFromCount"`
  76. // TotalDuration int `bson:"totalDuration" json:"totalDuration"`
  77. // TotalAdReqCount int `bson:"totalAdReqCount" json:"totalAdReqCount"`
  78. // TotalAdEposedCount int `bson:"totalAdEposedCount" json:"totalAdEposedCount"`
  79. // }{
  80. // Gid: behavior.Gid,
  81. // Pf: behavior.Pf,
  82. // OpenId: behavior.OpenId,
  83. // AdData: newAdData,
  84. // AdFromCount: behavior.AdFromCount,
  85. // TotalDuration: behavior.TotalDuration,
  86. // TotalAdReqCount: behavior.TotalAdReqCount,
  87. // TotalAdEposedCount: behavior.TotalAdEposedCount,
  88. // },
  89. // }
  90. // _, err = collection.UpdateOne(context.Background(), filter, update)
  91. // if err != nil {
  92. // response.Fail(c, 1003, "写入数据失败"+err.Error())
  93. // return
  94. // }
  95. // }
  96. //
  97. // //如果是从广告获取进来的用户,则需要检测是否上传
  98. // if form.AdData != nil {
  99. // res := service.OceanReportAction(behavior.Id)
  100. // if res.Code != 0 {
  101. // //上传出现了问题,或者并没有上传
  102. // global.App.Log.Error(res.Code, res.Message)
  103. // }
  104. // }
  105. //
  106. // response.Success(c, gin.H{})
  107. //}
  108. func CheckUserBehavior(c *gin.Context) {
  109. //response.Success(c, gin.H{"data": "success"})
  110. //return
  111. gid := c.GetString("gid")
  112. pf := c.GetString("pf")
  113. openId := c.GetString("openid")
  114. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  115. //
  116. filter := bson.M{"_id": gid + "|" + pf + "|" + openId}
  117. result := make(map[string]interface{})
  118. collection.FindOne(context.Background(), filter).Decode(&result)
  119. if len(result) == 0 {
  120. response.Success(c, gin.H{
  121. "data": nil,
  122. })
  123. } else {
  124. response.Success(c, gin.H{
  125. "data": result,
  126. })
  127. }
  128. }
  129. func UpdateUserBehavior(c *gin.Context) {
  130. //查出所有需要更新的数据
  131. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  132. filters := bson.M{}
  133. filters["adData"] = bson.M{"$exists": true}
  134. var result []map[string]interface{}
  135. cur, err := collection.Find(context.Background(), filters)
  136. if err != nil {
  137. response.Fail(c, 1001, err.Error())
  138. }
  139. err = cur.All(context.Background(), &result)
  140. if err != nil {
  141. response.Fail(c, 1001, err.Error())
  142. return
  143. }
  144. for _, v := range result {
  145. var adData map[string]interface{}
  146. oldAdDatas, _ := json.Marshal(v["adData"])
  147. json.Unmarshal(oldAdDatas, &adData)
  148. if adData["createtime"] != nil {
  149. //错误数据,需要修正
  150. filter := bson.M{"_id": v["_id"]}
  151. //
  152. adData["createTime"] = adData["createtime"]
  153. adData["adReqCount"] = adData["adreqcount"]
  154. adData["adEposedcount"] = adData["adeposedcount"]
  155. adData["reportUrl"] = adData["reporturl"]
  156. delete(adData, "createtime")
  157. delete(adData, "adreqcount")
  158. delete(adData, "adeposedcount")
  159. delete(adData, "reporturl")
  160. //更新到MongoDB 中
  161. update := bson.M{
  162. "$set": struct {
  163. AdData map[string]interface{} `bson:"adData" json:"adData"`
  164. }{
  165. AdData: adData,
  166. },
  167. }
  168. _, err = collection.UpdateOne(context.Background(), filter, update)
  169. if err != nil {
  170. response.Fail(c, 1003, "写入数据失败"+err.Error())
  171. return
  172. }
  173. }
  174. }
  175. defer cur.Close(context.Background())
  176. //更新成正确的数据
  177. response.Success(c, gin.H{
  178. "data": result,
  179. })
  180. }
  181. func FindUserBehavior(id string) *model.UserBehavior {
  182. filter := bson.M{"_id": id}
  183. var result model.UserBehavior
  184. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  185. err := collection.FindOne(context.Background(), filter).Decode(&result)
  186. if err != nil {
  187. return nil
  188. }
  189. return &result
  190. }
  191. // 新建UserBehavior
  192. func CreateUserBehavior(gid string, pf string, openId string, now time.Time) error {
  193. id := gid + "|" + pf + "|" + openId
  194. Behavior := FindUserBehavior(id)
  195. if Behavior != nil {
  196. //更新start_num参数
  197. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  198. filter := bson.M{"_id": id}
  199. update := bson.M{"$inc": bson.M{"startNum": 1}}
  200. _, err := collection.UpdateOne(context.Background(), filter, update)
  201. if err != nil {
  202. return err
  203. }
  204. //更新关联的广告数据
  205. filter = bson.M{"userId": id}
  206. collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  207. update = bson.M{"$inc": bson.M{"startNum": 1}}
  208. _, err = collection.UpdateMany(context.Background(), filter, update)
  209. if err != nil {
  210. return err
  211. }
  212. return nil
  213. } else {
  214. behavior := model.UserBehavior{
  215. Id: id,
  216. Gid: gid,
  217. Pf: pf,
  218. OpenId: openId,
  219. TotalDuration: 0,
  220. TotalAdReqCount: 0,
  221. TotalAdEposedCount: 0,
  222. RelatedAid: 0,
  223. StartNum: 1,
  224. CreateTime: int(now.Unix()),
  225. CreateDate: now.Format("20060102"),
  226. ActiveStatus: false,
  227. ConversionStatus: false,
  228. RemainData: nil,
  229. }
  230. //新增
  231. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  232. _, err := collection.InsertOne(context.Background(), behavior)
  233. if err != nil {
  234. return err
  235. }
  236. }
  237. //存储在线数据到redis中
  238. global.App.Redis.Set(context.Background(), id+"|online", now.Unix(), time.Second*300)
  239. return nil
  240. }
  241. // 更新UserBehavior 在线时间
  242. func UpdateUserBehaviorDuration(gid string, pf string, openId string, now time.Time, types int) error {
  243. id := gid + "|" + pf + "|" + openId
  244. fmt.Println(now.Format("2006-01-02 15:04:05"))
  245. Behavior := FindUserBehavior(id)
  246. if Behavior == nil {
  247. return errors.New("该用户数据未保存,无法计算在线时间")
  248. }
  249. lastTime, _ := global.App.Redis.Get(context.Background(), id+"|online").Result()
  250. //当状态为在线时,刷新redis数据,状态为2是离线,不刷新
  251. if types == 1 {
  252. global.App.Redis.Set(context.Background(), id+"|online", now.Unix(), time.Second*300)
  253. } else {
  254. global.App.Redis.Del(context.Background(), id+"|online")
  255. }
  256. //fmt.Println("types", types)
  257. //如果redis中没有查到在线状态,那就视为刚刚登录,不增加时间
  258. if lastTime == "" {
  259. return nil
  260. }
  261. //计算时间差
  262. lastTimeUnix, _ := strconv.ParseInt(lastTime, 10, 64)
  263. duration := now.Unix() - lastTimeUnix
  264. //更新到MongoDB 中
  265. update := bson.M{
  266. "$set": struct {
  267. TotalDuration int `bson:"totalDuration" json:"totalDuration"`
  268. }{
  269. TotalDuration: Behavior.TotalDuration + int(duration),
  270. },
  271. }
  272. filter := bson.M{"_id": id}
  273. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  274. _, err := collection.UpdateOne(context.Background(), filter, update)
  275. if err != nil {
  276. return err
  277. }
  278. //更新到当日数据中 todo
  279. //更新到广告关联数据中
  280. filter = bson.M{"userId": id}
  281. collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  282. update = bson.M{"$inc": bson.M{"duration": int(duration)}}
  283. _, err = collection.UpdateMany(context.Background(), filter, update)
  284. if err != nil {
  285. return err
  286. }
  287. return nil
  288. }
  289. // 更新UserBehavior 看广告的数据
  290. func UpdateUserBehaviorAdInfo(gid string, pf string, openId string, adsState int) error {
  291. id := gid + "|" + pf + "|" + openId
  292. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  293. filter := bson.M{"_id": id}
  294. Behavior := FindUserBehavior(id)
  295. if Behavior == nil {
  296. return errors.New("该用户数据未保存,无法累加看广告数据")
  297. }
  298. var AdReqCount int
  299. var AdEposedcount int
  300. if adsState == 0 {
  301. //展示不成功
  302. } else if adsState == 1 {
  303. //展示成功
  304. AdReqCount = 1
  305. } else if adsState == 2 {
  306. //展示成功并且看完
  307. AdReqCount = 1
  308. AdEposedcount = 1
  309. }
  310. //更新到总数据中
  311. update := bson.M{
  312. "$set": struct {
  313. TotalAdReqCount int `bson:"totalAdReqCount" json:"totalAdReqCount"`
  314. TotalAdEposedCount int `bson:"totalAdEposedCount" json:"totalAdEposedCount"`
  315. }{
  316. TotalAdReqCount: Behavior.TotalAdReqCount + AdReqCount,
  317. TotalAdEposedCount: Behavior.TotalAdEposedCount + AdEposedcount,
  318. },
  319. }
  320. _, err := collection.UpdateOne(context.Background(), filter, update)
  321. if err != nil {
  322. return err
  323. }
  324. //更新到当日数据中 todo
  325. //更新到广告关联数据中
  326. filter = bson.M{"userId": id}
  327. collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  328. update = bson.M{"$inc": bson.M{"req_count": AdReqCount, "exp_count": AdEposedcount}}
  329. _, err = collection.UpdateMany(context.Background(), filter, update)
  330. if err != nil {
  331. return err
  332. }
  333. return nil
  334. }
  335. // 上报给巨量对接系统
  336. func CheckUserActive(gid string, pf string, openId string) {
  337. request := map[string]interface{}{
  338. "gid": gid,
  339. "platform": pf,
  340. "openId": openId,
  341. }
  342. data, err := service.CurlPost(config.Get("app.check_user_active"), request, nil)
  343. if err != nil {
  344. global.App.Log.Error("CheckUserActive err: ", err)
  345. return
  346. }
  347. res := make(map[string]interface{})
  348. err = json.Unmarshal([]byte(data), &res)
  349. if err != nil {
  350. global.App.Log.Error("解析返回json错误: ", err)
  351. }
  352. fmt.Println(res)
  353. }
  354. func CheckRetention(gid string, pf string, openId string) {
  355. request := map[string]interface{}{
  356. "gid": gid,
  357. "platform": pf,
  358. "openId": openId,
  359. }
  360. data, err := service.CurlPost(config.Get("app.check_retention"), request, nil)
  361. if err != nil {
  362. global.App.Log.Error("CheckUserActive err: ", err)
  363. return
  364. }
  365. res := make(map[string]interface{})
  366. err = json.Unmarshal([]byte(data), &res)
  367. if err != nil {
  368. global.App.Log.Error("解析返回json错误: ", err)
  369. }
  370. }