get.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2017 utimes.cc. All rights reserved.
  2. // Use of this source code is governed by utimes.cc.
  3. package action
  4. import (
  5. "gd_admin/apis"
  6. "gd_admin/consts"
  7. "gd_admin/errors"
  8. "encoding/json"
  9. "fmt"
  10. "gd_admin/common.in/jsonrpc2"
  11. "github.com/astaxie/beego/orm"
  12. "go.uber.org/zap"
  13. "golang.org/x/net/context"
  14. )
  15. // getSql 获取查询sql
  16. func getSql(req *apis.GetLogReq) (string, string) {
  17. sql := "SELECT a.id, admin_name as user, a.modules, a.func, a.name, a.before, a.after, a.created_at FROM t_gd_admin_action_log a INNER JOIN t_gd_admin b ON a.uid = b.id"
  18. countSql := "SELECT count(*) as total FROM t_gd_admin_action_log a INNER JOIN t_gd_admin b ON a.uid = b.id"
  19. if req.Search != "" {
  20. sql += " WHERE after LIKE '%" + req.Search + "%'"
  21. countSql += " WHERE after LIKE '%" + req.Search + "%'"
  22. }
  23. // 计算分页
  24. var (
  25. pageSize = consts.PageSize
  26. start int
  27. )
  28. if req.PageSize != 0 {
  29. pageSize = req.PageSize
  30. }
  31. if req.PageNum <= 1 {
  32. start = 0
  33. } else {
  34. start = (req.PageNum - 1) * pageSize
  35. }
  36. sql = fmt.Sprintf("%s ORDER BY a.created_at DESC LIMIT %d, %d", sql, start, pageSize)
  37. return sql, countSql
  38. }
  39. // Log 获取用户行为日志
  40. func Log(ctx context.Context, req *apis.GetLogReq, reply *apis.GetLogReply) (err error) {
  41. // 捕获各个task中的异常并返回给调用者
  42. defer func() {
  43. if r := recover(); r != nil {
  44. err := fmt.Errorf("%+v", r)
  45. e := &jsonrpc2.Error{}
  46. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  47. l.Error("err",
  48. zap.String("system_err", err.Error()),
  49. zap.Stack("stacktrace"))
  50. }
  51. }
  52. }()
  53. sql, countSql := getSql(req)
  54. err = orm.NewOrm().Raw(countSql).QueryRow(&reply.Total)
  55. if err != nil {
  56. l.Error("mysql",
  57. zap.String("sql", countSql),
  58. zap.String("fields", ""),
  59. zap.String("error", err.Error()))
  60. return errors.DataBaseError
  61. }
  62. reply.List = make([]apis.LogList, 0)
  63. if reply.Total > 0 {
  64. _, err = orm.NewOrm().Raw(sql).QueryRows(&reply.List)
  65. if err != nil {
  66. l.Error("mysql",
  67. zap.String("sql", sql),
  68. zap.String("fields", ""),
  69. zap.String("error", err.Error()))
  70. return errors.DataBaseError
  71. }
  72. }
  73. return nil
  74. }