synthesis.go 11 KB

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