synthesis.go 12 KB

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