feat(knowledge-base): document list filters and explicit batch-management UX
Add three new optional filters to the document list under a knowledge base detail page — parse status, source/channel, and updated time range — and rework multi-select to no longer cause the card title to jitter on hover. Backend - Introduce types.KnowledgeListFilter to aggregate optional filter dimensions (tag, keyword, file_type, parse_status, source, updated_from/to) and switch ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept it instead of a growing positional parameter list. - The ListKnowledge HTTP handler accepts new parse_status, source, start_time and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type column to stay consistent with file_type semantics; other source values match the channel column. - Update the four other callers (agent_service, initialization) to pass an empty filter struct, preserving prior behavior. Frontend - Add three controls in the doc-filter-bar (status select, source select, date-range picker with future-date disabled) wired through getKnowled / listKnowledgeFiles into the new backend params. - Replace the hover-triggered card checkbox with an explicit "批量管理" mode (mirrors the session list UX): in card view the checkbox only renders while batch mode is on, entered via the per-card "..." menu; the list view keeps its leading checkbox column. Switching from list to grid auto-enables batch mode when something is already selected, so the selection stays visible. - DocumentBatchBar now stays open whenever batch mode or selection > 0, and its "取消选择" button both clears the selection and exits batch mode. API surface sync - Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml). - Update docs/api/knowledge.md with the new query parameters. - Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the Go SDK; the existing ListKnowledge keeps its signature. i18n - New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing menu.batchManage / batchManage.cancel for the multi-select strings.
This commit is contained in:
@@ -80,64 +80,73 @@ func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID(
|
||||
return knowledges, nil
|
||||
}
|
||||
|
||||
// applyKnowledgeListFilter applies the optional filter dimensions of
|
||||
// KnowledgeListFilter to a GORM query. Tenant / knowledge base scoping must be
|
||||
// applied by the caller before invoking this helper.
|
||||
func applyKnowledgeListFilter(query *gorm.DB, filter types.KnowledgeListFilter) *gorm.DB {
|
||||
if filter.TagID != "" {
|
||||
query = query.Where("tag_id = ?", filter.TagID)
|
||||
}
|
||||
if filter.Keyword != "" {
|
||||
escaped := escapeLikeKeyword(filter.Keyword)
|
||||
query = query.Where("(file_name LIKE ? OR title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
|
||||
}
|
||||
// FileType and Source share the same special-case routing onto `type` for
|
||||
// the "manual" / "url" values, so callers can pick either control.
|
||||
applyTypeOrFileType := func(q *gorm.DB, val string) *gorm.DB {
|
||||
switch val {
|
||||
case "":
|
||||
return q
|
||||
case "manual", "url":
|
||||
return q.Where("type = ?", val)
|
||||
default:
|
||||
return q.Where("file_type = ?", val)
|
||||
}
|
||||
}
|
||||
query = applyTypeOrFileType(query, filter.FileType)
|
||||
if filter.Source != "" {
|
||||
switch filter.Source {
|
||||
case "manual", "url":
|
||||
query = query.Where("type = ?", filter.Source)
|
||||
default:
|
||||
query = query.Where("channel = ?", filter.Source)
|
||||
}
|
||||
}
|
||||
if filter.ParseStatus != "" {
|
||||
query = query.Where("parse_status = ?", filter.ParseStatus)
|
||||
}
|
||||
if !filter.UpdatedFrom.IsZero() {
|
||||
query = query.Where("updated_at >= ?", filter.UpdatedFrom)
|
||||
}
|
||||
if !filter.UpdatedTo.IsZero() {
|
||||
query = query.Where("updated_at <= ?", filter.UpdatedTo)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination
|
||||
func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbID string,
|
||||
page *types.Pagination,
|
||||
tagID string,
|
||||
keyword string,
|
||||
fileType string,
|
||||
filter types.KnowledgeListFilter,
|
||||
) ([]*types.Knowledge, int64, error) {
|
||||
var knowledges []*types.Knowledge
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID)
|
||||
if tagID != "" {
|
||||
query = query.Where("tag_id = ?", tagID)
|
||||
}
|
||||
if keyword != "" {
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
query = query.Where("(file_name LIKE ? OR title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
|
||||
}
|
||||
if fileType != "" {
|
||||
if fileType == "manual" {
|
||||
query = query.Where("type = ?", "manual")
|
||||
} else if fileType == "url" {
|
||||
query = query.Where("type = ?", "url")
|
||||
} else {
|
||||
query = query.Where("file_type = ?", fileType)
|
||||
}
|
||||
scope := func(q *gorm.DB) *gorm.DB {
|
||||
return applyKnowledgeListFilter(
|
||||
q.Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID),
|
||||
filter,
|
||||
)
|
||||
}
|
||||
|
||||
// Query total count first
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
if err := scope(r.db.WithContext(ctx).Model(&types.Knowledge{})).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Then query paginated data
|
||||
dataQuery := r.db.Debug().WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID)
|
||||
if tagID != "" {
|
||||
dataQuery = dataQuery.Where("tag_id = ?", tagID)
|
||||
}
|
||||
if keyword != "" {
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
dataQuery = dataQuery.Where("(file_name LIKE ? OR title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
|
||||
}
|
||||
if fileType != "" {
|
||||
if fileType == "manual" {
|
||||
dataQuery = dataQuery.Where("type = ?", "manual")
|
||||
} else if fileType == "url" {
|
||||
dataQuery = dataQuery.Where("type = ?", "url")
|
||||
} else {
|
||||
dataQuery = dataQuery.Where("file_type = ?", fileType)
|
||||
}
|
||||
}
|
||||
|
||||
if err := dataQuery.
|
||||
if err := scope(r.db.WithContext(ctx)).
|
||||
Order("created_at DESC").
|
||||
Offset(page.Offset()).
|
||||
Limit(page.Limit()).
|
||||
|
||||
@@ -687,7 +687,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
|
||||
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 10,
|
||||
}, "", "", "")
|
||||
}, types.KnowledgeListFilter{})
|
||||
|
||||
if err == nil && pageResult != nil {
|
||||
docCount = int(pageResult.Total)
|
||||
|
||||
@@ -36,25 +36,25 @@ var (
|
||||
// knowledgeService implements the knowledge service interface
|
||||
// service 实现知识服务接口
|
||||
type knowledgeService struct {
|
||||
config *config.Config
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
repo interfaces.KnowledgeRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
tenantRepo interfaces.TenantRepository
|
||||
tenantService interfaces.TenantService
|
||||
documentReader interfaces.DocumentReader
|
||||
chunkService interfaces.ChunkService
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
tagService interfaces.KnowledgeTagService
|
||||
fileSvc interfaces.FileService
|
||||
modelService interfaces.ModelService
|
||||
task interfaces.TaskEnqueuer
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
redisClient *redis.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
imageResolver *docparser.ImageResolver
|
||||
taskPendingRepo interfaces.TaskPendingOpsRepository
|
||||
config *config.Config
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
repo interfaces.KnowledgeRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
tenantRepo interfaces.TenantRepository
|
||||
tenantService interfaces.TenantService
|
||||
documentReader interfaces.DocumentReader
|
||||
chunkService interfaces.ChunkService
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
tagService interfaces.KnowledgeTagService
|
||||
fileSvc interfaces.FileService
|
||||
modelService interfaces.ModelService
|
||||
task interfaces.TaskEnqueuer
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
redisClient *redis.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
imageResolver *docparser.ImageResolver
|
||||
taskPendingRepo interfaces.TaskPendingOpsRepository
|
||||
|
||||
// In-memory fallbacks for Lite mode (no Redis)
|
||||
memFAQProgress sync.Map // taskID -> *types.FAQImportProgress
|
||||
@@ -208,10 +208,10 @@ func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,
|
||||
|
||||
// ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge base
|
||||
func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context,
|
||||
kbID string, page *types.Pagination, tagID string, keyword string, fileType string,
|
||||
kbID string, page *types.Pagination, filter types.KnowledgeListFilter,
|
||||
) (*types.PageResult, error) {
|
||||
knowledges, total, err := s.repo.ListPagedKnowledgeByKnowledgeBaseID(ctx,
|
||||
ctx.Value(types.TenantIDContextKey).(uint64), kbID, page, tagID, keyword, fileType)
|
||||
ctx.Value(types.TenantIDContextKey).(uint64), kbID, page, filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -250,7 +250,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
|
||||
kbIdStr, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 1,
|
||||
}, "", "", "")
|
||||
}, types.KnowledgeListFilter{})
|
||||
if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
|
||||
logger.Error(ctx, "Cannot change embedding model when files exist")
|
||||
c.Error(errors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型"))
|
||||
@@ -363,7 +363,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
|
||||
}
|
||||
if oldProvider != provider {
|
||||
knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx,
|
||||
kbIdStr, &types.Pagination{Page: 1, PageSize: 1}, "", "", "")
|
||||
kbIdStr, &types.Pagination{Page: 1, PageSize: 1}, types.KnowledgeListFilter{})
|
||||
if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
|
||||
logger.Warn(ctx, "Storage engine changed with existing files, old files may become inaccessible")
|
||||
}
|
||||
@@ -1341,7 +1341,7 @@ func (h *InitializationHandler) GetCurrentConfigByKB(c *gin.Context) {
|
||||
kbIdStr, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 1,
|
||||
}, "", "", "")
|
||||
}, types.KnowledgeListFilter{})
|
||||
hasFiles := err == nil && knowledgeList != nil && knowledgeList.Total > 0
|
||||
|
||||
// 构建配置响应
|
||||
|
||||
@@ -538,9 +538,13 @@ func (h *KnowledgeHandler) GetKnowledge(c *gin.Context) {
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param page query int false "页码"
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Param tag_id query string false "标签ID筛选"
|
||||
// @Param keyword query string false "关键词搜索"
|
||||
// @Param file_type query string false "文件类型筛选"
|
||||
// @Param tag_id query string false "标签ID筛选"
|
||||
// @Param keyword query string false "关键词搜索"
|
||||
// @Param file_type query string false "文件类型筛选"
|
||||
// @Param parse_status query string false "解析状态筛选 (pending/processing/completed/failed)"
|
||||
// @Param source query string false "来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url 按 type 过滤)"
|
||||
// @Param start_time query string false "更新时间起点,RFC3339 格式"
|
||||
// @Param end_time query string false "更新时间终点,RFC3339 格式"
|
||||
// @Success 200 {object} map[string]interface{} "知识列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
@@ -569,24 +573,48 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
tagID := c.Query("tag_id")
|
||||
keyword := c.Query("keyword")
|
||||
fileType := c.Query("file_type")
|
||||
filter := types.KnowledgeListFilter{
|
||||
TagID: c.Query("tag_id"),
|
||||
Keyword: c.Query("keyword"),
|
||||
FileType: c.Query("file_type"),
|
||||
ParseStatus: c.Query("parse_status"),
|
||||
Source: c.Query("source"),
|
||||
}
|
||||
if raw := c.Query("start_time"); raw != "" {
|
||||
t, err := parseFilterTime(raw)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("invalid start_time: " + err.Error()))
|
||||
return
|
||||
}
|
||||
filter.UpdatedFrom = t
|
||||
}
|
||||
if raw := c.Query("end_time"); raw != "" {
|
||||
t, err := parseFilterTime(raw)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("invalid end_time: " + err.Error()))
|
||||
return
|
||||
}
|
||||
filter.UpdatedTo = t
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Retrieving knowledge list under knowledge base, knowledge base ID: %s, tag_id: %s, keyword: %s, file_type: %s, page: %d, page size: %d, effectiveTenantID: %d",
|
||||
"Retrieving knowledge list under knowledge base, kb_id=%s tag_id=%s keyword=%s file_type=%s parse_status=%s source=%s start_time=%s end_time=%s page=%d page_size=%d effectiveTenantID=%d",
|
||||
secutils.SanitizeForLog(kbID),
|
||||
secutils.SanitizeForLog(tagID),
|
||||
secutils.SanitizeForLog(keyword),
|
||||
secutils.SanitizeForLog(fileType),
|
||||
secutils.SanitizeForLog(filter.TagID),
|
||||
secutils.SanitizeForLog(filter.Keyword),
|
||||
secutils.SanitizeForLog(filter.FileType),
|
||||
secutils.SanitizeForLog(filter.ParseStatus),
|
||||
secutils.SanitizeForLog(filter.Source),
|
||||
secutils.SanitizeForLog(c.Query("start_time")),
|
||||
secutils.SanitizeForLog(c.Query("end_time")),
|
||||
pagination.Page,
|
||||
pagination.PageSize,
|
||||
effectiveTenantID,
|
||||
)
|
||||
|
||||
// Retrieve paginated knowledge entries
|
||||
result, err := h.kgService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &pagination, tagID, keyword, fileType)
|
||||
result, err := h.kgService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &pagination, filter)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
@@ -1796,6 +1824,26 @@ func resolveAgentAllowedKBIDs(agent *types.CustomAgent) []string {
|
||||
}
|
||||
}
|
||||
|
||||
// parseFilterTime parses a query-string timestamp accepted by knowledge list
|
||||
// filters. It supports RFC3339, RFC3339 with milliseconds, and the date-only
|
||||
// "2006-01-02" form (interpreted at start of day in the local timezone).
|
||||
func parseFilterTime(raw string) (time.Time, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
layouts := []string{time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05", "2006-01-02"}
|
||||
var lastErr error
|
||||
for _, layout := range layouts {
|
||||
if t, err := time.ParseInLocation(layout, raw, time.Local); err == nil {
|
||||
return t, nil
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
}
|
||||
return time.Time{}, lastErr
|
||||
}
|
||||
|
||||
func sliceContains(ss []string, target string) bool {
|
||||
for _, s := range ss {
|
||||
if s == target {
|
||||
|
||||
@@ -61,17 +61,15 @@ type KnowledgeService interface {
|
||||
GetKnowledgeBatchWithSharedAccess(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error)
|
||||
// ListKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base.
|
||||
ListKnowledgeByKnowledgeBaseID(ctx context.Context, kbID string) ([]*types.Knowledge, error)
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination.
|
||||
// When tagID is non-empty, results are filtered by tag_id.
|
||||
// When keyword is non-empty, results are filtered by file_name.
|
||||
// When fileType is non-empty, results are filtered by file_type or type.
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base
|
||||
// with pagination. The filter struct controls optional dimensions (tag, keyword,
|
||||
// file type, parse status, source channel, updated time range); pass a zero
|
||||
// struct to disable all filters.
|
||||
ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
page *types.Pagination,
|
||||
tagID string,
|
||||
keyword string,
|
||||
fileType string,
|
||||
filter types.KnowledgeListFilter,
|
||||
) (*types.PageResult, error)
|
||||
// DeleteKnowledge deletes knowledge by ID.
|
||||
DeleteKnowledge(ctx context.Context, id string) error
|
||||
@@ -178,12 +176,12 @@ type KnowledgeRepository interface {
|
||||
// GetKnowledgeByIDOnly returns knowledge by ID without tenant filter (for permission resolution).
|
||||
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
ListKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) ([]*types.Knowledge, error)
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination.
|
||||
// When tagID is non-empty, results are filtered by tag_id.
|
||||
// When keyword is non-empty, results are filtered by file_name.
|
||||
// When fileType is non-empty, results are filtered by file_type or type.
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base
|
||||
// with pagination. The filter struct controls optional dimensions (tag, keyword,
|
||||
// file type, parse status, source channel, updated time range); pass a zero
|
||||
// struct to disable all filters.
|
||||
ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context,
|
||||
tenantID uint64, kbID string, page *types.Pagination, tagID string, keyword string, fileType string,
|
||||
tenantID uint64, kbID string, page *types.Pagination, filter types.KnowledgeListFilter,
|
||||
) ([]*types.Knowledge, int64, error)
|
||||
UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
|
||||
// UpdateKnowledgeBatch updates knowledge items in batch
|
||||
|
||||
@@ -67,6 +67,27 @@ const (
|
||||
ManualKnowledgeStatusPublish = "publish"
|
||||
)
|
||||
|
||||
// KnowledgeListFilter aggregates optional filters for listing knowledge entries
|
||||
// under a knowledge base. Empty / zero fields mean "no filter on that dimension".
|
||||
type KnowledgeListFilter struct {
|
||||
// TagID filters by tag_id when non-empty.
|
||||
TagID string
|
||||
// Keyword performs a LIKE match on file_name / title when non-empty.
|
||||
Keyword string
|
||||
// FileType filters by file_type, or by type for the special values "manual" / "url".
|
||||
FileType string
|
||||
// ParseStatus filters by parse_status when non-empty (e.g. pending, processing, completed, failed).
|
||||
ParseStatus string
|
||||
// Source filters by ingestion channel when non-empty (web, api, feishu, notion, wechat, ...).
|
||||
// The special values "manual" and "url" are routed to the `type` column to match
|
||||
// FileType semantics, so callers can filter "manually created" / "URL imported" entries.
|
||||
Source string
|
||||
// UpdatedFrom, when non-zero, keeps rows with updated_at >= UpdatedFrom.
|
||||
UpdatedFrom time.Time
|
||||
// UpdatedTo, when non-zero, keeps rows with updated_at <= UpdatedTo.
|
||||
UpdatedTo time.Time
|
||||
}
|
||||
|
||||
// Knowledge represents a knowledge entity in the system.
|
||||
// It contains metadata about the knowledge source, its processing status,
|
||||
// and references to the physical file if applicable.
|
||||
|
||||
Reference in New Issue
Block a user