package admin import ( "context" v1 "github.com/go-nunu/nunu-layout-advanced/api/v1" adminApi "github.com/go-nunu/nunu-layout-advanced/api/v1/admin" "github.com/go-nunu/nunu-layout-advanced/internal/model" "github.com/go-nunu/nunu-layout-advanced/internal/repository" "gorm.io/gorm" "math" "strings" ) type WafLogRepository interface { GetWafLog(ctx context.Context, id int64) (*model.WafLog, error) GetWafLogList(ctx context.Context, req adminApi.SearchWafLogParams) (*v1.PaginatedResponse[model.WafLog], error) AddWafLog(ctx context.Context, log *model.WafLog) error BatchAddWafLog(ctx context.Context, logs []*model.WafLog) error // 导出日志(已更新) ExportWafLog(ctx context.Context, req adminApi.ExportWafLog) ([]model.WafLogWithGatewayIP, error) // 支持分页的导出方法(已更新) ExportWafLogWithPagination(ctx context.Context, req adminApi.ExportWafLog, page, pageSize int) ([]model.WafLogWithGatewayIP, error) // 获取导出数据总数 GetWafLogExportCount(ctx context.Context, req adminApi.ExportWafLog) (int, error) } func NewWafLogRepository( repository *repository.Repository, ) WafLogRepository { return &wafLogRepository{ Repository: repository, } } type wafLogRepository struct { *repository.Repository } func (r *wafLogRepository) GetWafLog(ctx context.Context, id int64) (*model.WafLog, error) { var res model.WafLog return &res, r.DBWithName(ctx,"admin").Where("id = ?", id).First(&res).Error } func (r *wafLogRepository) GetWafLogList(ctx context.Context, req adminApi.SearchWafLogParams) (*v1.PaginatedResponse[model.WafLog], error) { var res []model.WafLog var total int64 query := r.DBWithName(ctx,"admin").Model(&model.WafLog{}) if req.RequestIp != "" { trimmedName := strings.TrimSpace(req.RequestIp) query = query.Where("request_ip LIKE CONCAT('%', ?, '%')", trimmedName) } if req.Uid != 0 { query = query.Where("uid = ?", req.Uid) } if req.Api != "" { trimmedName := strings.TrimSpace(req.Api) query = query.Where("api LIKE CONCAT('%', ?, '%')", trimmedName) } if req.Name != "" { trimmedName := strings.TrimSpace(req.Name) query = query.Where("name LIKE CONCAT('%', ?, '%')", trimmedName) } if req.RuleId != 0 { query = query.Where("rule_id = ?", req.RuleId) } if req.HostId != 0 { query = query.Where("host_id = ?", req.HostId) } if req.Api != "" { trimmedName := strings.TrimSpace(req.Api) query = query.Where("api LIKE CONCAT('%', ?, '%')", trimmedName) } if req.UserAgent != "" { trimmedName := strings.TrimSpace(req.UserAgent) query = query.Where("user_agent LIKE CONCAT('%', ?, '%')", trimmedName) } if req.ApiName != "" { trimmedName := strings.TrimSpace(req.ApiName) query = query.Where("api_name LIKE CONCAT('%', ?, '%')", trimmedName) } if req.ApiType != "" { query = query.Where("api_type = ?", req.ApiType) } if req.Column != "" { query = query.Order(req.Column + " " + req.Order) } if err := query.Count(&total).Error; err != nil { return nil, err } page := req.Current pageSize := req.PageSize if page <= 0 { page = 1 } if pageSize <= 0 { pageSize = 10 } else if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize result := query.Offset(offset).Limit(pageSize).Find(&res) if result.Error != nil { return nil, result.Error } return &v1.PaginatedResponse[model.WafLog]{ Records: res, Page: page, PageSize: pageSize, Total: total, TotalPages: int(math.Ceil(float64(total) / float64(pageSize))), }, nil } func (r *wafLogRepository) AddWafLog(ctx context.Context, log *model.WafLog) error { return r.DBWithName(ctx,"admin").Create(log).Error } func (r *wafLogRepository) BatchAddWafLog(ctx context.Context, logs []*model.WafLog) error { if len(logs) == 0 { return nil } return r.DBWithName(ctx, "admin").CreateInBatches(logs, len(logs)).Error } func (r *wafLogRepository) ExportWafLog(ctx context.Context, req adminApi.ExportWafLog) ([]model.WafLogWithGatewayIP, error) { return r.ExportWafLogWithPagination(ctx, req, 0, 0) } // ExportWafLogWithPagination 使用子查询获取每条日志在当时时间点的正确网关组IP func (r *wafLogRepository) ExportWafLogWithPagination(ctx context.Context, req adminApi.ExportWafLog, page, pageSize int) ([]model.WafLogWithGatewayIP, error) { var res []model.WafLogWithGatewayIP // 主查询,我们将其命名为 "wl" 以便在子查询中引用 query := r.DBWithName(ctx, "admin").Model(&model.WafLog{}).Table("waf_log as wl") // --- 构建子查询 --- // 这个子查询的目标是:对于 "wl" 表中的每一行,找到在它创建时间点之前(或同时)的、 // host_id 和 uid 都匹配的、最新的那条 "分配网关组" 的日志,并返回其 extra_data。 subQuery := r.DBWithName(ctx, "admin").Model(&model.WafLog{}). Select("extra_data"). Where("api_name = ?", "分配网关组"). Where("host_id = wl.host_id"). // 关联主查询的 host_id Where("uid = wl.uid"). // 关联主查询的 uid Where("created_at <= wl.created_at"). // 时间条件:必须是历史或当前记录 Order("created_at DESC"). // 按时间降序,保证第一条是最新 Limit(1) // 只取最新的一条 // --- 构建主查询的选择列表 --- // "wl.*" 选择 waf_log 表的所有字段 // 第二个参数是使用子查询作为 "gateway_ip_data" 字段的值 query = query.Select("wl.*, (?) as gateway_ip_data", subQuery) // --- 应用过滤条件 (与原函数保持一致) --- if req.RequestIp != "" { query = query.Where("wl.request_ip = ?", strings.TrimSpace(req.RequestIp)) } if req.Uid != 0 { query = query.Where("wl.uid = ?", req.Uid) } if req.Api != "" { query = query.Where("wl.api = ?", strings.TrimSpace(req.Api)) } if req.Name != "" { query = query.Where("wl.name = ?", strings.TrimSpace(req.Name)) } if req.RuleId != 0 { query = query.Where("wl.rule_id = ?", req.RuleId) } if len(req.HostIds) > 0 { query = query.Where("wl.host_id IN ?", req.HostIds) } if req.UserAgent != "" { query = query.Where("wl.user_agent = ?", strings.TrimSpace(req.UserAgent)) } if len(req.ApiNames) > 0 { query = query.Where("wl.api_name IN ?", req.ApiNames) } if len(req.ApiTypes) > 0 { query = query.Where("wl.api_type IN ?", req.ApiTypes) } if req.StartTime != "" { query = query.Where("wl.created_at > ?", strings.TrimSpace(req.StartTime)) } if req.EndTime != "" { query = query.Where("wl.created_at < ?", strings.TrimSpace(req.EndTime)) } // --- 应用分页 --- if page > 0 && pageSize > 0 { offset := (page - 1) * pageSize query = query.Offset(offset).Limit(pageSize) } // 执行查询 if err := query.Find(&res).Error; err != nil { // 如果是记录未找到的错误,我们希望返回一个空切片而不是错误 if err == gorm.ErrRecordNotFound { return []model.WafLogWithGatewayIP{}, nil } return nil, err } return res, nil } // GetWafLogExportCount 获取导出数据总数 func (r *wafLogRepository) GetWafLogExportCount(ctx context.Context, req adminApi.ExportWafLog) (int, error) { var count int64 query := r.DBWithName(ctx,"admin").Model(&model.WafLog{}) // 复用ExportWafLog的查询条件 if req.RequestIp != "" { trimmedName := strings.TrimSpace(req.RequestIp) query = query.Where("request_ip = ?", trimmedName) } if req.Uid != 0 { query = query.Where("uid = ?", req.Uid) } if req.Api != "" { trimmedName := strings.TrimSpace(req.Api) query = query.Where("api = ?", trimmedName) } if req.Name != "" { trimmedName := strings.TrimSpace(req.Name) query = query.Where("name = ?", trimmedName) } if req.RuleId != 0 { query = query.Where("rule_id = ?", req.RuleId) } if len(req.HostIds) > 0 { query = query.Where("host_id IN ?", req.HostIds) } if req.UserAgent != "" { trimmedName := strings.TrimSpace(req.UserAgent) query = query.Where("user_agent = ?", trimmedName) } if len(req.ApiNames) > 0 { trimmedNames := make([]string, len(req.ApiNames)) for i, apiName := range req.ApiNames { trimmedNames[i] = strings.TrimSpace(apiName) } query = query.Where("api_name IN ?", trimmedNames) } if len(req.ApiTypes) > 0 { query = query.Where("api_type IN ?", req.ApiTypes) } if req.StartTime != "" { trimmedName := strings.TrimSpace(req.StartTime) query = query.Where("created_at > ?", trimmedName) } if req.EndTime != "" { trimmedName := strings.TrimSpace(req.EndTime) query = query.Where("created_at < ?", trimmedName) } result := query.Count(&count) if result.Error != nil { return 0, result.Error } return int(count), nil }