synthesis.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. package service
  2. import (
  3. "context"
  4. "math"
  5. "time"
  6. "github.com/mhaya/game/game_cluster/internal/mdb"
  7. "github.com/mhaya/game/game_cluster/internal/mdb/models"
  8. "github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
  9. "github.com/spf13/cast"
  10. "go.mongodb.org/mongo-driver/bson"
  11. "go.mongodb.org/mongo-driver/mongo"
  12. "go.mongodb.org/mongo-driver/mongo/options"
  13. )
  14. type Synthesis struct {
  15. db *mongo.Database
  16. }
  17. func NewSynthesis() *Synthesis {
  18. return &Synthesis{
  19. db: mdb.MDB,
  20. }
  21. }
  22. func (s *Synthesis) FindMDBUserLogDaily(req *entity.UserLogDailyReq) ([]entity.UserLogDailyResp, error) {
  23. // 定义上下文
  24. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  25. defer cancel()
  26. // 指定集合
  27. collection := mdb.MDB.Collection("playerDailyRecord")
  28. // 构建查询条件 - 如果查询值为空那就不添加查询条件
  29. filter := bson.M{}
  30. if req.StartTime != 0 {
  31. filter["timestamp"] = bson.M{
  32. "$gte": req.StartTime,
  33. "$lte": req.EndTime,
  34. }
  35. }
  36. if req.Platform != "" && req.Platform != "all" {
  37. filter["platform"] = req.Platform
  38. }
  39. if req.Channel != "" {
  40. filter["channel"] = req.Channel
  41. }
  42. // 分页参数
  43. skip := (req.Page - 1) * req.Size
  44. // 执行查询
  45. opts := options.Find()
  46. opts.SetSkip(int64(skip))
  47. opts.SetLimit(int64(req.Size))
  48. cursor, err := collection.Find(ctx, filter, opts)
  49. if err != nil {
  50. return nil, err
  51. }
  52. defer cursor.Close(ctx)
  53. // 解析查询结果
  54. var results []entity.UserLogDailyResp
  55. for cursor.Next(ctx) {
  56. var result entity.UserLogDailyResp
  57. err := cursor.Decode(&result)
  58. if err != nil {
  59. return nil, err
  60. }
  61. results = append(results, result)
  62. }
  63. // 同一天的数据全部放到platform= ALl 且数据累加
  64. // 如果没有platform=all 的那就新增一个 同一个时间段只能有一个 platform=all
  65. // 将同一天的数据累加到platform=all的记录中
  66. allPlatformRecordMap := make(map[int64]*entity.UserLogDailyResp)
  67. for _, result := range results {
  68. allPlatformRecordMap[result.Timestamp] = &entity.UserLogDailyResp{
  69. Timestamp: result.Timestamp,
  70. Platform: "all",
  71. }
  72. }
  73. for _, v := range results {
  74. if v.Timestamp == allPlatformRecordMap[v.Timestamp].Timestamp {
  75. allPlatformRecordMap[v.Timestamp].Registered += v.Registered
  76. allPlatformRecordMap[v.Timestamp].LoggedIn += v.LoggedIn
  77. allPlatformRecordMap[v.Timestamp].NewActive += v.NewActive
  78. allPlatformRecordMap[v.Timestamp].OldActive += v.OldActive
  79. allPlatformRecordMap[v.Timestamp].TotalPoints += v.TotalPoints
  80. allPlatformRecordMap[v.Timestamp].UProduced += v.UProduced
  81. allPlatformRecordMap[v.Timestamp].UCashout += v.UCashout
  82. allPlatformRecordMap[v.Timestamp].NewLogin += v.NewLogin
  83. allPlatformRecordMap[v.Timestamp].OldLogin += v.OldLogin
  84. }
  85. }
  86. // 替换原有结果
  87. for _, record := range allPlatformRecordMap {
  88. results = append(results, *record)
  89. }
  90. return results, nil
  91. }
  92. // FindWithdrawal 根据请求查询提现记录
  93. func (s *Synthesis) FindWithdrawal(req *entity.UserWithdrawalReq) ([]*entity.UserWithdrawalResp, error) {
  94. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  95. defer cancel()
  96. collection := mdb.MDB.Collection("CashOutRecord")
  97. // 构建过滤器
  98. filter := bson.M{}
  99. if req.UserName != "" {
  100. filter["userName"] = req.UserName
  101. }
  102. if req.NickName != "" {
  103. filter["nickName"] = req.NickName
  104. }
  105. if req.StartTime > 0 && req.EndTime > 0 {
  106. filter["createdAt"] = bson.M{"$gte": time.Unix(req.StartTime, 0), "$lte": time.Unix(req.EndTime, 0)}
  107. } else if req.StartTime > 0 {
  108. filter["createdAt"] = bson.M{"$gte": time.Unix(req.StartTime, 0)}
  109. } else if req.EndTime > 0 {
  110. filter["createdAt"] = bson.M{"$lte": time.Unix(req.EndTime, 0)}
  111. }
  112. // 设置分页选项
  113. findOptions := options.Find()
  114. findOptions.SetSkip(int64((req.Page - 1) * req.Size))
  115. findOptions.SetLimit(int64(req.Size))
  116. // 查询数据
  117. var results []*entity.UserWithdrawalResp
  118. cursor, err := collection.Find(ctx, filter, findOptions)
  119. if err != nil {
  120. return nil, err
  121. }
  122. defer cursor.Close(ctx)
  123. // 解析结果
  124. for cursor.Next(ctx) {
  125. var result entity.UserWithdrawalResp
  126. if err := cursor.Decode(&result); err != nil {
  127. return nil, err
  128. }
  129. results = append(results, &result)
  130. }
  131. if err := cursor.Err(); err != nil {
  132. return nil, err
  133. }
  134. return results, nil
  135. }
  136. // WithdrawalStatus 更新提现状态
  137. func (s *Synthesis) WithdrawalStatus(req *entity.UserWithdrawalStatus) error {
  138. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  139. defer cancel()
  140. collection := mdb.MDB.Collection("CashOutRecord")
  141. _, err := collection.UpdateOne(ctx, bson.M{"userName": req.UserName}, bson.M{"$set": bson.M{"status": req.Status}})
  142. if err != nil {
  143. return err
  144. }
  145. return nil
  146. }
  147. // FindUserCountryCount 查询用户国家分布
  148. //
  149. // 返回值为 UserCountryResp 的切片和错误。
  150. func (s *Synthesis) FindUserCountryCount() ([]*entity.UserCountryResp, error) {
  151. // 选择数据库和集合
  152. collection := mdb.MDB.Collection("playerCountryStat")
  153. // 定义聚合管道
  154. // 定义聚合管道
  155. pipeline := []bson.D{
  156. {
  157. {Key: "$project", Value: bson.D{
  158. {Key: "playerRegisterCountry", Value: bson.D{{Key: "$objectToArray", Value: "$playerRegisterCountry"}}},
  159. }},
  160. },
  161. {
  162. {Key: "$unwind", Value: "$playerRegisterCountry"},
  163. },
  164. {
  165. {Key: "$group", Value: bson.D{
  166. {Key: "_id", Value: "$playerRegisterCountry.k"},
  167. {Key: "totalValue", Value: bson.D{{Key: "$sum", Value: "$playerRegisterCountry.v"}}},
  168. }},
  169. },
  170. {
  171. {Key: "$project", Value: bson.D{
  172. {Key: "_id", Value: 0},
  173. {Key: "countryKey", Value: "$_id"},
  174. {Key: "totalValue", Value: 1},
  175. }},
  176. },
  177. }
  178. // 执行聚合查询
  179. cursor, err := collection.Aggregate(context.TODO(), pipeline)
  180. if err != nil {
  181. panic(err)
  182. }
  183. defer cursor.Close(context.TODO())
  184. // 遍历查询结果
  185. var results []bson.M
  186. if err := cursor.All(context.TODO(), &results); err != nil {
  187. panic(err)
  188. }
  189. var totalIPCount int64
  190. var data []*entity.UserCountryResp
  191. // 将结果转换为 UserCountryResp
  192. for _, r := range results {
  193. var resp entity.UserCountryResp
  194. resp.Country = r["countryKey"].(string)
  195. resp.IPCount = int(r["totalValue"].(int32))
  196. totalIPCount += int64(resp.IPCount)
  197. data = append(data, &resp)
  198. }
  199. for _, v := range data {
  200. // 保留小数点后两位
  201. v.Percentage = math.Round(float64(v.IPCount)/float64(totalIPCount)*10000) / 100
  202. }
  203. // 根据阈值过滤结果
  204. otherCount := 0
  205. otherPercentage := 0.00
  206. filteredResults := make([]*entity.UserCountryResp, 0)
  207. threshold := 1.00
  208. for _, r := range data {
  209. if r.Percentage >= threshold {
  210. filteredResults = append(filteredResults, r)
  211. // 保留小数点后两位
  212. r.Percentage = math.Round(r.Percentage*100) / 100
  213. otherPercentage += r.Percentage
  214. } else {
  215. otherCount += r.IPCount
  216. }
  217. }
  218. // 将其他国家添加到过滤后的结果中
  219. if otherCount > 0 {
  220. p := 100.00 - math.Round(otherPercentage*100)/100
  221. filteredResults = append(filteredResults, &entity.UserCountryResp{
  222. Country: "other",
  223. IPCount: otherCount,
  224. Percentage: math.Round(p*100) / 100,
  225. })
  226. }
  227. return filteredResults, nil
  228. }
  229. // FindUserRetention UserRetentionResp 用户留存率
  230. // 1. 获取指定日期范围内的注册用户数量
  231. // 2. 获取指定日期范围内的活跃用户数量
  232. // 3. 计算留存率
  233. // 4. 返回结果
  234. func (s *Synthesis) FindUserRetention(req *entity.UserRetentionReq) ([]*entity.UserRetentionResp, error) {
  235. playerPreserve := models.GetPlayerPreserve(req.StartTime, req.EndTime)
  236. // 查询数据
  237. var results []*entity.UserRetentionResp
  238. for key, v := range playerPreserve {
  239. var resp entity.UserRetentionResp
  240. var retention entity.Retention
  241. for _, vv := range v {
  242. if vv.ID == 1 {
  243. retention.Day1 = entity.DayRetention{
  244. LoggedIn: vv.Ratio,
  245. LoginDate: key,
  246. }
  247. }
  248. if vv.ID == 3 {
  249. retention.Day3 = entity.DayRetention{
  250. LoggedIn: vv.Ratio,
  251. LoginDate: key,
  252. }
  253. }
  254. if vv.ID == 7 {
  255. retention.Day7 = entity.DayRetention{
  256. LoggedIn: vv.Ratio,
  257. LoginDate: key,
  258. }
  259. }
  260. if vv.ID == 14 {
  261. retention.Day14 = entity.DayRetention{
  262. LoggedIn: vv.Ratio,
  263. LoginDate: key,
  264. }
  265. }
  266. if vv.ID == 30 {
  267. retention.Day30 = entity.DayRetention{
  268. LoggedIn: vv.Ratio,
  269. LoginDate: key,
  270. }
  271. }
  272. }
  273. resp.RegistrationDate = key
  274. resp.RetentionData = retention
  275. results = append(results, &resp)
  276. }
  277. return results, nil
  278. }
  279. // FindUserLevel 用户等级统计
  280. func (s *Synthesis) FindUserLevel() ([]*entity.UserLevelCountResp, error) {
  281. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  282. defer cancel()
  283. collection := mdb.MDB.Collection("playerLevelStat")
  284. // 查询所有文档
  285. cursor, err := collection.Find(ctx, bson.M{})
  286. if err != nil {
  287. return nil, err
  288. }
  289. defer cursor.Close(ctx)
  290. var results []*entity.UserLevelCountResp
  291. var reData []*models.PlayerLevelStat
  292. for cursor.Next(ctx) {
  293. var result models.PlayerLevelStat
  294. if err := cursor.Decode(&result); err != nil {
  295. return nil, err
  296. }
  297. reData = append(reData, &result)
  298. }
  299. if err := cursor.Err(); err != nil {
  300. return nil, err
  301. }
  302. dataMap := make(map[string]int)
  303. for _, v := range reData {
  304. for key, v1 := range v.ServerLevel {
  305. dataMap[key] += v1
  306. }
  307. }
  308. for k, v := range dataMap {
  309. results = append(results, &entity.UserLevelCountResp{
  310. Level: cast.ToInt(k),
  311. UserCount: v,
  312. })
  313. }
  314. return results, nil
  315. }