synthesis.go 11 KB

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