// Copyright 2017 utimes.cc. All rights reserved. // Use of this source code is governed by utimes.cc. package action import ( "gd_admin/apis" "gd_admin/consts" "gd_admin/errors" "encoding/json" "fmt" "gd_admin/common.in/jsonrpc2" "github.com/astaxie/beego/orm" "go.uber.org/zap" "golang.org/x/net/context" ) // getSql 获取查询sql func getSql(req *apis.GetLogReq) (string, string) { 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" countSql := "SELECT count(*) as total FROM t_gd_admin_action_log a INNER JOIN t_gd_admin b ON a.uid = b.id" if req.Search != "" { sql += " WHERE after LIKE '%" + req.Search + "%'" countSql += " WHERE after LIKE '%" + req.Search + "%'" } // 计算分页 var ( pageSize = consts.PageSize start int ) if req.PageSize != 0 { pageSize = req.PageSize } if req.PageNum <= 1 { start = 0 } else { start = (req.PageNum - 1) * pageSize } sql = fmt.Sprintf("%s ORDER BY a.created_at DESC LIMIT %d, %d", sql, start, pageSize) return sql, countSql } // Log 获取用户行为日志 func Log(ctx context.Context, req *apis.GetLogReq, reply *apis.GetLogReply) (err error) { // 捕获各个task中的异常并返回给调用者 defer func() { if r := recover(); r != nil { err := fmt.Errorf("%+v", r) e := &jsonrpc2.Error{} if er := json.Unmarshal([]byte(err.Error()), e); er != nil { l.Error("err", zap.String("system_err", err.Error()), zap.Stack("stacktrace")) } } }() sql, countSql := getSql(req) err = orm.NewOrm().Raw(countSql).QueryRow(&reply.Total) if err != nil { l.Error("mysql", zap.String("sql", countSql), zap.String("fields", ""), zap.String("error", err.Error())) return errors.DataBaseError } reply.List = make([]apis.LogList, 0) if reply.Total > 0 { _, err = orm.NewOrm().Raw(sql).QueryRows(&reply.List) if err != nil { l.Error("mysql", zap.String("sql", sql), zap.String("fields", ""), zap.String("error", err.Error())) return errors.DataBaseError } } return nil }