behavior.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. gid := c.GetString("gid")
  110. pf := c.GetString("pf")
  111. openId := c.GetString("openid")
  112. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  113. //
  114. filter := bson.M{"_id": gid + "|" + pf + "|" + openId}
  115. result := make(map[string]interface{})
  116. collection.FindOne(context.Background(), filter).Decode(&result)
  117. if len(result) == 0 {
  118. response.Success(c, gin.H{
  119. "data": nil,
  120. })
  121. } else {
  122. response.Success(c, gin.H{
  123. "data": result,
  124. })
  125. }
  126. }
  127. func UpdateUserBehavior(c *gin.Context) {
  128. //查出所有需要更新的数据
  129. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  130. filters := bson.M{}
  131. filters["adData"] = bson.M{"$exists": true}
  132. var result []map[string]interface{}
  133. cur, err := collection.Find(context.Background(), filters)
  134. if err != nil {
  135. response.Fail(c, 1001, err.Error())
  136. }
  137. err = cur.All(context.Background(), &result)
  138. if err != nil {
  139. response.Fail(c, 1001, err.Error())
  140. return
  141. }
  142. for _, v := range result {
  143. var adData map[string]interface{}
  144. oldAdDatas, _ := json.Marshal(v["adData"])
  145. json.Unmarshal(oldAdDatas, &adData)
  146. if adData["createtime"] != nil {
  147. //错误数据,需要修正
  148. filter := bson.M{"_id": v["_id"]}
  149. //
  150. adData["createTime"] = adData["createtime"]
  151. adData["adReqCount"] = adData["adreqcount"]
  152. adData["adEposedcount"] = adData["adeposedcount"]
  153. adData["reportUrl"] = adData["reporturl"]
  154. delete(adData, "createtime")
  155. delete(adData, "adreqcount")
  156. delete(adData, "adeposedcount")
  157. delete(adData, "reporturl")
  158. //更新到MongoDB 中
  159. update := bson.M{
  160. "$set": struct {
  161. AdData map[string]interface{} `bson:"adData" json:"adData"`
  162. }{
  163. AdData: adData,
  164. },
  165. }
  166. _, err = collection.UpdateOne(context.Background(), filter, update)
  167. if err != nil {
  168. response.Fail(c, 1003, "写入数据失败"+err.Error())
  169. return
  170. }
  171. }
  172. }
  173. defer cur.Close(context.Background())
  174. //更新成正确的数据
  175. response.Success(c, gin.H{
  176. "data": result,
  177. })
  178. }
  179. func FindUserBehavior(id string) *model.UserBehavior {
  180. filter := bson.M{"_id": id}
  181. var result model.UserBehavior
  182. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  183. err := collection.FindOne(context.Background(), filter).Decode(&result)
  184. if err != nil {
  185. return nil
  186. }
  187. return &result
  188. }
  189. // 新建UserBehavior
  190. func CreateUserBehavior(gid string, pf string, openId string, now time.Time) error {
  191. id := gid + "|" + pf + "|" + openId
  192. Behavior := FindUserBehavior(id)
  193. if Behavior != nil {
  194. //更新start_num参数
  195. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  196. filter := bson.M{"_id": id}
  197. update := bson.M{"$inc": bson.M{"startNum": 1}}
  198. _, err := collection.UpdateOne(context.Background(), filter, update)
  199. if err != nil {
  200. return err
  201. }
  202. //更新关联的广告数据
  203. filter = bson.M{"userId": id}
  204. collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  205. update = bson.M{"$inc": bson.M{"startNum": 1}}
  206. _, err = collection.UpdateMany(context.Background(), filter, update)
  207. if err != nil {
  208. return err
  209. }
  210. return nil
  211. } else {
  212. behavior := model.UserBehavior{
  213. Id: id,
  214. Gid: gid,
  215. Pf: pf,
  216. OpenId: openId,
  217. TotalDuration: 0,
  218. TotalAdReqCount: 0,
  219. TotalAdEposedCount: 0,
  220. RelatedAid: 0,
  221. StartNum: 1,
  222. CreateTime: int(now.Unix()),
  223. CreateDate: now.Format("20060102"),
  224. ActiveStatus: false,
  225. ConversionStatus: false,
  226. RemainData: nil,
  227. }
  228. //新增
  229. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  230. _, err := collection.InsertOne(context.Background(), behavior)
  231. if err != nil {
  232. return err
  233. }
  234. }
  235. //存储在线数据到redis中
  236. global.App.Redis.Set(context.Background(), id+"|online", now.Unix(), time.Second*300)
  237. return nil
  238. }
  239. // 更新UserBehavior 在线时间
  240. func UpdateUserBehaviorDuration(gid string, pf string, openId string, now time.Time, types int) error {
  241. id := gid + "|" + pf + "|" + openId
  242. fmt.Println(now.Format("2006-01-02 15:04:05"))
  243. Behavior := FindUserBehavior(id)
  244. if Behavior == nil {
  245. return errors.New("该用户数据未保存,无法计算在线时间")
  246. }
  247. lastTime, _ := global.App.Redis.Get(context.Background(), id+"|online").Result()
  248. //当状态为在线时,刷新redis数据,状态为2是离线,不刷新
  249. if types == 1 {
  250. global.App.Redis.Set(context.Background(), id+"|online", now.Unix(), time.Second*300)
  251. } else {
  252. global.App.Redis.Del(context.Background(), id+"|online")
  253. }
  254. //fmt.Println("types", types)
  255. //如果redis中没有查到在线状态,那就视为刚刚登录,不增加时间
  256. if lastTime == "" {
  257. return nil
  258. }
  259. //计算时间差
  260. lastTimeUnix, _ := strconv.ParseInt(lastTime, 10, 64)
  261. duration := now.Unix() - lastTimeUnix
  262. //更新到MongoDB 中
  263. update := bson.M{
  264. "$set": struct {
  265. TotalDuration int `bson:"totalDuration" json:"totalDuration"`
  266. }{
  267. TotalDuration: Behavior.TotalDuration + int(duration),
  268. },
  269. }
  270. filter := bson.M{"_id": id}
  271. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  272. _, err := collection.UpdateOne(context.Background(), filter, update)
  273. if err != nil {
  274. return err
  275. }
  276. //更新到当日数据中 todo
  277. //更新到广告关联数据中
  278. filter = bson.M{"userId": id}
  279. collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  280. update = bson.M{"$inc": bson.M{"duration": int(duration)}}
  281. _, err = collection.UpdateMany(context.Background(), filter, update)
  282. if err != nil {
  283. return err
  284. }
  285. return nil
  286. }
  287. // 更新UserBehavior 看广告的数据
  288. func UpdateUserBehaviorAdInfo(gid string, pf string, openId string, adsState int) error {
  289. id := gid + "|" + pf + "|" + openId
  290. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  291. filter := bson.M{"_id": id}
  292. Behavior := FindUserBehavior(id)
  293. if Behavior == nil {
  294. return errors.New("该用户数据未保存,无法累加看广告数据")
  295. }
  296. var AdReqCount int
  297. var AdEposedcount int
  298. if adsState == 0 {
  299. //展示不成功
  300. } else if adsState == 1 {
  301. //展示成功
  302. AdReqCount = 1
  303. } else if adsState == 2 {
  304. //展示成功并且看完
  305. AdReqCount = 1
  306. AdEposedcount = 1
  307. }
  308. //更新到总数据中
  309. update := bson.M{
  310. "$set": struct {
  311. TotalAdReqCount int `bson:"totalAdReqCount" json:"totalAdReqCount"`
  312. TotalAdEposedCount int `bson:"totalAdEposedCount" json:"totalAdEposedCount"`
  313. }{
  314. TotalAdReqCount: Behavior.TotalAdReqCount + AdReqCount,
  315. TotalAdEposedCount: Behavior.TotalAdEposedCount + AdEposedcount,
  316. },
  317. }
  318. _, err := collection.UpdateOne(context.Background(), filter, update)
  319. if err != nil {
  320. return err
  321. }
  322. //更新到当日数据中 todo
  323. //更新到广告关联数据中
  324. filter = bson.M{"userId": id}
  325. collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  326. update = bson.M{"$inc": bson.M{"req_count": AdReqCount, "exp_count": AdEposedcount}}
  327. _, err = collection.UpdateMany(context.Background(), filter, update)
  328. if err != nil {
  329. return err
  330. }
  331. return nil
  332. }
  333. // 上报给巨量对接系统
  334. func CheckUserActive(gid string, pf string, openId string) {
  335. request := map[string]interface{}{
  336. "gid": gid,
  337. "platform": pf,
  338. "openId": openId,
  339. }
  340. data, err := service.CurlPost(config.Get("app.check_user_active"), request, nil)
  341. if err != nil {
  342. global.App.Log.Error("CheckUserActive err: ", err)
  343. return
  344. }
  345. res := make(map[string]interface{})
  346. err = json.Unmarshal([]byte(data), &res)
  347. if err != nil {
  348. global.App.Log.Error("解析返回json错误: ", err)
  349. }
  350. fmt.Println(res)
  351. }