synthesis.go 11 KB

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