synthesis.go 18 KB

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