synthesis.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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/webadmin/common"
  12. "github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
  13. "github.com/mhaya/game/game_cluster/nodes/webadmin/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.Address != "" {
  128. filter["address"] = req.Address
  129. }
  130. if req.State > 0 {
  131. filter["state"] = req.State
  132. }
  133. if req.Withdrawal > 0 {
  134. filter["withdrawal"] = req.Withdrawal
  135. }
  136. if req.StartTime > 0 {
  137. filter["createAt"] = bson.M{
  138. "$gte": req.StartTime,
  139. "$lte": req.EndTime,
  140. }
  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. mhayaLogger.Warnf("FindWithdrawal CountDocuments error:%v", err)
  151. return nil, common.NewResult(code.InternalError)
  152. }
  153. // 查询数据
  154. var results []*entity.UserWithdrawalDetail
  155. cursor, err := collection.Find(ctx, filter, findOptions)
  156. if err != nil {
  157. mhayaLogger.Warnf("FindWithdrawal Find error:%v", err)
  158. return nil, common.NewResult(code.InternalError)
  159. }
  160. defer cursor.Close(ctx)
  161. // 解析结果
  162. for cursor.Next(ctx) {
  163. var result entity.UserWithdrawalDetail
  164. if err := cursor.Decode(&result); err != nil {
  165. mhayaLogger.Warnf("FindWithdrawal Decode error:%v", err)
  166. return nil, common.NewResult(code.InternalError)
  167. }
  168. results = append(results, &result)
  169. }
  170. if err := cursor.Err(); err != nil {
  171. mhayaLogger.Warnf("FindWithdrawal cursor error:%v", err)
  172. return nil, common.NewResult(code.InternalError)
  173. }
  174. return &entity.UserWithdrawalResp{
  175. Details: results,
  176. Total: count,
  177. }, nil
  178. }
  179. // WithdrawalStatus 更新提现状态
  180. func (s *Synthesis) WithdrawalStatus(req entity.UserWithdrawalStatus) *code.Result {
  181. // ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  182. // defer cancel()
  183. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  184. // 更新条件
  185. updateCondition := bson.M{"userName": req.UserName}
  186. // 更新内容
  187. updateContent := bson.M{"$set": bson.M{"status": req.Status}}
  188. // 设置更新选项
  189. updateOptions := options.Update() // 设置 upsert 选项
  190. // 执行更新操作
  191. _, err := collection.UpdateOne(context.TODO(), updateCondition, updateContent, updateOptions)
  192. if err != nil {
  193. mhayaLogger.Warnf("WithdrawalStatus UpdateOne error:%v", err)
  194. return common.NewResult(code.InternalError)
  195. }
  196. return nil
  197. }
  198. // WithdrawalStatusBatch 更新提现状态
  199. func (s *Synthesis) WithdrawalStatusBatch(req entity.UserWithdrawalStatusBatch) *code.Result {
  200. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  201. if len(req.ID) == 0 {
  202. return common.NewResult(code.ParamError)
  203. }
  204. for _, id := range req.ID {
  205. objID := primitive.ObjectID{}
  206. objID, _ = primitive.ObjectIDFromHex(id)
  207. updateCondition := bson.M{"_id": objID}
  208. updateContent := bson.M{}
  209. withdrawal := models.CashOutRecord{}
  210. err := collection.FindOne(context.TODO(), updateCondition).Decode(&withdrawal)
  211. if err != nil {
  212. mhayaLogger.Warnf("WithdrawalStatusBatch FindOne error:%v", err)
  213. continue
  214. }
  215. if req.Withdrawal != 0 {
  216. if withdrawal.Status == 1 {
  217. updateContent = bson.M{"$set": bson.M{"withdrawal": req.Withdrawal}}
  218. } else {
  219. continue
  220. }
  221. }
  222. if req.Status > 0 {
  223. if withdrawal.Status != 0 {
  224. continue
  225. }
  226. updateContent = bson.M{"$set": bson.M{"status": req.Status}}
  227. }
  228. updateOptions := options.Update().SetUpsert(true)
  229. _, err = collection.UpdateOne(context.TODO(), updateCondition, updateContent, updateOptions)
  230. if err != nil {
  231. mhayaLogger.Warnf("WithdrawalStatusBatch UpdateOne error:%v", err)
  232. continue
  233. }
  234. }
  235. return nil
  236. }
  237. // FindUserCountryCount 查询用户国家分布
  238. //
  239. // 返回值为 UserCountryResp 的切片和错误。
  240. func (s *Synthesis) FindUserCountryCount() (*entity.UserCountryResp, *code.Result) {
  241. // 选择数据库和集合
  242. collection := mdb.MDB.Collection(constant.CNamePlayerCountryByIPStat)
  243. // 定义聚合管道
  244. // 定义聚合管道
  245. pipeline := []bson.D{
  246. {
  247. {Key: "$project", Value: bson.D{
  248. {Key: "playerRegisterCountry", Value: bson.D{{Key: "$objectToArray", Value: "$playerRegisterCountry"}}},
  249. }},
  250. },
  251. {
  252. {Key: "$unwind", Value: "$playerRegisterCountry"},
  253. },
  254. {
  255. {Key: "$group", Value: bson.D{
  256. {Key: "_id", Value: "$playerRegisterCountry.k"},
  257. {Key: "totalValue", Value: bson.D{{Key: "$sum", Value: "$playerRegisterCountry.v"}}},
  258. }},
  259. },
  260. {
  261. {Key: "$project", Value: bson.D{
  262. {Key: "_id", Value: 0},
  263. {Key: "countryKey", Value: "$_id"},
  264. {Key: "totalValue", Value: 1},
  265. }},
  266. },
  267. }
  268. // 执行聚合查询
  269. cursor, err := collection.Aggregate(context.TODO(), pipeline)
  270. if err != nil {
  271. mhayaLogger.Warnf("FindUserCountryCount Aggregate error:%v", err)
  272. return nil, common.NewResult(code.InternalError)
  273. }
  274. defer cursor.Close(context.TODO())
  275. // 遍历查询结果
  276. var results []bson.M
  277. if err := cursor.All(context.TODO(), &results); err != nil {
  278. mhayaLogger.Warnf("FindUserCountryCount All error:%v", err)
  279. return nil, common.NewResult(code.InternalError)
  280. }
  281. var totalIPCount int64
  282. var data []*entity.UserCountryDetail
  283. // 将结果转换为 UserCountryDetail
  284. for _, r := range results {
  285. var resp entity.UserCountryDetail
  286. resp.Country = r["countryKey"].(string)
  287. resp.IPCount = int(r["totalValue"].(int32))
  288. totalIPCount += int64(resp.IPCount)
  289. data = append(data, &resp)
  290. }
  291. for _, v := range data {
  292. // 保留小数点后两位
  293. v.Percentage = math.Round(float64(v.IPCount)/float64(totalIPCount)*10000) / 100
  294. }
  295. // 根据阈值过滤结果
  296. otherCount := 0
  297. otherPercentage := 0.00
  298. filteredResults := make([]*entity.UserCountryDetail, 0)
  299. threshold := 1.00
  300. for _, r := range data {
  301. if r.Percentage >= threshold {
  302. filteredResults = append(filteredResults, r)
  303. // 保留小数点后两位
  304. r.Percentage = math.Round(r.Percentage*100) / 100
  305. otherPercentage += r.Percentage
  306. } else {
  307. otherCount += r.IPCount
  308. }
  309. }
  310. // 将其他国家添加到过滤后的结果中
  311. if otherCount > 0 {
  312. p := 100.00 - math.Round(otherPercentage*100)/100
  313. filteredResults = append(filteredResults, &entity.UserCountryDetail{
  314. Country: "other",
  315. IPCount: otherCount,
  316. Percentage: math.Round(p*100) / 100,
  317. })
  318. }
  319. return &entity.UserCountryResp{
  320. Details: filteredResults,
  321. }, nil
  322. }
  323. // FindUserRetention UserRetentionResp 用户留存率
  324. // 1. 获取指定日期范围内的注册用户数量
  325. // 2. 获取指定日期范围内的活跃用户数量
  326. // 3. 计算留存率
  327. // 4. 返回结果
  328. func (s *Synthesis) FindUserRetention(req entity.UserRetentionReq) (*entity.UserRetentionResp, *code.Result) {
  329. playerPreserve := models.GetPlayerPreserve(req.StartTime, req.EndTime)
  330. // 查询数据
  331. var results []*entity.UserRetentionDetail
  332. for key, v := range playerPreserve {
  333. var retention entity.Retention
  334. for _, vv := range v {
  335. if vv.ID == 1 {
  336. retention.Day1 = entity.DayRetention{
  337. LoggedIn: vv.Ratio,
  338. LoginDate: key,
  339. }
  340. }
  341. if vv.ID == 3 {
  342. retention.Day3 = entity.DayRetention{
  343. LoggedIn: vv.Ratio,
  344. LoginDate: key,
  345. }
  346. }
  347. if vv.ID == 7 {
  348. retention.Day7 = entity.DayRetention{
  349. LoggedIn: vv.Ratio,
  350. LoginDate: key,
  351. }
  352. }
  353. if vv.ID == 14 {
  354. retention.Day14 = entity.DayRetention{
  355. LoggedIn: vv.Ratio,
  356. LoginDate: key,
  357. }
  358. }
  359. if vv.ID == 30 {
  360. retention.Day30 = entity.DayRetention{
  361. LoggedIn: vv.Ratio,
  362. LoginDate: key,
  363. }
  364. }
  365. }
  366. results = append(results, &entity.UserRetentionDetail{
  367. RegistrationDate: key,
  368. RetentionData: retention,
  369. })
  370. }
  371. return &entity.UserRetentionResp{
  372. Details: results,
  373. }, nil
  374. }
  375. // FindUserLevel 用户等级统计
  376. func (s *Synthesis) FindUserLevel() (*entity.UserLevelCountResp, *code.Result) {
  377. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  378. defer cancel()
  379. collection := mdb.MDB.Collection(constant.CNamePlayerLevelStat)
  380. // 查询所有文档
  381. cursor, err := collection.Find(ctx, bson.M{})
  382. if err != nil {
  383. mhayaLogger.Warnf("FindUserLevel Find error:%v", err)
  384. return nil, common.NewResult(code.InternalError)
  385. }
  386. defer cursor.Close(ctx)
  387. var results []*entity.UserLevelCountDetail
  388. var reData []*models.PlayerLevelStat
  389. for cursor.Next(ctx) {
  390. var result models.PlayerLevelStat
  391. if err := cursor.Decode(&result); err != nil {
  392. mhayaLogger.Warnf("FindUserLevel Decode error:%v", err)
  393. return nil, common.NewResult(code.InternalError)
  394. }
  395. reData = append(reData, &result)
  396. }
  397. if err := cursor.Err(); err != nil {
  398. mhayaLogger.Warnf("FindUserLevel cursor error:%v", err)
  399. return nil, common.NewResult(code.InternalError)
  400. }
  401. dataMap := make(map[string]int)
  402. for _, v := range reData {
  403. for key, v1 := range v.ServerLevel {
  404. dataMap[key] += v1
  405. }
  406. }
  407. for k, v := range dataMap {
  408. results = append(results, &entity.UserLevelCountDetail{
  409. Level: cast.ToInt(k),
  410. UserCount: v,
  411. })
  412. }
  413. return &entity.UserLevelCountResp{
  414. Details: results,
  415. }, nil
  416. }
  417. func (s *Synthesis) InsertRecord(param model.UserOperationLog) {
  418. mhayaLogger.Warnf("InsertRecord param:%#v", param)
  419. record := new(model.UserOperationLog)
  420. collection := mdb.MDB.Collection(record.TableName())
  421. insertData := bson.M{}
  422. insertData["user_name"] = param.Username
  423. insertData["role_id"] = param.RoleId
  424. insertData["url"] = param.Path
  425. insertData["method"] = param.Method
  426. insertData["status_code"] = param.StatusCode
  427. insertData["dur"] = param.Dur
  428. insertData["client_ip"] = param.ClientIP
  429. insertData["error_message"] = param.ErrorMessage
  430. insertData["created_at"] = mhayaTime.Now().Unix()
  431. _, err := collection.InsertOne(context.Background(), insertData)
  432. if err != nil {
  433. mhayaLogger.Warnf("InsertRecord InsertOne error:%v", err)
  434. return
  435. }
  436. }
  437. func (s *Synthesis) RecordList(req entity.RecordListReq) (*entity.RecordListResp, *code.Result) {
  438. record := new(model.UserOperationLog)
  439. collection := mdb.MDB.Collection(record.TableName())
  440. // 构建过滤器
  441. filter := bson.M{}
  442. if req.UserName != "" {
  443. filter["userName"] = req.UserName
  444. }
  445. if req.RoleId != "" {
  446. filter["role_id"] = req.RoleId
  447. }
  448. if req.ID != "" {
  449. id, err := primitive.ObjectIDFromHex(req.ID)
  450. if err != nil {
  451. mhayaLogger.Warnf("RecordList ObjectIDFromHex error:%v, req.ID:%s", err, req.ID)
  452. return nil, common.NewResult(code.ParamError)
  453. }
  454. filter["id"] = id
  455. }
  456. if req.StartTime != 0 {
  457. filter["createAt"] = bson.M{
  458. "$gte": req.StartTime,
  459. "$lte": req.EndTime,
  460. }
  461. }
  462. // 设置分页选项
  463. findOptions := options.Find()
  464. findOptions.SetSkip(int64((req.Page - 1) * req.Size))
  465. findOptions.SetLimit(int64(req.Size))
  466. findOptions.SetSort(bson.D{{"created_at", -1}})
  467. // 获取总数total
  468. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  469. defer cancel()
  470. count, err := collection.CountDocuments(ctx, filter)
  471. if err != nil {
  472. mhayaLogger.Warnf("RecordList CountDocuments error:%v", err)
  473. return nil, common.NewResult(code.InternalError)
  474. }
  475. // 查询数据
  476. var results []*entity.RecordListDetail
  477. cursor, err := collection.Find(ctx, filter, findOptions)
  478. if err != nil {
  479. mhayaLogger.Warnf("RecordList Find error:%v", err)
  480. return nil, common.NewResult(code.InternalError)
  481. }
  482. defer cursor.Close(ctx)
  483. // 解析结果
  484. for cursor.Next(ctx) {
  485. var result entity.RecordListDetail
  486. if err := cursor.Decode(&result); err != nil {
  487. mhayaLogger.Warnf("RecordList Decode error:%v", err)
  488. return nil, common.NewResult(code.InternalError)
  489. }
  490. results = append(results, &result)
  491. }
  492. if err := cursor.Err(); err != nil {
  493. mhayaLogger.Warnf("RecordList cursor error:%v", err)
  494. return nil, common.NewResult(code.InternalError)
  495. }
  496. return &entity.RecordListResp{
  497. Details: results,
  498. Total: count,
  499. }, nil
  500. }