synthesis.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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. // 统计用户相关信息
  30. func (s *Synthesis) UserList(req entity.UserListReq) (*entity.UserListResp, *code.Result) {
  31. page, pageSize := checkPageParam(req.Page, req.Size)
  32. // 构建查询条件
  33. filter := bson.M{}
  34. if req.UserName != "" {
  35. filter["userName"] = req.UserName
  36. }
  37. if req.NickName != "" {
  38. filter["nickName"] = req.NickName
  39. }
  40. // 设置分页选项
  41. findOptions := options.Find()
  42. findOptions.SetSkip(int64((page - 1) * pageSize))
  43. findOptions.SetLimit(int64(pageSize))
  44. findOptions.SetSort(bson.D{{"createTime", -1}})
  45. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  46. defer cancel()
  47. collection := mdb.MDB.Collection(constant.CNamePlayer)
  48. // 获取总数total
  49. count, err := collection.CountDocuments(ctx, filter)
  50. if err != nil {
  51. mhayaLogger.Warnf("UserList CountDocuments error:%v", err)
  52. return nil, common.NewResult(code.InternalError)
  53. }
  54. // TODO UserList 统计用户相关信息
  55. // 查询数据
  56. var results []*entity.UserListDetail
  57. cursor, err := collection.Find(ctx, filter, findOptions)
  58. if err != nil {
  59. mhayaLogger.Warnf("UserList Find error:%v", err)
  60. return nil, common.NewResult(code.InternalError)
  61. }
  62. defer cursor.Close(ctx)
  63. // 解析结果
  64. for cursor.Next(ctx) {
  65. var result entity.UserListDetail
  66. if err := cursor.Decode(&result); err != nil {
  67. mhayaLogger.Warnf("UserList Decode error:%v", err)
  68. return nil, common.NewResult(code.InternalError)
  69. }
  70. results = append(results, &result)
  71. }
  72. if err := cursor.Err(); err != nil {
  73. mhayaLogger.Warnf("UserList cursor error:%v", err)
  74. return nil, common.NewResult(code.InternalError)
  75. }
  76. return &entity.UserListResp{
  77. Details: results,
  78. Total: count,
  79. }, nil
  80. }
  81. func (s *Synthesis) FindMDBUserLogDaily(req entity.UserLogDailyReq) (*entity.UserLogDailyResp, *code.Result) {
  82. page, pageSize := checkPageParam(req.Page, req.Size)
  83. // 定义上下文
  84. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  85. defer cancel()
  86. // 指定集合
  87. collection := mdb.MDB.Collection(constant.CNamePlayerDailyRecord)
  88. // 构建查询条件 - 如果查询值为空那就不添加查询条件
  89. filter := bson.M{}
  90. if req.StartTime != 0 {
  91. filter["daily"] = bson.M{
  92. "$gte": req.StartTime,
  93. "$lte": req.EndTime,
  94. }
  95. }
  96. if req.Platform != "" && req.Platform != "all" {
  97. filter["platform"] = req.Platform
  98. }
  99. if req.Channel != "" {
  100. filter["channel"] = req.Channel
  101. }
  102. // 计算总数
  103. count, err := collection.CountDocuments(ctx, filter)
  104. if err != nil {
  105. mhayaLogger.Warnf("FindMDBUserLogDaily CountDocuments error:%v", err)
  106. return nil, common.NewResult(code.InternalError)
  107. }
  108. // 执行查询
  109. opts := options.Find()
  110. opts.SetSkip(int64((page - 1) * pageSize))
  111. opts.SetLimit(int64(pageSize))
  112. opts.SetSort(bson.D{{"daily", -1}})
  113. cursor, err := collection.Find(ctx, filter, opts)
  114. if err != nil {
  115. mhayaLogger.Warnf("FindMDBUserLogDaily Find error:%v", err)
  116. return nil, common.NewResult(code.InternalError)
  117. }
  118. defer cursor.Close(ctx)
  119. // 解析查询结果
  120. var results []*entity.UserLogDailyDetail
  121. for cursor.Next(ctx) {
  122. var result *entity.UserLogDailyDetail
  123. err := cursor.Decode(&result)
  124. if err != nil {
  125. mhayaLogger.Warnf("FindMDBUserLogDaily Decode error:%v", err)
  126. return nil, common.NewResult(code.InternalError)
  127. }
  128. results = append(results, result)
  129. }
  130. // 同一天的数据全部放到platform= ALl 且数据累加
  131. // 如果没有platform=all 的那就新增一个 同一个时间段只能有一个 platform=all
  132. // 将同一天的数据累加到platform=all的记录中
  133. allPlatformRecordMap := make(map[int64]*entity.UserLogDailyDetail)
  134. for _, result := range results {
  135. allPlatformRecordMap[result.Timestamp] = &entity.UserLogDailyDetail{
  136. Timestamp: result.Timestamp,
  137. Platform: "all",
  138. }
  139. }
  140. for _, v := range results {
  141. if v.Timestamp == allPlatformRecordMap[v.Timestamp].Timestamp {
  142. allPlatformRecordMap[v.Timestamp].Registered += v.Registered
  143. allPlatformRecordMap[v.Timestamp].LoggedIn += v.LoggedIn
  144. allPlatformRecordMap[v.Timestamp].NewActive += v.NewActive
  145. allPlatformRecordMap[v.Timestamp].OldActive += v.OldActive
  146. allPlatformRecordMap[v.Timestamp].TotalPoints += v.TotalPoints
  147. allPlatformRecordMap[v.Timestamp].UProduced += v.UProduced
  148. allPlatformRecordMap[v.Timestamp].UCashout += v.UCashout
  149. allPlatformRecordMap[v.Timestamp].NewLogin += v.NewLogin
  150. allPlatformRecordMap[v.Timestamp].OldLogin += v.OldLogin
  151. }
  152. }
  153. // 替换原有结果
  154. for _, record := range allPlatformRecordMap {
  155. results = append(results, record)
  156. }
  157. return &entity.UserLogDailyResp{
  158. Details: results,
  159. Total: count,
  160. }, nil
  161. }
  162. // FindWithdrawal 根据请求查询提现记录
  163. func (s *Synthesis) FindWithdrawal(req entity.UserWithdrawalReq) (*entity.UserWithdrawalResp, *code.Result) {
  164. page, pageSize := checkPageParam(req.Page, req.Size)
  165. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  166. defer cancel()
  167. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  168. // 构建过滤器
  169. filter := bson.M{}
  170. if req.UserName != "" {
  171. filter["userName"] = req.UserName
  172. }
  173. if req.NickName != "" {
  174. filter["nickName"] = req.NickName
  175. }
  176. if req.ID != "" {
  177. filter["_id"], _ = primitive.ObjectIDFromHex(req.ID)
  178. }
  179. if req.Address != "" {
  180. filter["address"] = req.Address
  181. }
  182. if req.State > 0 {
  183. filter["state"] = req.State
  184. }
  185. if req.Withdrawal > 0 {
  186. filter["withdrawal"] = req.Withdrawal
  187. }
  188. if req.StartTime > 0 && req.EndTime > 0 && req.StartTime <= req.EndTime {
  189. filter["createAt"] = bson.M{
  190. "$gte": req.StartTime,
  191. "$lte": req.EndTime,
  192. }
  193. }
  194. if req.AmountMin > 0 && req.AmountMax > 0 && req.AmountMin <= req.AmountMax {
  195. filter["amount"] = bson.M{
  196. "$gte": req.AmountMin,
  197. "$lte": req.AmountMax,
  198. }
  199. }
  200. if req.AfterAmountMin > 0 && req.AfterAmountMax > 0 && req.AfterAmountMin <= req.AfterAmountMax {
  201. filter["after_amount"] = bson.M{
  202. "$gte": req.AfterAmountMin,
  203. "$lte": req.AfterAmountMax,
  204. }
  205. }
  206. // 设置分页选项
  207. findOptions := options.Find()
  208. findOptions.SetSkip(int64((page - 1) * pageSize))
  209. findOptions.SetLimit(int64(pageSize))
  210. findOptions.SetSort(bson.D{{"createAt", -1}})
  211. // 获取总数total
  212. count, err := collection.CountDocuments(ctx, filter)
  213. if err != nil {
  214. mhayaLogger.Warnf("FindWithdrawal CountDocuments error:%v", err)
  215. return nil, common.NewResult(code.InternalError)
  216. }
  217. // 查询数据
  218. var results []*entity.UserWithdrawalDetail
  219. cursor, err := collection.Find(ctx, filter, findOptions)
  220. if err != nil {
  221. mhayaLogger.Warnf("FindWithdrawal Find error:%v", err)
  222. return nil, common.NewResult(code.InternalError)
  223. }
  224. defer cursor.Close(ctx)
  225. // 解析结果
  226. for cursor.Next(ctx) {
  227. var result entity.UserWithdrawalDetail
  228. if err := cursor.Decode(&result); err != nil {
  229. mhayaLogger.Warnf("FindWithdrawal Decode error:%v", err)
  230. return nil, common.NewResult(code.InternalError)
  231. }
  232. results = append(results, &result)
  233. }
  234. if err := cursor.Err(); err != nil {
  235. mhayaLogger.Warnf("FindWithdrawal cursor error:%v", err)
  236. return nil, common.NewResult(code.InternalError)
  237. }
  238. return &entity.UserWithdrawalResp{
  239. Details: results,
  240. Total: count,
  241. }, nil
  242. }
  243. // 导出提现记录
  244. func (s *Synthesis) WithdrawalExport(req entity.UserWithdrawalExportReq) (*entity.UserWithdrawalResp, *code.Result) {
  245. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  246. defer cancel()
  247. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  248. // 构建过滤器
  249. filter := bson.M{}
  250. if req.UserName != "" {
  251. filter["userName"] = req.UserName
  252. }
  253. if req.NickName != "" {
  254. filter["nickName"] = req.NickName
  255. }
  256. if req.ID != "" {
  257. filter["_id"], _ = primitive.ObjectIDFromHex(req.ID)
  258. }
  259. if req.Address != "" {
  260. filter["address"] = req.Address
  261. }
  262. if req.State > 0 {
  263. filter["state"] = req.State
  264. }
  265. if req.Withdrawal > 0 {
  266. filter["withdrawal"] = req.Withdrawal
  267. }
  268. if req.StartTime > 0 && req.EndTime > 0 && req.StartTime <= req.EndTime {
  269. filter["createAt"] = bson.M{
  270. "$gte": req.StartTime,
  271. "$lte": req.EndTime,
  272. }
  273. }
  274. if req.AmountMin > 0 && req.AmountMax > 0 && req.AmountMin <= req.AmountMax {
  275. filter["amount"] = bson.M{
  276. "$gte": req.AmountMin,
  277. "$lte": req.AmountMax,
  278. }
  279. }
  280. if req.AfterAmountMin > 0 && req.AfterAmountMax > 0 && req.AfterAmountMin <= req.AfterAmountMax {
  281. filter["after_amount"] = bson.M{
  282. "$gte": req.AfterAmountMin,
  283. "$lte": req.AfterAmountMax,
  284. }
  285. }
  286. findOptions := options.Find()
  287. findOptions.SetSort(bson.D{{"createAt", -1}})
  288. // 获取总数total
  289. count, err := collection.CountDocuments(ctx, filter)
  290. if err != nil {
  291. mhayaLogger.Warnf("WithdrawalExportData CountDocuments error:%v", err)
  292. return nil, common.NewResult(code.InternalError)
  293. }
  294. // 查询数据
  295. var results []*entity.UserWithdrawalDetail
  296. cursor, err := collection.Find(ctx, filter, findOptions)
  297. if err != nil {
  298. mhayaLogger.Warnf("WithdrawalExportData Find error:%v", err)
  299. return nil, common.NewResult(code.InternalError)
  300. }
  301. defer cursor.Close(ctx)
  302. // 解析结果
  303. for cursor.Next(ctx) {
  304. var result entity.UserWithdrawalDetail
  305. if err := cursor.Decode(&result); err != nil {
  306. mhayaLogger.Warnf("WithdrawalExportData Decode error:%v", err)
  307. return nil, common.NewResult(code.InternalError)
  308. }
  309. results = append(results, &result)
  310. }
  311. if err := cursor.Err(); err != nil {
  312. mhayaLogger.Warnf("WithdrawalExportData cursor error:%v", err)
  313. return nil, common.NewResult(code.InternalError)
  314. }
  315. return &entity.UserWithdrawalResp{
  316. Details: results,
  317. Total: count,
  318. }, nil
  319. }
  320. // WithdrawalStatus 更新提现状态
  321. func (s *Synthesis) WithdrawalStatus(req entity.UserWithdrawalStatus) *code.Result {
  322. // ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  323. // defer cancel()
  324. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  325. // 更新条件
  326. updateCondition := bson.M{"userName": req.UserName}
  327. // 更新内容
  328. updateContent := bson.M{"$set": bson.M{"status": req.Status}}
  329. // 设置更新选项
  330. updateOptions := options.Update() // 设置 upsert 选项
  331. // 执行更新操作
  332. _, err := collection.UpdateOne(context.TODO(), updateCondition, updateContent, updateOptions)
  333. if err != nil {
  334. mhayaLogger.Warnf("WithdrawalStatus UpdateOne error:%v", err)
  335. return common.NewResult(code.InternalError)
  336. }
  337. return nil
  338. }
  339. // WithdrawalStatusBatch 更新提现状态
  340. func (s *Synthesis) WithdrawalStatusBatch(req entity.UserWithdrawalStatusBatch) *code.Result {
  341. collection := mdb.MDB.Collection(constant.CNameCashOutRecord)
  342. if len(req.ID) == 0 {
  343. return common.NewResult(code.ParamError)
  344. }
  345. for _, id := range req.ID {
  346. objID := primitive.ObjectID{}
  347. objID, _ = primitive.ObjectIDFromHex(id)
  348. updateCondition := bson.M{"_id": objID}
  349. updateContent := bson.M{}
  350. withdrawal := models.CashOutRecord{}
  351. err := collection.FindOne(context.TODO(), updateCondition).Decode(&withdrawal)
  352. if err != nil {
  353. mhayaLogger.Warnf("WithdrawalStatusBatch FindOne error:%v", err)
  354. continue
  355. }
  356. if req.Withdrawal != 0 {
  357. if withdrawal.Status == 1 {
  358. updateContent = bson.M{"$set": bson.M{"withdrawal": req.Withdrawal}}
  359. } else {
  360. continue
  361. }
  362. }
  363. if req.Status > 0 {
  364. if withdrawal.Status != 0 {
  365. continue
  366. }
  367. updateContent = bson.M{"$set": bson.M{"status": req.Status}}
  368. }
  369. updateOptions := options.Update().SetUpsert(true)
  370. _, err = collection.UpdateOne(context.TODO(), updateCondition, updateContent, updateOptions)
  371. if err != nil {
  372. mhayaLogger.Warnf("WithdrawalStatusBatch UpdateOne error:%v", err)
  373. continue
  374. }
  375. }
  376. return nil
  377. }
  378. // FindUserCountryCount 查询用户国家分布
  379. //
  380. // 返回值为 UserCountryResp 的切片和错误。
  381. func (s *Synthesis) FindUserCountryCount() (*entity.UserCountryResp, *code.Result) {
  382. // 选择数据库和集合
  383. collection := mdb.MDB.Collection(constant.CNamePlayerCountryByIPStat)
  384. // 定义聚合管道
  385. // 定义聚合管道
  386. pipeline := []bson.D{
  387. {
  388. {Key: "$project", Value: bson.D{
  389. {Key: "playerRegisterCountry", Value: bson.D{{Key: "$objectToArray", Value: "$playerRegisterCountry"}}},
  390. }},
  391. },
  392. {
  393. {Key: "$unwind", Value: "$playerRegisterCountry"},
  394. },
  395. {
  396. {Key: "$group", Value: bson.D{
  397. {Key: "_id", Value: "$playerRegisterCountry.k"},
  398. {Key: "totalValue", Value: bson.D{{Key: "$sum", Value: "$playerRegisterCountry.v"}}},
  399. }},
  400. },
  401. {
  402. {Key: "$project", Value: bson.D{
  403. {Key: "_id", Value: 0},
  404. {Key: "countryKey", Value: "$_id"},
  405. {Key: "totalValue", Value: 1},
  406. }},
  407. },
  408. }
  409. // 执行聚合查询
  410. cursor, err := collection.Aggregate(context.TODO(), pipeline)
  411. if err != nil {
  412. mhayaLogger.Warnf("FindUserCountryCount Aggregate error:%v", err)
  413. return nil, common.NewResult(code.InternalError)
  414. }
  415. defer cursor.Close(context.TODO())
  416. // 遍历查询结果
  417. var results []bson.M
  418. if err := cursor.All(context.TODO(), &results); err != nil {
  419. mhayaLogger.Warnf("FindUserCountryCount All error:%v", err)
  420. return nil, common.NewResult(code.InternalError)
  421. }
  422. var totalIPCount int64
  423. var data []*entity.UserCountryDetail
  424. // 将结果转换为 UserCountryDetail
  425. for _, r := range results {
  426. var resp entity.UserCountryDetail
  427. resp.Country = r["countryKey"].(string)
  428. resp.IPCount = int(r["totalValue"].(int32))
  429. totalIPCount += int64(resp.IPCount)
  430. data = append(data, &resp)
  431. }
  432. for _, v := range data {
  433. // 保留小数点后两位
  434. v.Percentage = math.Round(float64(v.IPCount)/float64(totalIPCount)*10000) / 100
  435. }
  436. // 根据阈值过滤结果
  437. otherCount := 0
  438. otherPercentage := 0.00
  439. filteredResults := make([]*entity.UserCountryDetail, 0)
  440. threshold := 1.00
  441. for _, r := range data {
  442. if r.Percentage >= threshold {
  443. filteredResults = append(filteredResults, r)
  444. // 保留小数点后两位
  445. r.Percentage = math.Round(r.Percentage*100) / 100
  446. otherPercentage += r.Percentage
  447. } else {
  448. otherCount += r.IPCount
  449. }
  450. }
  451. // 将其他国家添加到过滤后的结果中
  452. if otherCount > 0 {
  453. p := 100.00 - math.Round(otherPercentage*100)/100
  454. filteredResults = append(filteredResults, &entity.UserCountryDetail{
  455. Country: "other",
  456. IPCount: otherCount,
  457. Percentage: math.Round(p*100) / 100,
  458. })
  459. }
  460. return &entity.UserCountryResp{
  461. Details: filteredResults,
  462. }, nil
  463. }
  464. // FindUserRetention UserRetentionResp 用户留存率
  465. // 1. 获取指定日期范围内的注册用户数量
  466. // 2. 获取指定日期范围内的活跃用户数量
  467. // 3. 计算留存率
  468. // 4. 返回结果
  469. func (s *Synthesis) FindUserRetention(req entity.UserRetentionReq) (*entity.UserRetentionResp, *code.Result) {
  470. playerPreserve := models.GetPlayerPreserve(req.StartTime, req.EndTime)
  471. // 查询数据
  472. var results []*entity.UserRetentionDetail
  473. for key, v := range playerPreserve {
  474. var retention entity.Retention
  475. for _, vv := range v {
  476. if vv.ID == 1 {
  477. retention.Day1 = entity.DayRetention{
  478. LoggedIn: vv.Ratio,
  479. LoginDate: key,
  480. }
  481. }
  482. if vv.ID == 3 {
  483. retention.Day3 = entity.DayRetention{
  484. LoggedIn: vv.Ratio,
  485. LoginDate: key,
  486. }
  487. }
  488. if vv.ID == 7 {
  489. retention.Day7 = entity.DayRetention{
  490. LoggedIn: vv.Ratio,
  491. LoginDate: key,
  492. }
  493. }
  494. if vv.ID == 14 {
  495. retention.Day14 = entity.DayRetention{
  496. LoggedIn: vv.Ratio,
  497. LoginDate: key,
  498. }
  499. }
  500. if vv.ID == 30 {
  501. retention.Day30 = entity.DayRetention{
  502. LoggedIn: vv.Ratio,
  503. LoginDate: key,
  504. }
  505. }
  506. }
  507. results = append(results, &entity.UserRetentionDetail{
  508. RegistrationDate: key,
  509. RetentionData: retention,
  510. })
  511. }
  512. return &entity.UserRetentionResp{
  513. Details: results,
  514. }, nil
  515. }
  516. // FindUserLevel 用户等级统计
  517. func (s *Synthesis) FindUserLevel() (*entity.UserLevelCountResp, *code.Result) {
  518. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  519. defer cancel()
  520. collection := mdb.MDB.Collection(constant.CNamePlayerLevelStat)
  521. // 查询所有文档
  522. cursor, err := collection.Find(ctx, bson.M{})
  523. if err != nil {
  524. mhayaLogger.Warnf("FindUserLevel Find error:%v", err)
  525. return nil, common.NewResult(code.InternalError)
  526. }
  527. defer cursor.Close(ctx)
  528. var results []*entity.UserLevelCountDetail
  529. var reData []*models.PlayerLevelStat
  530. for cursor.Next(ctx) {
  531. var result models.PlayerLevelStat
  532. if err := cursor.Decode(&result); err != nil {
  533. mhayaLogger.Warnf("FindUserLevel Decode error:%v", err)
  534. return nil, common.NewResult(code.InternalError)
  535. }
  536. reData = append(reData, &result)
  537. }
  538. if err := cursor.Err(); err != nil {
  539. mhayaLogger.Warnf("FindUserLevel cursor error:%v", err)
  540. return nil, common.NewResult(code.InternalError)
  541. }
  542. dataMap := make(map[string]int)
  543. for _, v := range reData {
  544. for key, v1 := range v.ServerLevel {
  545. dataMap[key] += v1
  546. }
  547. }
  548. for k, v := range dataMap {
  549. results = append(results, &entity.UserLevelCountDetail{
  550. Level: cast.ToInt(k),
  551. UserCount: v,
  552. })
  553. }
  554. return &entity.UserLevelCountResp{
  555. Details: results,
  556. }, nil
  557. }
  558. func (s *Synthesis) InsertRecord(param model.UserOperationLog) {
  559. mhayaLogger.Warnf("InsertRecord param:%#v", param)
  560. record := new(model.UserOperationLog)
  561. collection := mdb.MDB.Collection(record.TableName())
  562. insertData := bson.M{}
  563. insertData["user_name"] = param.Username
  564. insertData["role_id"] = param.RoleId
  565. insertData["url"] = param.Path
  566. insertData["method"] = param.Method
  567. insertData["status_code"] = param.StatusCode
  568. insertData["dur"] = param.Dur
  569. insertData["client_ip"] = param.ClientIP
  570. insertData["error_message"] = param.ErrorMessage
  571. insertData["created_at"] = mhayaTime.Now().Unix()
  572. _, err := collection.InsertOne(context.Background(), insertData)
  573. if err != nil {
  574. mhayaLogger.Warnf("InsertRecord InsertOne error:%v", err)
  575. return
  576. }
  577. }
  578. func (s *Synthesis) RecordList(req entity.RecordListReq) (*entity.RecordListResp, *code.Result) {
  579. page, pageSize := checkPageParam(req.Page, req.Size)
  580. record := new(model.UserOperationLog)
  581. collection := mdb.MDB.Collection(record.TableName())
  582. // 构建过滤器
  583. filter := bson.M{}
  584. if req.UserName != "" {
  585. filter["userName"] = req.UserName
  586. }
  587. if req.RoleId != "" {
  588. filter["role_id"] = req.RoleId
  589. }
  590. if req.ID != "" {
  591. id, err := primitive.ObjectIDFromHex(req.ID)
  592. if err != nil {
  593. mhayaLogger.Warnf("RecordList ObjectIDFromHex error:%v, req.ID:%s", err, req.ID)
  594. return nil, common.NewResult(code.ParamError)
  595. }
  596. filter["id"] = id
  597. }
  598. if req.StartTime != 0 {
  599. filter["createAt"] = bson.M{
  600. "$gte": req.StartTime,
  601. "$lte": req.EndTime,
  602. }
  603. }
  604. // 设置分页选项
  605. findOptions := options.Find()
  606. findOptions.SetSkip(int64((page - 1) * pageSize))
  607. findOptions.SetLimit(int64(pageSize))
  608. findOptions.SetSort(bson.D{{"created_at", -1}})
  609. // 获取总数total
  610. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
  611. defer cancel()
  612. count, err := collection.CountDocuments(ctx, filter)
  613. if err != nil {
  614. mhayaLogger.Warnf("RecordList CountDocuments error:%v", err)
  615. return nil, common.NewResult(code.InternalError)
  616. }
  617. // 查询数据
  618. var results []*entity.RecordListDetail
  619. cursor, err := collection.Find(ctx, filter, findOptions)
  620. if err != nil {
  621. mhayaLogger.Warnf("RecordList Find error:%v", err)
  622. return nil, common.NewResult(code.InternalError)
  623. }
  624. defer cursor.Close(ctx)
  625. // 解析结果
  626. for cursor.Next(ctx) {
  627. var result entity.RecordListDetail
  628. if err := cursor.Decode(&result); err != nil {
  629. mhayaLogger.Warnf("RecordList Decode error:%v", err)
  630. return nil, common.NewResult(code.InternalError)
  631. }
  632. results = append(results, &result)
  633. }
  634. if err := cursor.Err(); err != nil {
  635. mhayaLogger.Warnf("RecordList cursor error:%v", err)
  636. return nil, common.NewResult(code.InternalError)
  637. }
  638. return &entity.RecordListResp{
  639. Details: results,
  640. Total: count,
  641. }, nil
  642. }
  643. // 转盘统计
  644. func (s *Synthesis) Turntable(req entity.TurntableReq) (*entity.TurntableResp, *code.Result) {
  645. // TODO Turntable 转盘统计
  646. return nil, nil
  647. }
  648. // 资产统计
  649. func (s *Synthesis) Assets(req entity.AssetsReq) (*entity.AssetsResp, *code.Result) {
  650. // TODO Assets 资产统计
  651. return nil, nil
  652. }
  653. // 邀请统计
  654. func (s *Synthesis) Invite(req entity.InviteReq) (*entity.InviteResp, *code.Result) {
  655. // TODO Invite 邀请统计
  656. return nil, nil
  657. }