This commit is contained in:
2025-08-02 02:54:21 +08:00
parent 934dce2776
commit 66845d3fe0
74 changed files with 8686 additions and 212 deletions

View File

@@ -235,4 +235,98 @@ func (r *GormApiCallRepository) FindByTransactionId(ctx context.Context, transac
return nil, err
}
return &call, nil
}
// ListWithFiltersAndProductName 管理端根据条件筛选所有API调用记录包含产品名称
func (r *GormApiCallRepository) ListWithFiltersAndProductName(ctx context.Context, filters map[string]interface{}, options interfaces.ListOptions) (map[string]string, []*entities.ApiCall, int64, error) {
var callsWithProduct []*ApiCallWithProduct
var total int64
// 构建基础查询条件
whereCondition := "1=1"
whereArgs := []interface{}{}
// 应用筛选条件
if filters != nil {
// 用户ID筛选
if userId, ok := filters["user_id"].(string); ok && userId != "" {
whereCondition += " AND ac.user_id = ?"
whereArgs = append(whereArgs, userId)
}
// 时间范围筛选
if startTime, ok := filters["start_time"].(time.Time); ok {
whereCondition += " AND ac.created_at >= ?"
whereArgs = append(whereArgs, startTime)
}
if endTime, ok := filters["end_time"].(time.Time); ok {
whereCondition += " AND ac.created_at <= ?"
whereArgs = append(whereArgs, endTime)
}
// TransactionID筛选
if transactionId, ok := filters["transaction_id"].(string); ok && transactionId != "" {
whereCondition += " AND ac.transaction_id LIKE ?"
whereArgs = append(whereArgs, "%"+transactionId+"%")
}
// 产品名称筛选
if productName, ok := filters["product_name"].(string); ok && productName != "" {
whereCondition += " AND p.name LIKE ?"
whereArgs = append(whereArgs, "%"+productName+"%")
}
// 状态筛选
if status, ok := filters["status"].(string); ok && status != "" {
whereCondition += " AND ac.status = ?"
whereArgs = append(whereArgs, status)
}
}
// 构建JOIN查询
query := r.GetDB(ctx).Table("api_calls ac").
Select("ac.*, p.name as product_name").
Joins("LEFT JOIN product p ON ac.product_id = p.id").
Where(whereCondition, whereArgs...)
// 获取总数
var count int64
err := query.Count(&count).Error
if err != nil {
return nil, nil, 0, err
}
total = count
// 应用排序和分页
if options.Sort != "" {
query = query.Order("ac." + options.Sort + " " + options.Order)
} else {
query = query.Order("ac.created_at DESC")
}
if options.Page > 0 && options.PageSize > 0 {
offset := (options.Page - 1) * options.PageSize
query = query.Offset(offset).Limit(options.PageSize)
}
// 执行查询
err = query.Find(&callsWithProduct).Error
if err != nil {
return nil, nil, 0, err
}
// 转换为entities.ApiCall并构建产品名称映射
var calls []*entities.ApiCall
productNameMap := make(map[string]string)
for _, c := range callsWithProduct {
call := c.ApiCall
calls = append(calls, &call)
// 构建产品ID到产品名称的映射
if c.ProductName != "" {
productNameMap[call.ID] = c.ProductName
}
}
return productNameMap, calls, total, nil
}