synthesis.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. package service
  2. import (
  3. "context"
  4. "math"
  5. "time"
  6. mhayaTime "github.com/mhaya/extend/time"
  7. "github.com/mhaya/game/game_cluster/internal/code"
  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/adminapi/common"
  12. "github.com/mhaya/game/game_cluster/nodes/adminapi/entity"
  13. "github.com/mhaya/game/game_cluster/nodes/adminapi/model"
  14. mhayaLogger "github.com/mhaya/logger"
  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, *code.Result) {
  30. // 定义上下文
  31. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  32. defer cancel()
  33. // 指定集合
  34. collection := mdb.MDB.Collection(constant.CNamePlayerDailyRecord)
  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. // 计算总数
  52. count, err := collection.CountDocuments(ctx, filter)
  53. if err != nil {
  54. mhayaLogger.Warnf("FindMDBUserLogDaily CountDocuments error:%v", err)
  55. return nil, common.NewResult(code.InternalError)
  56. }
  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. mhayaLogger.Warnf("FindMDBUserLogDaily Find error:%v", err)
  65. return nil, common.NewResult(code.InternalError)
  66. }
  67. defer cursor.Close(ctx)
  68. // 解析查询结果
  69. var results []*entity.UserLogDailyDetail
  70. for cursor.Next(ctx) {
  71. var result *entity.UserLogDailyDetail
  72. err := cursor.Decode(&result)
  73. if err != nil {
  74. mhayaLogger.Warnf("FindMDBUserLogDaily Decode error:%v", err)
  75. return nil, common.NewResult(code.InternalError)
  76. }
  77. results = append(results, result)
  78. }
  79. // 同一天的数据全部放到platform= ALl 且数据累加
  80. // 如果没有platform=all 的那就新增一个 同一个时间段只能有一个 platform=all
  81. // 将同一天的数据累加到platform=all的记录中
  82. allPlatformRecordMap := make(map[int64]*entity.UserLogDailyDetail)
  83. for _, result := range results {
  84. allPlatformRecordMap[result.Timestamp] = &entity.UserLogDailyDetail{
  85. Timestamp: result.Timestamp,
  86. Platform: "all",
  87. }
  88. }
  89. for _, v := range results {
  90. if v.Timestamp == allPlatformRecordMap[v.Timestamp].Timestamp {
  91. allPlatformRecordMap[v.Timestamp].Registered += v.Registered
  92. allPlatformRecordMap[v.Timestamp].LoggedIn += v.LoggedIn
  93. allPlatformRecordMap[v.Timestamp].NewActive += v.NewActive
  94. allPlatformRecordMap[v.Timestamp].OldActive += v.OldActive
  95. allPlatformRecordMap[v.Timestamp].TotalPoints += v.TotalPoints
  96. allPlatformRecordMap[v.Timestamp].UProduced += v.UProduced
  97. allPlatformRecordMap[v.Timestamp].UCashout += v.UCashout
  98. allPlatformRecordMap[v.Timestamp].NewLogin += v.NewLogin
  99. allPlatformRecordMap[v.Timestamp].OldLogin += v.OldLogin
  100. }
  101. }
  102. // 替换原有结果
  103. for _, record := range allPlatformRecordMap {
  104. results = append(results, record)
  105. }
  106. return &entity.UserLogDailyResp{
  107. Details: results,
  108. Total: count,
  109. }, nil
  110. }
  111. // FindWithdrawal 根据请求查询提现记录
  112. func (s *Synthesis) FindWithdrawal(req entity.UserWithdrawalReq) (*entity.UserWithdrawalResp, *code.Result) {
  113. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  114. defer cancel()
  115. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  116. // 构建过滤器
  117. filter := bson.M{}
  118. if req.UserName != "" {
  119. filter["userName"] = req.UserName
  120. }
  121. if req.NickName != "" {
  122. filter["nickName"] = req.NickName
  123. }
  124. if req.ID != "" {
  125. filter["_id"], _ = primitive.ObjectIDFromHex(req.ID)
  126. }
  127. if req.StartTime != 0 {
  128. filter["createAt"] = bson.M{
  129. "$gte": req.StartTime,
  130. "$lte": req.EndTime,
  131. }
  132. }
  133. // 设置分页选项
  134. findOptions := options.Find()
  135. findOptions.SetSkip(int64((req.Page - 1) * req.Size))
  136. findOptions.SetLimit(int64(req.Size))
  137. findOptions.SetSort(bson.D{{"createAt", -1}})
  138. // 获取总数total
  139. count, err := collection.CountDocuments(ctx, filter)
  140. if err != nil {
  141. mhayaLogger.Warnf("FindWithdrawal CountDocuments error:%v", err)
  142. return nil, common.NewResult(code.InternalError)
  143. }
  144. // 查询数据
  145. var results []*entity.UserWithdrawalDetail
  146. cursor, err := collection.Find(ctx, filter, findOptions)
  147. if err != nil {
  148. mhayaLogger.Warnf("FindWithdrawal Find error:%v", err)
  149. return nil, common.NewResult(code.InternalError)
  150. }
  151. defer cursor.Close(ctx)
  152. // 解析结果
  153. for cursor.Next(ctx) {
  154. var result entity.UserWithdrawalDetail
  155. if err := cursor.Decode(&result); err != nil {
  156. mhayaLogger.Warnf("FindWithdrawal Decode error:%v", err)
  157. return nil, common.NewResult(code.InternalError)
  158. }
  159. results = append(results, &result)
  160. }
  161. if err := cursor.Err(); err != nil {
  162. mhayaLogger.Warnf("FindWithdrawal cursor error:%v", err)
  163. return nil, common.NewResult(code.InternalError)
  164. }
  165. return &entity.UserWithdrawalResp{
  166. Details: results,
  167. Total: count,
  168. }, nil
  169. }
  170. // WithdrawalStatus 更新提现状态
  171. func (s *Synthesis) WithdrawalStatus(req entity.UserWithdrawalStatus) *code.Result {
  172. // ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  173. // defer cancel()
  174. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  175. // 更新条件
  176. updateCondition := bson.M{"userName": req.UserName}
  177. // 更新内容
  178. updateContent := bson.M{"$set": bson.M{"status": req.Status}}
  179. // 设置更新选项
  180. updateOptions := options.Update() // 设置 upsert 选项
  181. // 执行更新操作
  182. _, err := collection.UpdateOne(context.TODO(), updateCondition, updateContent, updateOptions)
  183. if err != nil {
  184. mhayaLogger.Warnf("WithdrawalStatus UpdateOne error:%v", err)
  185. return common.NewResult(code.InternalError)
  186. }
  187. return nil
  188. }
  189. // WithdrawalStatusBatch 更新提现状态
  190. func (s *Synthesis) WithdrawalStatusBatch(req entity.UserWithdrawalStatusBatch) *code.Result {
  191. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  192. if len(req.ID) == 0 {
  193. return common.NewResult(code.ParamError)
  194. }
  195. for _, id := range req.ID {
  196. objID := primitive.ObjectID{}
  197. objID, _ = primitive.ObjectIDFromHex(id)
  198. updateCondition := bson.M{"_id": objID}
  199. updateContent := bson.M{}
  200. withdrawal := models.CashOutRecord{}
  201. err := collection.FindOne(context.TODO(), updateCondition).Decode(&withdrawal)
  202. if err != nil {
  203. mhayaLogger.Warnf("WithdrawalStatusBatch FindOne error:%v", err)
  204. continue
  205. }
  206. if req.Withdrawal != 0 {
  207. if withdrawal.Status == 1 {
  208. updateContent = bson.M{"$set": bson.M{"withdrawal": req.Withdrawal}}
  209. } else {
  210. continue
  211. }
  212. }
  213. if req.Status > 0 {
  214. if withdrawal.Status != 0 {
  215. continue
  216. }
  217. updateContent = bson.M{"$set": bson.M{"status": req.Status}}
  218. }
  219. updateOptions := options.Update().SetUpsert(true)
  220. _, err = collection.UpdateOne(context.TODO(), updateCondition, updateContent, updateOptions)
  221. if err != nil {
  222. mhayaLogger.Warnf("WithdrawalStatusBatch UpdateOne error:%v", err)
  223. continue
  224. }
  225. }
  226. return nil
  227. }
  228. // FindUserCountryCount 查询用户国家分布
  229. //
  230. // 返回值为 UserCountryResp 的切片和错误。
  231. func (s *Synthesis) FindUserCountryCount() (*entity.UserCountryResp, *code.Result) {
  232. // 选择数据库和集合
  233. collection := mdb.MDB.Collection(constant.CNamePlayerCountryByIPStat)
  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. mhayaLogger.Warnf("FindUserCountryCount Aggregate error:%v", err)
  263. return nil, common.NewResult(code.InternalError)
  264. }
  265. defer cursor.Close(context.TODO())
  266. // 遍历查询结果
  267. var results []bson.M
  268. if err := cursor.All(context.TODO(), &results); err != nil {
  269. mhayaLogger.Warnf("FindUserCountryCount All error:%v", err)
  270. return nil, common.NewResult(code.InternalError)
  271. }
  272. var totalIPCount int64
  273. var data []*entity.UserCountryDetail
  274. // 将结果转换为 UserCountryDetail
  275. for _, r := range results {
  276. var resp entity.UserCountryDetail
  277. resp.Country = r["countryKey"].(string)
  278. resp.IPCount = int(r["totalValue"].(int32))
  279. totalIPCount += int64(resp.IPCount)
  280. data = append(data, &resp)
  281. }
  282. for _, v := range data {
  283. // 保留小数点后两位
  284. v.Percentage = math.Round(float64(v.IPCount)/float64(totalIPCount)*10000) / 100
  285. }
  286. // 根据阈值过滤结果
  287. otherCount := 0
  288. otherPercentage := 0.00
  289. filteredResults := make([]*entity.UserCountryDetail, 0)
  290. threshold := 1.00
  291. for _, r := range data {
  292. if r.Percentage >= threshold {
  293. filteredResults = append(filteredResults, r)
  294. // 保留小数点后两位
  295. r.Percentage = math.Round(r.Percentage*100) / 100
  296. otherPercentage += r.Percentage
  297. } else {
  298. otherCount += r.IPCount
  299. }
  300. }
  301. // 将其他国家添加到过滤后的结果中
  302. if otherCount > 0 {
  303. p := 100.00 - math.Round(otherPercentage*100)/100
  304. filteredResults = append(filteredResults, &entity.UserCountryDetail{
  305. Country: "other",
  306. IPCount: otherCount,
  307. Percentage: math.Round(p*100) / 100,
  308. })
  309. }
  310. return &entity.UserCountryResp{
  311. Details: filteredResults,
  312. }, nil
  313. }
  314. // FindUserRetention UserRetentionResp 用户留存率
  315. // 1. 获取指定日期范围内的注册用户数量
  316. // 2. 获取指定日期范围内的活跃用户数量
  317. // 3. 计算留存率
  318. // 4. 返回结果
  319. func (s *Synthesis) FindUserRetention(req entity.UserRetentionReq) (*entity.UserRetentionResp, *code.Result) {
  320. playerPreserve := models.GetPlayerPreserve(req.StartTime, req.EndTime)
  321. // 查询数据
  322. var results []*entity.UserRetentionDetail
  323. for key, v := range playerPreserve {
  324. var retention entity.Retention
  325. for _, vv := range v {
  326. if vv.ID == 1 {
  327. retention.Day1 = entity.DayRetention{
  328. LoggedIn: vv.Ratio,
  329. LoginDate: key,
  330. }
  331. }
  332. if vv.ID == 3 {
  333. retention.Day3 = entity.DayRetention{
  334. LoggedIn: vv.Ratio,
  335. LoginDate: key,
  336. }
  337. }
  338. if vv.ID == 7 {
  339. retention.Day7 = entity.DayRetention{
  340. LoggedIn: vv.Ratio,
  341. LoginDate: key,
  342. }
  343. }
  344. if vv.ID == 14 {
  345. retention.Day14 = entity.DayRetention{
  346. LoggedIn: vv.Ratio,
  347. LoginDate: key,
  348. }
  349. }
  350. if vv.ID == 30 {
  351. retention.Day30 = entity.DayRetention{
  352. LoggedIn: vv.Ratio,
  353. LoginDate: key,
  354. }
  355. }
  356. }
  357. results = append(results, &entity.UserRetentionDetail{
  358. RegistrationDate: key,
  359. RetentionData: retention,
  360. })
  361. }
  362. return &entity.UserRetentionResp{
  363. Details: results,
  364. }, nil
  365. }
  366. // FindUserLevel 用户等级统计
  367. func (s *Synthesis) FindUserLevel() (*entity.UserLevelCountResp, *code.Result) {
  368. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  369. defer cancel()
  370. collection := mdb.MDB.Collection(constant.CNamePlayerLevelStat)
  371. // 查询所有文档
  372. cursor, err := collection.Find(ctx, bson.M{})
  373. if err != nil {
  374. mhayaLogger.Warnf("FindUserLevel Find error:%v", err)
  375. return nil, common.NewResult(code.InternalError)
  376. }
  377. defer cursor.Close(ctx)
  378. var results []*entity.UserLevelCountDetail
  379. var reData []*models.PlayerLevelStat
  380. for cursor.Next(ctx) {
  381. var result models.PlayerLevelStat
  382. if err := cursor.Decode(&result); err != nil {
  383. mhayaLogger.Warnf("FindUserLevel Decode error:%v", err)
  384. return nil, common.NewResult(code.InternalError)
  385. }
  386. reData = append(reData, &result)
  387. }
  388. if err := cursor.Err(); err != nil {
  389. mhayaLogger.Warnf("FindUserLevel cursor error:%v", err)
  390. return nil, common.NewResult(code.InternalError)
  391. }
  392. dataMap := make(map[string]int)
  393. for _, v := range reData {
  394. for key, v1 := range v.ServerLevel {
  395. dataMap[key] += v1
  396. }
  397. }
  398. for k, v := range dataMap {
  399. results = append(results, &entity.UserLevelCountDetail{
  400. Level: cast.ToInt(k),
  401. UserCount: v,
  402. })
  403. }
  404. return &entity.UserLevelCountResp{
  405. Details: results,
  406. }, nil
  407. }
  408. func (s *Synthesis) InsertRecord(param model.UserOperationLog) {
  409. mhayaLogger.Warnf("InsertRecord param:%#v", param)
  410. record := new(model.UserOperationLog)
  411. collection := mdb.MDB.Collection(record.TableName())
  412. insertData := bson.M{}
  413. insertData["user_name"] = param.Username
  414. insertData["role_id"] = param.RoleId
  415. insertData["url"] = param.Path
  416. insertData["method"] = param.Method
  417. insertData["status_code"] = param.StatusCode
  418. insertData["dur"] = param.Dur
  419. insertData["client_ip"] = param.ClientIP
  420. insertData["error_message"] = param.ErrorMessage
  421. insertData["created_at"] = mhayaTime.Now().Unix()
  422. _, err := collection.InsertOne(context.Background(), insertData)
  423. if err != nil {
  424. mhayaLogger.Warnf("InsertRecord InsertOne error:%v", err)
  425. return
  426. }
  427. }
  428. func (s *Synthesis) RecordList(req entity.RecordListReq) (*entity.RecordListResp, *code.Result) {
  429. record := new(model.UserOperationLog)
  430. collection := mdb.MDB.Collection(record.TableName())
  431. // 构建过滤器
  432. filter := bson.M{}
  433. if req.UserName != "" {
  434. filter["userName"] = req.UserName
  435. }
  436. if req.RoleId != "" {
  437. filter["role_id"] = req.RoleId
  438. }
  439. if req.ID != "" {
  440. id, err := primitive.ObjectIDFromHex(req.ID)
  441. if err != nil {
  442. mhayaLogger.Warnf("RecordList ObjectIDFromHex error:%v, req.ID:%s", err, req.ID)
  443. return nil, common.NewResult(code.ParamError)
  444. }
  445. filter["id"] = id
  446. }
  447. if req.StartTime != 0 {
  448. filter["createAt"] = bson.M{
  449. "$gte": req.StartTime,
  450. "$lte": req.EndTime,
  451. }
  452. }
  453. // 设置分页选项
  454. findOptions := options.Find()
  455. findOptions.SetSkip(int64((req.Page - 1) * req.Size))
  456. findOptions.SetLimit(int64(req.Size))
  457. findOptions.SetSort(bson.D{{"created_at", -1}})
  458. // 获取总数total
  459. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  460. defer cancel()
  461. count, err := collection.CountDocuments(ctx, filter)
  462. if err != nil {
  463. mhayaLogger.Warnf("RecordList CountDocuments error:%v", err)
  464. return nil, common.NewResult(code.InternalError)
  465. }
  466. // 查询数据
  467. var results []*entity.RecordListDetail
  468. cursor, err := collection.Find(ctx, filter, findOptions)
  469. if err != nil {
  470. mhayaLogger.Warnf("RecordList Find error:%v", err)
  471. return nil, common.NewResult(code.InternalError)
  472. }
  473. defer cursor.Close(ctx)
  474. // 解析结果
  475. for cursor.Next(ctx) {
  476. var result entity.RecordListDetail
  477. if err := cursor.Decode(&result); err != nil {
  478. mhayaLogger.Warnf("RecordList Decode error:%v", err)
  479. return nil, common.NewResult(code.InternalError)
  480. }
  481. results = append(results, &result)
  482. }
  483. if err := cursor.Err(); err != nil {
  484. mhayaLogger.Warnf("RecordList cursor error:%v", err)
  485. return nil, common.NewResult(code.InternalError)
  486. }
  487. return &entity.RecordListResp{
  488. Details: results,
  489. Total: count,
  490. }, nil
  491. }