synthesis.go 9.4 KB

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