getNewActiveUser.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package public
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/util/gconv"
  6. "sync"
  7. "time"
  8. )
  9. type NewActiveMsg struct {
  10. MgoUserID string
  11. TimeStamp int64 //活跃时间
  12. }
  13. func GetNewActiveUser(st, ed time.Time) []*NewActiveMsg {
  14. var mgoIds []string
  15. stYear, stMonth, stDay := st.Date()
  16. edYear, edMonth, edDay := ed.Date()
  17. nst := st.AddDate(0, -1, 0)
  18. _, nstMonth, nstDay := nst.Date()
  19. var sql, nSql string
  20. if stYear == edYear && stMonth == edMonth && stDay == edDay {
  21. sql = fmt.Sprintf("month = %d and day = %d", int(stMonth), stDay)
  22. } else if stMonth == edMonth {
  23. sql = fmt.Sprintf("month = %d and day >= %d and day <= %d", int(stMonth), stDay, edDay)
  24. } else {
  25. sql = fmt.Sprintf("(month = %d and day >= %d) or (month = %d and day <= %d)", int(stMonth), stDay, int(edMonth), edDay)
  26. }
  27. //昨天所有活跃用户
  28. res, err := g.DB().Query(ctx, fmt.Sprintf(`SELECT DISTINCT user_mongoid FROM user_countbyhour WHERE %s `, sql))
  29. if err == nil && !res.IsEmpty() {
  30. for _, m := range res.List() {
  31. mongoid := gconv.String(m["user_mongoid"])
  32. mgoIds = append(mgoIds, mongoid)
  33. }
  34. }
  35. var (
  36. lock sync.Mutex
  37. data []*NewActiveMsg
  38. )
  39. if nstMonth == stMonth {
  40. nSql = fmt.Sprintf("month = %d and day >= %d and day < %d", int(stMonth), nstDay, stDay)
  41. } else {
  42. nSql = fmt.Sprintf("((month = %d and day >= %d) or (month = %d and day < %d))", int(nstMonth), nstDay, int(stMonth), stDay)
  43. }
  44. pool := make(chan bool, 5)
  45. wait := &sync.WaitGroup{}
  46. for _, id := range mgoIds {
  47. pool <- true
  48. wait.Add(1)
  49. go func(mId string) {
  50. defer func() {
  51. wait.Done()
  52. <-pool
  53. }()
  54. count, _ := g.DB().GetCount(ctx, fmt.Sprintf("user_mongoid = '%s' and %s", mId, nSql))
  55. if count == 0 { //统计昨天之前30天不活跃用户
  56. lock.Lock()
  57. data = append(data, &NewActiveMsg{
  58. MgoUserID: mId,
  59. TimeStamp: time.Date(stYear, stMonth, stDay, 0, 0, 0, 0, time.Local).Unix(),
  60. })
  61. lock.Unlock()
  62. }
  63. }(id)
  64. }
  65. wait.Wait()
  66. return data
  67. }