synthesis.go 13 KB

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