synthesis.go 11 KB

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