synthesis.go 18 KB

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