synthesis.go 10 KB

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