Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(faq): filter entries by enabled status (#3157)
langcaiye5db13a131e10
diff --git a/docs/api/faq.md b/docs/api/faq.mdindex 94b4db867..ab8bf4f26 100644--- a/docs/api/faq.md+++ b/docs/api/faq.md@@ -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'```**响应**:diff --git a/docs/docs.go b/docs/docs.goindex 6acaef496..25fb26052 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -4227,6 +4227,12 @@ const docTemplate = `{"description": "排序方式: asc(按更新时间正序), 默认按更新时间倒序","name": "sort_order","in": "query"+ },+ {+ "type": "boolean",+ "description": "启用状态筛选;不传时返回全部",+ "name": "is_enabled",+ "in": "query"}],"responses": {diff --git a/docs/plans/2026-09-10-faq-enabled-filter-design.md b/docs/plans/2026-09-10-faq-enabled-filter-design.mdnew file mode 100644index 000000000..537bd37ee--- /dev/null+++ b/docs/plans/2026-09-10-faq-enabled-filter-design.md@@ -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 测试、前端类型检查及差异检查。diff --git a/docs/swagger.json b/docs/swagger.jsonindex a363b5bf4..1f1c54b25 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -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"}}-}\ No newline at end of file+}diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex fa0537a4d..e47d06775 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -9137,6 +9137,10 @@ paths:in: queryname: sort_ordertype: string+ - description: 启用状态筛选;不传时返回全部+ in: query+ name: is_enabled+ type: booleanproduces:- application/jsonresponses:diff --git a/docs/swagger_contract_test.go b/docs/swagger_contract_test.goindex 75349c501..09161fa24 100644--- a/docs/swagger_contract_test.go+++ b/docs/swagger_contract_test.go@@ -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([]bytet.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:diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.tsindex d4f70c5fb..791e0da9c 100644--- a/frontend/src/api/knowledge-base/index.ts+++ b/frontend/src/api/knowledge-base/index.ts@@ -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}`);diff --git a/internal/application/repository/chunk_sqlite_test.go b/internal/application/repository/chunk_sqlite_test.goindex 104652729..89587055a 100644--- a/internal/application/repository/chunk_sqlite_test.go+++ b/internal/application/repository/chunk_sqlite_test.go@@ -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,diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex 181feee6a..a4dd94d9e 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -1206,7 +1206,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []stringpageResult, 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 {diff --git a/internal/application/service/knowledge_faq.go b/internal/application/service/knowledge_faq.goindex b935342a9..1331f6eff 100644--- a/internal/application/service/knowledge_faq.go+++ b/internal/application/service/knowledge_faq.go@@ -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, errdiff --git a/internal/handler/faq.go b/internal/handler/faq.goindex c31d3aff2..24f6bc257 100644--- a/internal/handler/faq.go+++ b/internal/handler/faq.go@@ -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),异步验证不实际导入。diff --git a/internal/handler/faq_enabled_filter_test.go b/internal/handler/faq_enabled_filter_test.gonew file mode 100644index 000000000..9074af7b7--- /dev/null+++ b/internal/handler/faq_enabled_filter_test.go@@ -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)+ }+}diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.goindex 7dcf240d6..88ceba3f5 100644--- a/internal/types/interfaces/knowledge.go+++ b/internal/types/interfaces/knowledge.go@@ -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.