synthesis.go 9.3 KB

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