synthesis.go 13 KB

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