feat(faq): filter entries by enabled status (#3157)
* docs: design FAQ enabled-status filter * feat(faq): filter entries by enabled status * test(faq): cover disabled list filtering * docs(faq): publish enabled filter contractmain
parent
80c7b2f2bd
commit
5db13a131e
|
|
@ -27,7 +27,7 @@ FAQ 接口分为两组:
|
|||
|
||||
## GET `/knowledge-bases/:id/faq/entries` - 获取 FAQ 条目列表
|
||||
|
||||
支持分页、按标签过滤、关键字搜索与排序。
|
||||
支持分页、按标签、启用状态过滤、关键字搜索与排序。
|
||||
|
||||
**查询参数**:
|
||||
|
||||
|
|
@ -39,6 +39,7 @@ FAQ 接口分为两组:
|
|||
| keyword | string | 否 | 关键字搜索 |
|
||||
| search_field | string | 否 | 搜索字段:`standard_question` / `similar_questions` / `answers`,留空则全字段搜索 |
|
||||
| sort_order | string | 否 | 排序方式,`asc` 表示按更新时间正序,默认按更新时间倒序 |
|
||||
| is_enabled | bool | 否 | 启用状态;`true` 仅返回已启用条目,`false` 仅返回未启用条目,不传时返回全部 |
|
||||
|
||||
**请求**:
|
||||
|
||||
|
|
@ -50,6 +51,10 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/en
|
|||
# 仅搜索标准问
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries?keyword=密码&search_field=standard_question' \
|
||||
--header 'X-API-Key: sk-xxxxx'
|
||||
|
||||
# 仅查看未启用条目
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries?is_enabled=false' \
|
||||
--header 'X-API-Key: sk-xxxxx'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
|
|
|||
|
|
@ -4227,6 +4227,12 @@ const docTemplate = `{
|
|||
"description": "排序方式: asc(按更新时间正序), 默认按更新时间倒序",
|
||||
"name": "sort_order",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "启用状态筛选;不传时返回全部",
|
||||
"name": "is_enabled",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
# FAQ 条目启用状态筛选设计
|
||||
|
||||
## 背景
|
||||
|
||||
FAQ 条目管理接口支持分页、标签、关键词和排序,但不能按 `is_enabled` 筛选。前端在分页结果返回后过滤会导致当前页数据和总数不准确。
|
||||
|
||||
## 接口
|
||||
|
||||
`GET /api/v1/knowledge-bases/{id}/faq/entries` 增加可选查询参数 `is_enabled`:
|
||||
|
||||
- 不传:返回全部条目,保持现有行为。
|
||||
- `true`:只返回已启用条目。
|
||||
- `false`:只返回未启用条目。
|
||||
- 其他值:返回 `400 Bad Request`。
|
||||
|
||||
## 实现
|
||||
|
||||
Handler 区分参数缺失与布尔值,Service 将 `*bool` 传给已有的 Repository 查询。Repository 已在统计总数和分页数据查询中应用该条件,不需要数据库变更。
|
||||
|
||||
前端 API 参数类型补充 `is_enabled?: boolean`,本次不增加界面控件。Go 客户端保留现有方法签名,避免破坏调用方。
|
||||
|
||||
## 测试
|
||||
|
||||
补充查询参数解析测试,覆盖未传、`true`、`false` 和非法值;执行相关 Go 测试、前端类型检查及差异检查。
|
||||
|
|
@ -4220,6 +4220,12 @@
|
|||
"description": "排序方式: asc(按更新时间正序), 默认按更新时间倒序",
|
||||
"name": "sort_order",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "启用状态筛选;不传时返回全部",
|
||||
"name": "is_enabled",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
|
|
@ -25604,4 +25610,4 @@
|
|||
"in": "header"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9137,6 +9137,10 @@ paths:
|
|||
in: query
|
||||
name: sort_order
|
||||
type: string
|
||||
- description: 启用状态筛选;不传时返回全部
|
||||
in: query
|
||||
name: is_enabled
|
||||
type: boolean
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
|
|
|
|||
|
|
@ -15,6 +15,17 @@ type swaggerDocumentCase struct {
|
|||
parse func([]byte, any) error
|
||||
}
|
||||
|
||||
type swaggerParameter struct {
|
||||
Name string `json:"name" yaml:"name"`
|
||||
In string `json:"in" yaml:"in"`
|
||||
Type string `json:"type" yaml:"type"`
|
||||
Required bool `json:"required" yaml:"required"`
|
||||
}
|
||||
|
||||
type swaggerOperation struct {
|
||||
Parameters []swaggerParameter `json:"parameters" yaml:"parameters"`
|
||||
}
|
||||
|
||||
func swaggerDocuments() []swaggerDocumentCase {
|
||||
return []swaggerDocumentCase{
|
||||
{
|
||||
|
|
@ -60,6 +71,14 @@ func TestModelDeleteUsageContract(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestFAQEnabledFilterContract(t *testing.T) {
|
||||
for _, tt := range swaggerDocuments() {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assertFAQEnabledFilterContract(t, tt.loadSpec(t), tt.parse)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func readSwaggerFile(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(name)
|
||||
|
|
@ -141,6 +160,35 @@ func assertModelDeleteUsageContract(t *testing.T, data []byte, parse func([]byte
|
|||
t.Fatal("generated Swagger ErrorCode enum does not include model-in-use code 2300")
|
||||
}
|
||||
|
||||
func assertFAQEnabledFilterContract(t *testing.T, data []byte, parse func([]byte, any) error) {
|
||||
t.Helper()
|
||||
var spec struct {
|
||||
Paths map[string]map[string]swaggerOperation `json:"paths" yaml:"paths"`
|
||||
}
|
||||
if err := parse(data, &spec); err != nil {
|
||||
t.Fatalf("parse generated Swagger document: %v", err)
|
||||
}
|
||||
|
||||
faqEntries, ok := spec.Paths["/knowledge-bases/{id}/faq/entries"]
|
||||
if !ok {
|
||||
t.Fatal("generated Swagger document does not expose FAQ entries route")
|
||||
}
|
||||
getOperation, ok := faqEntries["get"]
|
||||
if !ok {
|
||||
t.Fatal("generated Swagger document does not expose GET FAQ entries")
|
||||
}
|
||||
for _, parameter := range getOperation.Parameters {
|
||||
if parameter.Name != "is_enabled" {
|
||||
continue
|
||||
}
|
||||
if parameter.In != "query" || parameter.Type != "boolean" || parameter.Required {
|
||||
t.Fatalf("is_enabled must be an optional boolean query parameter, got %#v", parameter)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatal("GET FAQ entries does not document the is_enabled query parameter")
|
||||
}
|
||||
|
||||
func swaggerInteger(value any) int {
|
||||
switch number := value.(type) {
|
||||
case int:
|
||||
|
|
|
|||
|
|
@ -500,7 +500,14 @@ const buildQuery = (params?: Record<string, any>) => {
|
|||
|
||||
export function listFAQEntries(
|
||||
kbId: string,
|
||||
params?: { page?: number; page_size?: number; tag_id?: number; tag_ids?: string; keyword?: string },
|
||||
params?: {
|
||||
page?: number
|
||||
page_size?: number
|
||||
tag_id?: number
|
||||
tag_ids?: string
|
||||
keyword?: string
|
||||
is_enabled?: boolean
|
||||
},
|
||||
) {
|
||||
const query = buildQuery(params);
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/faq/entries${query}`);
|
||||
|
|
|
|||
|
|
@ -258,6 +258,16 @@ func TestListPagedChunksByKnowledgeID_FiltersEnabledState(t *testing.T) {
|
|||
require.Len(t, chunks, 1)
|
||||
assert.Equal(t, enabledChunk.ID, chunks[0].ID)
|
||||
|
||||
disabled := false
|
||||
chunks, total, err = repo.ListPagedChunksByKnowledgeID(
|
||||
ctx, 1, "faq-knowledge", &types.Pagination{Page: 1, PageSize: 20},
|
||||
[]types.ChunkType{types.ChunkTypeFAQ}, nil, "", "", "", types.KnowledgeTypeFAQ, &disabled,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), total)
|
||||
require.Len(t, chunks, 1)
|
||||
assert.Equal(t, disabledChunk.ID, chunks[0].ID)
|
||||
|
||||
allChunks, allTotal, err := repo.ListPagedChunksByKnowledgeID(
|
||||
ctx, 1, "faq-knowledge", &types.Pagination{Page: 1, PageSize: 20},
|
||||
[]types.ChunkType{types.ChunkTypeFAQ}, nil, "", "", "", types.KnowledgeTypeFAQ, nil,
|
||||
|
|
|
|||
|
|
@ -1206,7 +1206,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
|
|||
pageResult, err := s.knowledgeService.ListFAQEntries(metaCtx, kbID, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 10,
|
||||
}, nil, 0, "", "", "")
|
||||
}, nil, 0, "", "", "", nil)
|
||||
if err == nil && pageResult != nil {
|
||||
docCount = int(pageResult.Total)
|
||||
if entries, ok := pageResult.Data.([]*types.FAQEntry); ok {
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import (
|
|||
// ListFAQEntries lists FAQ entries under a FAQ knowledge base.
|
||||
func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
||||
kbID string, page *types.Pagination, tagUUIDs []string, legacyTagSeqID int64, keyword string, searchField string, sortOrder string,
|
||||
isEnabled *bool,
|
||||
) (*types.PageResult, error) {
|
||||
if page == nil {
|
||||
page = &types.Pagination{}
|
||||
|
|
@ -56,7 +57,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
|||
chunkType := []types.ChunkType{types.ChunkTypeFAQ}
|
||||
chunks, total, err := s.chunkRepo.ListPagedChunksByKnowledgeID(
|
||||
ctx, effectiveTenantID, faqKnowledge.ID, page, chunkType, tagUUIDs, keyword, searchField, sortOrder, types.KnowledgeTypeFAQ,
|
||||
nil,
|
||||
isEnabled,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ type updateLastFAQImportResultDisplayStatusRequest struct {
|
|||
// @Param keyword query string false "关键词搜索"
|
||||
// @Param search_field query string false "搜索字段: standard_question(标准问题), similar_questions(相似问法), answers(答案), 默认搜索全部"
|
||||
// @Param sort_order query string false "排序方式: asc(按更新时间正序), 默认按更新时间倒序"
|
||||
// @Param is_enabled query bool false "启用状态筛选;不传时返回全部"
|
||||
// @Success 200 {object} map[string]interface{} "FAQ列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
|
|
@ -102,8 +103,13 @@ func (h *FAQHandler) ListEntries(c *gin.Context) {
|
|||
keyword := secutils.SanitizeForLog(c.Query("keyword"))
|
||||
searchField := secutils.SanitizeForLog(c.Query("search_field"))
|
||||
sortOrder := secutils.SanitizeForLog(c.Query("sort_order"))
|
||||
isEnabled, err := parseOptionalFAQEnabled(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.knowledgeService.ListFAQEntries(ctx, kbID, &page, tagUUIDs, legacyTagSeqID, keyword, searchField, sortOrder)
|
||||
result, err := h.knowledgeService.ListFAQEntries(ctx, kbID, &page, tagUUIDs, legacyTagSeqID, keyword, searchField, sortOrder, isEnabled)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
|
|
@ -116,6 +122,26 @@ func (h *FAQHandler) ListEntries(c *gin.Context) {
|
|||
})
|
||||
}
|
||||
|
||||
// parseOptionalFAQEnabled preserves the distinction between an omitted filter
|
||||
// and an explicit false value so the management endpoint remains backward compatible.
|
||||
func parseOptionalFAQEnabled(c *gin.Context) (*bool, error) {
|
||||
raw, exists := c.GetQuery("is_enabled")
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var value bool
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "true":
|
||||
value = true
|
||||
case "false":
|
||||
value = false
|
||||
default:
|
||||
return nil, errors.NewBadRequestError("is_enabled must be true or false")
|
||||
}
|
||||
return &value, nil
|
||||
}
|
||||
|
||||
// UpsertEntries godoc
|
||||
// @Summary 批量更新/插入FAQ条目
|
||||
// @Description 异步批量更新或插入FAQ条目。支持 dry_run 模式(设置 dry_run=true),异步验证不实际导入。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,137 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type faqListKnowledgeServiceStub struct {
|
||||
interfaces.KnowledgeService
|
||||
callCount int
|
||||
isEnabled *bool
|
||||
}
|
||||
|
||||
func (s *faqListKnowledgeServiceStub) ListFAQEntries(
|
||||
_ context.Context,
|
||||
_ string,
|
||||
page *types.Pagination,
|
||||
_ []string,
|
||||
_ int64,
|
||||
_ string,
|
||||
_ string,
|
||||
_ string,
|
||||
isEnabled *bool,
|
||||
) (*types.PageResult, error) {
|
||||
s.callCount++
|
||||
s.isEnabled = isEnabled
|
||||
return types.NewPageResult(0, page, []*types.FAQEntry{}), nil
|
||||
}
|
||||
|
||||
func TestParseOptionalFAQEnabled(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
want bool
|
||||
wantValue bool
|
||||
wantError bool
|
||||
}{
|
||||
{name: "omitted"},
|
||||
{name: "enabled", query: "?is_enabled=true", want: true, wantValue: true},
|
||||
{name: "disabled", query: "?is_enabled=false", want: true},
|
||||
{name: "case insensitive", query: "?is_enabled=TRUE", want: true, wantValue: true},
|
||||
{name: "invalid", query: "?is_enabled=invalid", wantError: true},
|
||||
{name: "numeric", query: "?is_enabled=1", wantError: true},
|
||||
{name: "empty", query: "?is_enabled=", wantError: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
context, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
context.Request = httptest.NewRequest("GET", "/faq/entries"+tt.query, nil)
|
||||
|
||||
value, err := parseOptionalFAQEnabled(context)
|
||||
if (err != nil) != tt.wantError {
|
||||
t.Fatalf("error = %v, wantError %v", err, tt.wantError)
|
||||
}
|
||||
if tt.wantError {
|
||||
return
|
||||
}
|
||||
if (value != nil) != tt.want {
|
||||
t.Fatalf("value presence = %v, want %v", value != nil, tt.want)
|
||||
}
|
||||
if value != nil && *value != tt.wantValue {
|
||||
t.Fatalf("value = %v, want %v", *value, tt.wantValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFAQListEntriesPassesEnabledFilter(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
want bool
|
||||
wantValue bool
|
||||
}{
|
||||
{name: "all entries"},
|
||||
{name: "enabled entries", query: "?is_enabled=true", want: true, wantValue: true},
|
||||
{name: "disabled entries", query: "?is_enabled=false", want: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
service := &faqListKnowledgeServiceStub{}
|
||||
handler := &FAQHandler{knowledgeService: service}
|
||||
context, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
context.Params = gin.Params{{Key: "id", Value: "kb-1"}}
|
||||
context.Request = httptest.NewRequest("GET", "/faq/entries"+tt.query, nil)
|
||||
|
||||
handler.ListEntries(context)
|
||||
|
||||
if len(context.Errors) != 0 {
|
||||
t.Fatalf("unexpected errors: %v", context.Errors)
|
||||
}
|
||||
if service.callCount != 1 {
|
||||
t.Fatalf("service call count = %d, want 1", service.callCount)
|
||||
}
|
||||
if (service.isEnabled != nil) != tt.want {
|
||||
t.Fatalf("filter presence = %v, want %v", service.isEnabled != nil, tt.want)
|
||||
}
|
||||
if service.isEnabled != nil && *service.isEnabled != tt.wantValue {
|
||||
t.Fatalf("filter = %v, want %v", *service.isEnabled, tt.wantValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFAQListEntriesRejectsInvalidEnabledFilter(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
service := &faqListKnowledgeServiceStub{}
|
||||
handler := &FAQHandler{knowledgeService: service}
|
||||
router := gin.New()
|
||||
router.Use(middleware.ErrorHandler())
|
||||
router.GET("/knowledge-bases/:id/faq/entries", handler.ListEntries)
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest("GET", "/knowledge-bases/kb-1/faq/entries?is_enabled=invalid", nil)
|
||||
|
||||
router.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusBadRequest)
|
||||
}
|
||||
if service.callCount != 0 {
|
||||
t.Fatalf("service call count = %d, want 0", service.callCount)
|
||||
}
|
||||
}
|
||||
|
|
@ -153,6 +153,7 @@ type KnowledgeService interface {
|
|||
keyword string,
|
||||
searchField string,
|
||||
sortOrder string,
|
||||
isEnabled *bool,
|
||||
) (*types.PageResult, error)
|
||||
// UpsertFAQEntries imports or appends FAQ entries asynchronously.
|
||||
// When DryRun is true, only validates entries without actually importing.
|
||||
|
|
|
|||
Loading…
Reference in New Issue