调整ListUserHistory

This commit is contained in:
2025-10-19 20:36:10 +08:00
parent 4e046021e3
commit 71afbf5ff9
2 changed files with 53 additions and 58 deletions

View File

@@ -96,7 +96,7 @@ func NewAPI(cfg config.ServerConfig,
config: cfg, config: cfg,
listenHandler: listenHandler, listenHandler: listenHandler,
// 在 NewAPI 中初始化用户控制器,并将其作为 API 结构体的成员 // 在 NewAPI 中初始化用户控制器,并将其作为 API 结构体的成员
userController: user.NewController(userRepo, userActionLogRepository, logger, tokenService), userController: user.NewController(userRepo, monitorService, logger, tokenService),
// 在 NewAPI 中初始化设备控制器,并将其作为 API 结构体的成员 // 在 NewAPI 中初始化设备控制器,并将其作为 API 结构体的成员
deviceController: device.NewController(deviceRepository, areaControllerRepository, deviceTemplateRepository, deviceService, logger), deviceController: device.NewController(deviceRepository, areaControllerRepository, deviceTemplateRepository, deviceService, logger),
// 在 NewAPI 中初始化计划控制器,并将其作为 API 结构体的成员 // 在 NewAPI 中初始化计划控制器,并将其作为 API 结构体的成员

View File

@@ -1,11 +1,12 @@
package user package user
import ( import (
"errors"
"strconv" "strconv"
"time"
"git.huangwc.com/pig/pig-farm-controller/internal/app/controller" "git.huangwc.com/pig/pig-farm-controller/internal/app/controller"
"git.huangwc.com/pig/pig-farm-controller/internal/app/dto" "git.huangwc.com/pig/pig-farm-controller/internal/app/dto"
"git.huangwc.com/pig/pig-farm-controller/internal/app/service"
"git.huangwc.com/pig/pig-farm-controller/internal/domain/token" "git.huangwc.com/pig/pig-farm-controller/internal/domain/token"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs" "git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models" "git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
@@ -16,19 +17,19 @@ import (
// Controller 用户控制器 // Controller 用户控制器
type Controller struct { type Controller struct {
userRepo repository.UserRepository userRepo repository.UserRepository
auditRepo repository.UserActionLogRepository monitorService service.MonitorService
logger *logs.Logger tokenService token.TokenService // 注入 token 服务
tokenService token.TokenService // 注入 token 服务 logger *logs.Logger
} }
// NewController 创建用户控制器实例 // NewController 创建用户控制器实例
func NewController(userRepo repository.UserRepository, auditRepo repository.UserActionLogRepository, logger *logs.Logger, tokenService token.TokenService) *Controller { func NewController(userRepo repository.UserRepository, monitorService service.MonitorService, logger *logs.Logger, tokenService token.TokenService) *Controller {
return &Controller{ return &Controller{
userRepo: userRepo, userRepo: userRepo,
auditRepo: auditRepo, monitorService: monitorService,
logger: logger, tokenService: tokenService,
tokenService: tokenService, logger: logger,
} }
} }
@@ -128,20 +129,18 @@ func (c *Controller) Login(ctx *gin.Context) {
// ListUserHistory godoc // ListUserHistory godoc
// @Summary 获取指定用户的操作历史 // @Summary 获取指定用户的操作历史
// @Description 根据用户ID分页获取该用户的操作审计日志。 // @Description 根据用户ID分页获取该用户的操作审计日志。支持与通用日志查询接口相同的过滤和排序参数。
// @Tags 用户管理 // @Tags 用户管理
// @Security BearerAuth // @Security BearerAuth
// @Produce json // @Produce json
// @Param id path int true "用户ID" // @Param id path int true "用户ID"
// @Param page query int false "页码" default(1) // @Param query query dto.ListUserActionLogRequest false "查询参数 (除了 user_id它被路径中的ID覆盖)"
// @Param page_size query int false "每页大小" default(10) // @Success 200 {object} controller.Response{data=dto.ListUserActionLogResponse} "业务码为200代表成功获取"
// @Param action_type query string false "按操作类型过滤"
// @Success 200 {object} controller.Response{data=dto.ListHistoryResponse} "业务码为200代表成功获取"
// @Router /api/v1/users/{id}/history [get] // @Router /api/v1/users/{id}/history [get]
func (c *Controller) ListUserHistory(ctx *gin.Context) { func (c *Controller) ListUserHistory(ctx *gin.Context) {
const actionType = "获取用户操作历史" const actionType = "获取用户操作历史"
// 1. 解析路径中的用户ID // 1. 解析路径中的用户ID,它的优先级最高
userIDStr := ctx.Param("id") userIDStr := ctx.Param("id")
userID, err := strconv.ParseUint(userIDStr, 10, 64) userID, err := strconv.ParseUint(userIDStr, 10, 64)
if err != nil { if err != nil {
@@ -150,50 +149,46 @@ func (c *Controller) ListUserHistory(ctx *gin.Context) {
return return
} }
// 2. 解析分页和过滤参数 // 2. 绑定通用的查询请求 DTO
page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1")) var req dto.ListUserActionLogRequest
pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10")) if err := ctx.ShouldBindQuery(&req); err != nil {
actionTypeFilter := ctx.Query("action_type") c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的查询参数: "+err.Error(), actionType, "参数绑定失败", req)
// 确保分页参数有效
if page <= 0 {
page = 1
}
if pageSize <= 0 || pageSize > 100 {
pageSize = 10
}
// 3. 调用审计仓库层获取历史数据
id := uint(userID)
findOptions := repository.UserActionLogListOptions{
UserID: &id,
ActionType: &actionTypeFilter,
}
l, total, err := c.auditRepo.List(findOptions, page, pageSize)
if err != nil {
c.logger.Errorf("%s: 查询历史记录失败: %v, Options: %+v", actionType, err, findOptions)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "查询历史记录失败", actionType, "查询历史记录失败", findOptions)
return return
} }
// 4. 将数据库模型转换为响应 DTO // 3. 准备 Service 调用参数,并强制使用路径中的 UserID
historyResponses := make([]dto.HistoryResponse, 0, len(l)) uid := uint(userID)
for _, log := range l { req.UserID = &uid // 强制覆盖
historyResponses = append(historyResponses, dto.HistoryResponse{
UserID: log.UserID, opts := repository.UserActionLogListOptions{
Username: log.Username, UserID: req.UserID,
ActionType: log.ActionType, Username: req.Username,
Description: log.Description, ActionType: req.ActionType,
TargetResource: log.TargetResource, OrderBy: req.OrderBy,
Time: log.Time.Format(time.RFC3339), StartTime: req.StartTime,
}) EndTime: req.EndTime,
}
if req.Status != nil {
status := models.AuditStatus(*req.Status)
opts.Status = &status
} }
// 5. 发送成功响应 // 4. 调用 monitorService复用其业务逻辑
resp := dto.ListHistoryResponse{ data, total, err := c.monitorService.ListUserActionLogs(opts, req.Page, req.PageSize)
History: historyResponses, if err != nil {
Total: total, if errors.Is(err, repository.ErrInvalidPagination) {
c.logger.Warnf("%s: 无效的分页参数: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的分页参数: "+err.Error(), actionType, "无效分页参数", opts)
return
}
c.logger.Errorf("%s: 服务层查询失败: %v", actionType, err)
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取用户历史记录失败", actionType, "服务层查询失败", opts)
return
} }
c.logger.Infof("%s: 成功获取用户 %d 的操作历史, 数量: %d", actionType, userID, len(historyResponses))
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取用户操作历史成功", resp, actionType, "获取用户操作历史成功", resp) // 5. 使用复用的 DTO 构建并发送成功响应
resp := dto.NewListUserActionLogResponse(data, total, req.Page, req.PageSize)
c.logger.Infof("%s: 成功获取用户 %d 的操作历史, 数量: %d", actionType, userID, len(data))
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取用户操作历史成功", resp, actionType, "获取用户操作历史成功", opts)
} }