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:
+54
-9
@@ -278,20 +278,65 @@ func (c *Client) GetKnowledgeBatch(ctx context.Context, knowledgeIDs []string) (
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// ListKnowledge lists knowledge entries in a knowledge base with pagination
|
||||
// ListKnowledge lists knowledge entries in a knowledge base with pagination.
|
||||
// For richer filtering (keyword, file type, parse status, source, time range)
|
||||
// use ListKnowledgeWithFilter.
|
||||
func (c *Client) ListKnowledge(ctx context.Context,
|
||||
knowledgeBaseID string,
|
||||
page int,
|
||||
pageSize int,
|
||||
tagID string,
|
||||
) ([]Knowledge, int64, error) {
|
||||
return c.ListKnowledgeWithFilter(ctx, knowledgeBaseID, page, pageSize, KnowledgeListFilter{TagID: tagID})
|
||||
}
|
||||
|
||||
// KnowledgeListFilter mirrors the server-side filters accepted by GET
|
||||
// /api/v1/knowledge-bases/{id}/knowledge. Empty / zero fields are omitted from
|
||||
// the request.
|
||||
type KnowledgeListFilter struct {
|
||||
TagID string
|
||||
Keyword string
|
||||
FileType string
|
||||
ParseStatus string
|
||||
Source string
|
||||
// StartTime / EndTime filter on knowledge updated_at. Zero values are skipped.
|
||||
// They are serialized in RFC3339 format.
|
||||
StartTime time.Time
|
||||
EndTime time.Time
|
||||
}
|
||||
|
||||
// ListKnowledgeWithFilter lists knowledge entries with the full filter surface.
|
||||
func (c *Client) ListKnowledgeWithFilter(ctx context.Context,
|
||||
knowledgeBaseID string,
|
||||
page int,
|
||||
pageSize int,
|
||||
filter KnowledgeListFilter,
|
||||
) ([]Knowledge, int64, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/knowledge", knowledgeBaseID)
|
||||
|
||||
queryParams := url.Values{}
|
||||
queryParams.Add("page", strconv.Itoa(page))
|
||||
queryParams.Add("page_size", strconv.Itoa(pageSize))
|
||||
if tagID != "" {
|
||||
queryParams.Add("tag_id", tagID)
|
||||
if filter.TagID != "" {
|
||||
queryParams.Add("tag_id", filter.TagID)
|
||||
}
|
||||
if filter.Keyword != "" {
|
||||
queryParams.Add("keyword", filter.Keyword)
|
||||
}
|
||||
if filter.FileType != "" {
|
||||
queryParams.Add("file_type", filter.FileType)
|
||||
}
|
||||
if filter.ParseStatus != "" {
|
||||
queryParams.Add("parse_status", filter.ParseStatus)
|
||||
}
|
||||
if filter.Source != "" {
|
||||
queryParams.Add("source", filter.Source)
|
||||
}
|
||||
if !filter.StartTime.IsZero() {
|
||||
queryParams.Add("start_time", filter.StartTime.Format(time.RFC3339))
|
||||
}
|
||||
if !filter.EndTime.IsZero() {
|
||||
queryParams.Add("end_time", filter.EndTime.Format(time.RFC3339))
|
||||
}
|
||||
|
||||
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, queryParams)
|
||||
@@ -439,8 +484,8 @@ func (c *Client) UpdateImageInfo(ctx context.Context,
|
||||
|
||||
// CreateManualKnowledgeRequest contains the parameters for creating a manual Markdown knowledge entry.
|
||||
type CreateManualKnowledgeRequest struct {
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
TagID string `json:"tag_id,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
}
|
||||
@@ -550,8 +595,8 @@ func (c *Client) MoveKnowledge(ctx context.Context, req *MoveKnowledgeRequest) (
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Data *MoveKnowledgeResponse `json:"data"`
|
||||
Success bool `json:"success"`
|
||||
Data *MoveKnowledgeResponse `json:"data"`
|
||||
}
|
||||
if err := parseResponse(resp, &result); err != nil {
|
||||
return nil, err
|
||||
@@ -579,8 +624,8 @@ func (c *Client) GetKnowledgeMoveProgress(ctx context.Context, taskID string) (*
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Data *KnowledgeMoveProgress `json:"data"`
|
||||
Success bool `json:"success"`
|
||||
Data *KnowledgeMoveProgress `json:"data"`
|
||||
}
|
||||
if err := parseResponse(resp, &result); err != nil {
|
||||
return nil, err
|
||||
|
||||
+11
-7
@@ -258,13 +258,17 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/knowle
|
||||
|
||||
**查询参数**:
|
||||
|
||||
| 字段 | 类型 | 默认 | 说明 |
|
||||
| ----------- | ------- | ---- | ----------------------------------- |
|
||||
| `page` | integer | 1 | 页码(从 1 开始) |
|
||||
| `page_size` | integer | 20 | 每页条数 |
|
||||
| `tag_id` | string | - | 按标签 ID 过滤 |
|
||||
| `keyword` | string | - | 按标题/内容关键词过滤 |
|
||||
| `file_type` | string | - | 按单个文件扩展名过滤(如 `pdf`) |
|
||||
| 字段 | 类型 | 默认 | 说明 |
|
||||
| -------------- | ------- | ---- | --------------------------------------------------------------------------------------------------- |
|
||||
| `page` | integer | 1 | 页码(从 1 开始) |
|
||||
| `page_size` | integer | 20 | 每页条数 |
|
||||
| `tag_id` | string | - | 按标签 ID 过滤 |
|
||||
| `keyword` | string | - | 按标题/内容关键词过滤 |
|
||||
| `file_type` | string | - | 按单个文件扩展名过滤(如 `pdf`);特殊值 `manual` / `url` 命中 `type` 列 |
|
||||
| `parse_status` | string | - | 按解析状态过滤:`pending` / `processing` / `completed` / `failed` |
|
||||
| `source` | string | - | 按来源/渠道过滤:`web` / `api` / `browser_extension` / `feishu` / `notion` / `yuque` / `wechat` 等; 特殊值 `manual` / `url` 命中 `type` 列 |
|
||||
| `start_time` | string | - | 更新时间起点,接受 RFC3339 (`2024-05-01T00:00:00+08:00`) 或 `YYYY-MM-DD HH:MM:SS` / `YYYY-MM-DD` |
|
||||
| `end_time` | string | - | 更新时间终点,格式同 `start_time` |
|
||||
|
||||
**请求**:
|
||||
|
||||
|
||||
+32
-2
@@ -5097,6 +5097,30 @@ const docTemplate = `{
|
||||
"description": "文件类型筛选",
|
||||
"name": "file_type",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "解析状态筛选 (pending/processing/completed/failed)",
|
||||
"name": "parse_status",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url 按 type 过滤)",
|
||||
"name": "source",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "更新时间起点,RFC3339 格式",
|
||||
"name": "start_time",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "更新时间终点,RFC3339 格式",
|
||||
"name": "end_time",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -15217,6 +15241,10 @@ const docTemplate = `{
|
||||
"description": "API key for the search provider (encrypted in DB)",
|
||||
"type": "string"
|
||||
},
|
||||
"base_url": {
|
||||
"description": "Base URL for self-hosted search engines (e.g. SearXNG instance URL).\nValidated with utils.ValidateURLForSSRF; private hosts must be added to SSRF_WHITELIST.",
|
||||
"type": "string"
|
||||
},
|
||||
"engine_id": {
|
||||
"description": "Google Custom Search Engine ID (only for Google provider)",
|
||||
"type": "string"
|
||||
@@ -15242,7 +15270,8 @@ const docTemplate = `{
|
||||
"duckduckgo",
|
||||
"tavily",
|
||||
"ollama",
|
||||
"baidu"
|
||||
"baidu",
|
||||
"searxng"
|
||||
],
|
||||
"x-enum-varnames": [
|
||||
"WebSearchProviderTypeBing",
|
||||
@@ -15250,7 +15279,8 @@ const docTemplate = `{
|
||||
"WebSearchProviderTypeDuckDuckGo",
|
||||
"WebSearchProviderTypeTavily",
|
||||
"WebSearchProviderTypeOllama",
|
||||
"WebSearchProviderTypeBaidu"
|
||||
"WebSearchProviderTypeBaidu",
|
||||
"WebSearchProviderTypeSearxng"
|
||||
]
|
||||
},
|
||||
"github_com_Tencent_WeKnora_internal_types.WikiConfig": {
|
||||
|
||||
+32
-2
@@ -5090,6 +5090,30 @@
|
||||
"description": "文件类型筛选",
|
||||
"name": "file_type",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "解析状态筛选 (pending/processing/completed/failed)",
|
||||
"name": "parse_status",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url 按 type 过滤)",
|
||||
"name": "source",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "更新时间起点,RFC3339 格式",
|
||||
"name": "start_time",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "更新时间终点,RFC3339 格式",
|
||||
"name": "end_time",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -15210,6 +15234,10 @@
|
||||
"description": "API key for the search provider (encrypted in DB)",
|
||||
"type": "string"
|
||||
},
|
||||
"base_url": {
|
||||
"description": "Base URL for self-hosted search engines (e.g. SearXNG instance URL).\nValidated with utils.ValidateURLForSSRF; private hosts must be added to SSRF_WHITELIST.",
|
||||
"type": "string"
|
||||
},
|
||||
"engine_id": {
|
||||
"description": "Google Custom Search Engine ID (only for Google provider)",
|
||||
"type": "string"
|
||||
@@ -15235,7 +15263,8 @@
|
||||
"duckduckgo",
|
||||
"tavily",
|
||||
"ollama",
|
||||
"baidu"
|
||||
"baidu",
|
||||
"searxng"
|
||||
],
|
||||
"x-enum-varnames": [
|
||||
"WebSearchProviderTypeBing",
|
||||
@@ -15243,7 +15272,8 @@
|
||||
"WebSearchProviderTypeDuckDuckGo",
|
||||
"WebSearchProviderTypeTavily",
|
||||
"WebSearchProviderTypeOllama",
|
||||
"WebSearchProviderTypeBaidu"
|
||||
"WebSearchProviderTypeBaidu",
|
||||
"WebSearchProviderTypeSearxng"
|
||||
]
|
||||
},
|
||||
"github_com_Tencent_WeKnora_internal_types.WikiConfig": {
|
||||
|
||||
@@ -2986,6 +2986,11 @@ definitions:
|
||||
api_key:
|
||||
description: API key for the search provider (encrypted in DB)
|
||||
type: string
|
||||
base_url:
|
||||
description: |-
|
||||
Base URL for self-hosted search engines (e.g. SearXNG instance URL).
|
||||
Validated with utils.ValidateURLForSSRF; private hosts must be added to SSRF_WHITELIST.
|
||||
type: string
|
||||
engine_id:
|
||||
description: Google Custom Search Engine ID (only for Google provider)
|
||||
type: string
|
||||
@@ -3008,6 +3013,7 @@ definitions:
|
||||
- tavily
|
||||
- ollama
|
||||
- baidu
|
||||
- searxng
|
||||
type: string
|
||||
x-enum-varnames:
|
||||
- WebSearchProviderTypeBing
|
||||
@@ -3016,6 +3022,7 @@ definitions:
|
||||
- WebSearchProviderTypeTavily
|
||||
- WebSearchProviderTypeOllama
|
||||
- WebSearchProviderTypeBaidu
|
||||
- WebSearchProviderTypeSearxng
|
||||
github_com_Tencent_WeKnora_internal_types.WikiConfig:
|
||||
properties:
|
||||
extraction_granularity:
|
||||
@@ -7478,6 +7485,23 @@ paths:
|
||||
in: query
|
||||
name: file_type
|
||||
type: string
|
||||
- description: 解析状态筛选 (pending/processing/completed/failed)
|
||||
in: query
|
||||
name: parse_status
|
||||
type: string
|
||||
- description: 来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url
|
||||
按 type 过滤)
|
||||
in: query
|
||||
name: source
|
||||
type: string
|
||||
- description: 更新时间起点,RFC3339 格式
|
||||
in: query
|
||||
name: start_time
|
||||
type: string
|
||||
- description: 更新时间终点,RFC3339 格式
|
||||
in: query
|
||||
name: end_time
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
|
||||
@@ -133,20 +133,28 @@ export function createManualKnowledge(kbId: string, data: { title: string; conte
|
||||
|
||||
export function listKnowledgeFiles(
|
||||
kbId: string,
|
||||
params: { page: number; page_size: number; tag_id?: string; keyword?: string; file_type?: string },
|
||||
params: {
|
||||
page: number;
|
||||
page_size: number;
|
||||
tag_id?: string;
|
||||
keyword?: string;
|
||||
file_type?: string;
|
||||
parse_status?: string;
|
||||
source?: string;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
},
|
||||
) {
|
||||
const query = new URLSearchParams();
|
||||
query.append('page', String(params.page));
|
||||
query.append('page_size', String(params.page_size));
|
||||
if (params.tag_id) {
|
||||
query.append('tag_id', params.tag_id);
|
||||
}
|
||||
if (params.keyword) {
|
||||
query.append('keyword', params.keyword);
|
||||
}
|
||||
if (params.file_type) {
|
||||
query.append('file_type', params.file_type);
|
||||
}
|
||||
if (params.tag_id) query.append('tag_id', params.tag_id);
|
||||
if (params.keyword) query.append('keyword', params.keyword);
|
||||
if (params.file_type) query.append('file_type', params.file_type);
|
||||
if (params.parse_status) query.append('parse_status', params.parse_status);
|
||||
if (params.source) query.append('source', params.source);
|
||||
if (params.start_time) query.append('start_time', params.start_time);
|
||||
if (params.end_time) query.append('end_time', params.end_time);
|
||||
const qs = query.toString();
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,17 @@ export default function (knowledgeBaseId?: string) {
|
||||
chunkLoadError: "",
|
||||
});
|
||||
const getKnowled = (
|
||||
query: { page: number; page_size: number; tag_id?: string; keyword?: string; file_type?: string } = { page: 1, page_size: 35 },
|
||||
query: {
|
||||
page: number;
|
||||
page_size: number;
|
||||
tag_id?: string;
|
||||
keyword?: string;
|
||||
file_type?: string;
|
||||
parse_status?: string;
|
||||
source?: string;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
} = { page: 1, page_size: 35 },
|
||||
kbId?: string,
|
||||
): Promise<void> => {
|
||||
const targetKbId = kbId || knowledgeBaseId;
|
||||
|
||||
@@ -315,6 +315,23 @@ export default {
|
||||
docSearchPlaceholder: 'Search document names...',
|
||||
fileTypeFilter: 'File Type',
|
||||
allFileTypes: 'All Types',
|
||||
parseStatusFilter: 'Status',
|
||||
allParseStatuses: 'All Statuses',
|
||||
parseStatusPending: 'Pending',
|
||||
parseStatusProcessing: 'Processing',
|
||||
parseStatusCompleted: 'Completed',
|
||||
parseStatusFailed: 'Failed',
|
||||
sourceFilter: 'Source',
|
||||
allSources: 'All Sources',
|
||||
sourceWeb: 'Web',
|
||||
sourceApi: 'API',
|
||||
sourceBrowserExtension: 'Browser Extension',
|
||||
sourceUpload: 'Upload',
|
||||
sourceUrl: 'URL Import',
|
||||
sourceManual: 'Manual',
|
||||
updatedTimeFilter: 'Updated',
|
||||
updatedTimeFrom: 'From',
|
||||
updatedTimeTo: 'To',
|
||||
noMatch: 'No matching knowledge base found',
|
||||
noKnowledge: 'No knowledge bases available',
|
||||
loadingFailed: 'Failed to load knowledge bases',
|
||||
|
||||
@@ -322,6 +322,23 @@ export default {
|
||||
docSearchPlaceholder: "문서 이름 검색...",
|
||||
fileTypeFilter: "파일 유형",
|
||||
allFileTypes: "모든 유형",
|
||||
parseStatusFilter: "상태",
|
||||
allParseStatuses: "모든 상태",
|
||||
parseStatusPending: "대기 중",
|
||||
parseStatusProcessing: "처리 중",
|
||||
parseStatusCompleted: "완료됨",
|
||||
parseStatusFailed: "실패",
|
||||
sourceFilter: "출처",
|
||||
allSources: "모든 출처",
|
||||
sourceWeb: "웹",
|
||||
sourceApi: "API",
|
||||
sourceBrowserExtension: "브라우저 확장",
|
||||
sourceUpload: "로컬 업로드",
|
||||
sourceUrl: "URL 가져오기",
|
||||
sourceManual: "수동 생성",
|
||||
updatedTimeFilter: "업데이트 시간",
|
||||
updatedTimeFrom: "시작",
|
||||
updatedTimeTo: "종료",
|
||||
noMatch: "일치하는 지식베이스를 찾을 수 없음",
|
||||
noKnowledge: "사용 가능한 지식베이스 없음",
|
||||
loadingFailed: "지식베이스 로드 실패",
|
||||
|
||||
@@ -286,6 +286,23 @@ export default {
|
||||
docSearchPlaceholder: 'Поиск документов...',
|
||||
fileTypeFilter: 'Тип файла',
|
||||
allFileTypes: 'Все типы',
|
||||
parseStatusFilter: 'Статус',
|
||||
allParseStatuses: 'Все статусы',
|
||||
parseStatusPending: 'Ожидание',
|
||||
parseStatusProcessing: 'Обработка',
|
||||
parseStatusCompleted: 'Завершено',
|
||||
parseStatusFailed: 'Ошибка',
|
||||
sourceFilter: 'Источник',
|
||||
allSources: 'Все источники',
|
||||
sourceWeb: 'Веб',
|
||||
sourceApi: 'API',
|
||||
sourceBrowserExtension: 'Расширение браузера',
|
||||
sourceUpload: 'Загрузка',
|
||||
sourceUrl: 'URL импорт',
|
||||
sourceManual: 'Создан вручную',
|
||||
updatedTimeFilter: 'Обновлено',
|
||||
updatedTimeFrom: 'С',
|
||||
updatedTimeTo: 'По',
|
||||
noMatch: 'Совпадающих баз знаний не найдено',
|
||||
noKnowledge: 'Нет доступных баз знаний',
|
||||
loadingFailed: 'Не удалось загрузить базы знаний',
|
||||
|
||||
@@ -319,6 +319,23 @@ export default {
|
||||
docSearchPlaceholder: "搜索文档名称...",
|
||||
fileTypeFilter: "文件类型",
|
||||
allFileTypes: "全部类型",
|
||||
parseStatusFilter: "解析状态",
|
||||
allParseStatuses: "全部状态",
|
||||
parseStatusPending: "等待中",
|
||||
parseStatusProcessing: "处理中",
|
||||
parseStatusCompleted: "已完成",
|
||||
parseStatusFailed: "失败",
|
||||
sourceFilter: "来源",
|
||||
allSources: "全部来源",
|
||||
sourceWeb: "网页",
|
||||
sourceApi: "API",
|
||||
sourceBrowserExtension: "浏览器扩展",
|
||||
sourceUpload: "本地上传",
|
||||
sourceUrl: "URL 导入",
|
||||
sourceManual: "手动创建",
|
||||
updatedTimeFilter: "更新时间",
|
||||
updatedTimeFrom: "起始时间",
|
||||
updatedTimeTo: "结束时间",
|
||||
noMatch: "未找到匹配的知识库",
|
||||
noKnowledge: "暂无可用知识库",
|
||||
loadingFailed: "加载知识库失败",
|
||||
|
||||
@@ -307,22 +307,65 @@ let docSearchDebounce: ReturnType<typeof setTimeout> | null = null;
|
||||
const docSearchKeyword = ref('');
|
||||
const selectedFileType = ref('');
|
||||
const fileTypeOptions = computed(() => [
|
||||
{ content: t('knowledgeBase.allFileTypes'), value: '' },
|
||||
{ content: 'PDF', value: 'pdf' },
|
||||
{ content: 'DOCX', value: 'docx' },
|
||||
{ content: 'DOC', value: 'doc' },
|
||||
{ content: 'PPTX', value: 'pptx' },
|
||||
{ content: 'PPT', value: 'ppt' },
|
||||
{ content: 'TXT', value: 'txt' },
|
||||
{ content: 'MD', value: 'md' },
|
||||
{ content: 'URL', value: 'url' },
|
||||
{ content: t('knowledgeBase.typeManual'), value: 'manual' },
|
||||
{ content: 'MP3', value: 'mp3' },
|
||||
{ content: 'WAV', value: 'wav' },
|
||||
{ content: 'M4A', value: 'm4a' },
|
||||
{ content: 'FLAC', value: 'flac' },
|
||||
{ content: 'OGG', value: 'ogg' },
|
||||
{ label: t('knowledgeBase.allFileTypes'), value: '' },
|
||||
{ label: 'PDF', value: 'pdf' },
|
||||
{ label: 'DOCX', value: 'docx' },
|
||||
{ label: 'DOC', value: 'doc' },
|
||||
{ label: 'PPTX', value: 'pptx' },
|
||||
{ label: 'PPT', value: 'ppt' },
|
||||
{ label: 'TXT', value: 'txt' },
|
||||
{ label: 'MD', value: 'md' },
|
||||
{ label: 'URL', value: 'url' },
|
||||
{ label: t('knowledgeBase.typeManual'), value: 'manual' },
|
||||
{ label: 'MP3', value: 'mp3' },
|
||||
{ label: 'WAV', value: 'wav' },
|
||||
{ label: 'M4A', value: 'm4a' },
|
||||
{ label: 'FLAC', value: 'flac' },
|
||||
{ label: 'OGG', value: 'ogg' },
|
||||
]);
|
||||
const selectedParseStatus = ref('');
|
||||
const parseStatusOptions = computed(() => [
|
||||
{ label: t('knowledgeBase.allParseStatuses'), value: '' },
|
||||
{ label: t('knowledgeBase.parseStatusPending'), value: 'pending' },
|
||||
{ label: t('knowledgeBase.parseStatusProcessing'), value: 'processing' },
|
||||
{ label: t('knowledgeBase.parseStatusCompleted'), value: 'completed' },
|
||||
{ label: t('knowledgeBase.parseStatusFailed'), value: 'failed' },
|
||||
]);
|
||||
const selectedSource = ref('');
|
||||
// Source filter combines ingestion channels and the "manual"/"url" virtual
|
||||
// sources that the backend routes onto the `type` column.
|
||||
const sourceOptions = computed(() => [
|
||||
{ label: t('knowledgeBase.allSources'), value: '' },
|
||||
{ label: t('knowledgeBase.sourceUpload'), value: 'web' },
|
||||
{ label: t('knowledgeBase.sourceUrl'), value: 'url' },
|
||||
{ label: t('knowledgeBase.sourceManual'), value: 'manual' },
|
||||
{ label: t('knowledgeBase.sourceApi'), value: 'api' },
|
||||
{ label: t('knowledgeBase.sourceBrowserExtension'), value: 'browser_extension' },
|
||||
{ label: t('knowledgeBase.channelFeishu'), value: 'feishu' },
|
||||
{ label: t('knowledgeBase.channelNotion'), value: 'notion' },
|
||||
{ label: t('knowledgeBase.channelYuque'), value: 'yuque' },
|
||||
{ label: t('knowledgeBase.channelWechat'), value: 'wechat' },
|
||||
{ label: t('knowledgeBase.channelWecom'), value: 'wecom' },
|
||||
{ label: t('knowledgeBase.channelDingtalk'), value: 'dingtalk' },
|
||||
{ label: t('knowledgeBase.channelSlack'), value: 'slack' },
|
||||
{ label: t('knowledgeBase.channelIm'), value: 'im' },
|
||||
]);
|
||||
// Date range as [start, end] in "YYYY-MM-DD" form (t-date-range-picker default).
|
||||
const updatedTimeRange = ref<string[]>([]);
|
||||
// Disable any date after today so users cannot filter into the future.
|
||||
const disableFutureDate = { after: new Date(new Date().setHours(23, 59, 59, 999)) };
|
||||
const filterParams = computed(() => {
|
||||
const [start, end] = updatedTimeRange.value || [];
|
||||
return {
|
||||
tag_id: selectedTagId.value || undefined,
|
||||
keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined,
|
||||
file_type: selectedFileType.value || undefined,
|
||||
parse_status: selectedParseStatus.value || undefined,
|
||||
source: selectedSource.value || undefined,
|
||||
start_time: start ? `${start} 00:00:00` : undefined,
|
||||
end_time: end ? `${end} 23:59:59` : undefined,
|
||||
};
|
||||
});
|
||||
type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>;
|
||||
const tagDropdownOptions = computed(() =>
|
||||
tagList.value.map((tag: any) => ({
|
||||
@@ -419,9 +462,7 @@ const loadKnowledgeFiles = (kbIdValue: string): Promise<void> => {
|
||||
{
|
||||
page: 1,
|
||||
page_size: pageSize,
|
||||
tag_id: selectedTagId.value || undefined,
|
||||
keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined,
|
||||
file_type: selectedFileType.value || undefined,
|
||||
...filterParams.value,
|
||||
},
|
||||
kbIdValue,
|
||||
);
|
||||
@@ -763,6 +804,14 @@ watch(selectedFileType, (newVal, oldVal) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 监听解析状态/来源/更新时间范围筛选变化(与文件类型行为一致)
|
||||
watch([selectedParseStatus, selectedSource, updatedTimeRange], () => {
|
||||
if (kbId.value) {
|
||||
page = 1;
|
||||
loadKnowledgeFiles(kbId.value);
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
// 监听文件上传事件
|
||||
const handleFileUploaded = (event: CustomEvent) => {
|
||||
const uploadedKbId = event.detail.kbId;
|
||||
@@ -1625,7 +1674,7 @@ const handleScroll = () => {
|
||||
if (scrollTop + clientHeight >= scrollHeight) {
|
||||
page++;
|
||||
if (cardList.value.length < total.value && page <= pageNum) {
|
||||
getKnowled({ page, page_size: pageSize, tag_id: selectedTagId.value, keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined, file_type: selectedFileType.value || undefined });
|
||||
getKnowled({ page, page_size: pageSize, ...filterParams.value });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1680,6 +1729,42 @@ const clearSelection = () => {
|
||||
lastSelectedIndex = -1;
|
||||
};
|
||||
|
||||
// Batch (multi-select) mode mirrors the session list's "批量管理" UX: while off,
|
||||
// no checkbox is rendered so the title doesn't jitter on hover; while on,
|
||||
// checkboxes are persistent and clicking a card toggles its selection.
|
||||
const batchMode = ref(false);
|
||||
const toggleBatchMode = () => {
|
||||
batchMode.value = !batchMode.value;
|
||||
if (!batchMode.value) clearSelection();
|
||||
};
|
||||
// "取消选择" / 退出批量管理:清空选择,并退出 grid 视图下的批量模式。
|
||||
const handleBatchCancel = () => {
|
||||
clearSelection();
|
||||
batchMode.value = false;
|
||||
};
|
||||
// 切到卡片视图时,如果列表视图里已经勾选过文档,需要自动开启批量管理模式,
|
||||
// 否则卡片视图默认不渲染 checkbox,会看不到勾选态。
|
||||
watch(viewMode, (mode) => {
|
||||
if (mode === 'grid' && selectedIds.value.size > 0) {
|
||||
batchMode.value = true;
|
||||
}
|
||||
});
|
||||
// Triggered from a card / row "..." menu — match the session-list UX where
|
||||
// the menu item simply opens batch mode (no auto-selection).
|
||||
const handleEnterBatchFromCard = (item: any) => {
|
||||
if (item) item.isMore = false;
|
||||
moreIndex.value = -1;
|
||||
clearSelection();
|
||||
batchMode.value = true;
|
||||
};
|
||||
const onCardClick = (item: any) => {
|
||||
if (batchMode.value) {
|
||||
onCardGridCheckboxChange(item.id, !selectedIds.value.has(item.id));
|
||||
} else {
|
||||
openCardDetails(item);
|
||||
}
|
||||
};
|
||||
|
||||
const openBatchDeleteDialog = () => {
|
||||
if (selectedIds.value.size === 0) return;
|
||||
batchDeleteDialog.value = true;
|
||||
@@ -1695,6 +1780,7 @@ const confirmBatchDelete = async () => {
|
||||
if (res?.success) {
|
||||
MessagePlugin.success(t('knowledgeBase.batchDeleteSuccess', { count: ids.length }));
|
||||
clearSelection();
|
||||
batchMode.value = false;
|
||||
batchDeleteDialog.value = false;
|
||||
page = 1;
|
||||
// 后端将批量删除放入异步队列,立刻拉列表仍可能包含待删项;短轮询直到列表与后端一致或超时
|
||||
@@ -1730,9 +1816,12 @@ const handleListAction = (
|
||||
};
|
||||
|
||||
// Clear selection on filter/tag/kb change to avoid acting on hidden items.
|
||||
watch([selectedTagId, docSearchKeyword, selectedFileType, kbId], () => {
|
||||
clearSelection();
|
||||
});
|
||||
watch(
|
||||
[selectedTagId, docSearchKeyword, selectedFileType, selectedParseStatus, selectedSource, updatedTimeRange, kbId],
|
||||
() => {
|
||||
clearSelection();
|
||||
},
|
||||
);
|
||||
|
||||
// After cardList reloads: stable keys rely on correct indices for shift-range; clamp anchor index.
|
||||
watch(cardList, () => {
|
||||
@@ -2130,6 +2219,28 @@ async function createNewSession(value: string): Promise<void> {
|
||||
class="doc-type-select"
|
||||
clearable
|
||||
/>
|
||||
<t-select
|
||||
v-model="selectedParseStatus"
|
||||
:options="parseStatusOptions"
|
||||
:placeholder="$t('knowledgeBase.parseStatusFilter')"
|
||||
class="doc-type-select"
|
||||
clearable
|
||||
/>
|
||||
<t-select
|
||||
v-model="selectedSource"
|
||||
:options="sourceOptions"
|
||||
:placeholder="$t('knowledgeBase.sourceFilter')"
|
||||
class="doc-type-select"
|
||||
clearable
|
||||
/>
|
||||
<t-date-range-picker
|
||||
v-model="updatedTimeRange"
|
||||
:placeholder="[$t('knowledgeBase.updatedTimeFrom'), $t('knowledgeBase.updatedTimeTo')]"
|
||||
:disable-date="disableFutureDate"
|
||||
class="doc-date-range"
|
||||
clearable
|
||||
allow-input
|
||||
/>
|
||||
<div class="doc-view-toggle" role="group" :aria-label="$t('knowledgeBase.viewModeToggle')">
|
||||
<t-tooltip :content="$t('knowledgeBase.viewModeGrid')" placement="top">
|
||||
<button
|
||||
@@ -2194,10 +2305,10 @@ async function createNewSession(value: string): Promise<void> {
|
||||
<!-- 现有文档卡片 -->
|
||||
<div
|
||||
class="knowledge-card"
|
||||
:class="{ 'is-selected': selectedIds.has(item.id), 'has-selection': selectedIds.size > 0 }"
|
||||
:class="{ 'is-selected': selectedIds.has(item.id), 'batch-mode': batchMode }"
|
||||
v-for="(item, index) in cardList"
|
||||
:key="item.id"
|
||||
@click="openCardDetails(item)"
|
||||
@click="onCardClick(item)"
|
||||
@mouseenter="onCardMouseEnter($event, item)"
|
||||
@mousemove="onCardMouseMove($event)"
|
||||
@mouseleave="onCardMouseLeave"
|
||||
@@ -2205,9 +2316,8 @@ async function createNewSession(value: string): Promise<void> {
|
||||
<div class="card-content">
|
||||
<div class="card-content-nav">
|
||||
<div
|
||||
v-if="canEdit"
|
||||
v-if="canEdit && batchMode"
|
||||
class="card-nav-check"
|
||||
:class="{ active: selectedIds.has(item.id) }"
|
||||
@click.stop
|
||||
>
|
||||
<t-checkbox
|
||||
@@ -2255,6 +2365,10 @@ async function createNewSession(value: string): Promise<void> {
|
||||
<t-icon class="icon" name="swap" />
|
||||
<span>{{ t('knowledgeBase.moveDocument') }}</span>
|
||||
</div>
|
||||
<div class="card-menu-item" @click.stop="handleEnterBatchFromCard(item)">
|
||||
<t-icon class="icon" name="queue" />
|
||||
<span>{{ t('menu.batchManage') }}</span>
|
||||
</div>
|
||||
<div class="card-menu-item danger" @click.stop="delCard(index, item)">
|
||||
<t-icon class="icon" name="delete" />
|
||||
<span>{{ t('knowledgeBase.deleteDocument') }}</span>
|
||||
@@ -2442,11 +2556,12 @@ async function createNewSession(value: string): Promise<void> {
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<div class="doc-batch-bar-anchor" v-show="selectedIds.size > 0">
|
||||
<div class="doc-batch-bar-anchor" v-show="batchMode || selectedIds.size > 0">
|
||||
<DocumentBatchBar
|
||||
:count="selectedIds.size"
|
||||
:loading="batchDeleting"
|
||||
@clear="clearSelection"
|
||||
:visible="batchMode || selectedIds.size > 0"
|
||||
@cancel="handleBatchCancel"
|
||||
@delete="openBatchDeleteDialog"
|
||||
/>
|
||||
</div>
|
||||
@@ -3063,10 +3178,11 @@ async function createNewSession(value: string): Promise<void> {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.doc-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
flex: 1 1 220px;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.doc-type-select {
|
||||
@@ -3074,6 +3190,18 @@ async function createNewSession(value: string): Promise<void> {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.doc-date-range {
|
||||
width: 280px;
|
||||
flex-shrink: 0;
|
||||
|
||||
// TDesign focuses both the outer popup reference and inner inputs, which
|
||||
// visually stacks into a "double border" — drop the inner shadow.
|
||||
:deep(.t-input--focused),
|
||||
:deep(.t-is-focused) {
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.doc-view-toggle {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
@@ -3854,26 +3982,17 @@ async function createNewSession(value: string): Promise<void> {
|
||||
cursor: pointer;
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
|
||||
|
||||
/* 默认折叠不占位,悬停/多选/已选时展开,避免非选择态左侧错位 */
|
||||
/* 仅在批量管理模式下渲染 checkbox,常态下不占位,避免标题在 hover 时右滑 */
|
||||
.card-nav-check {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 0;
|
||||
width: 22px;
|
||||
height: 29px;
|
||||
margin-right: 0;
|
||||
opacity: 0;
|
||||
overflow: hidden;
|
||||
transition: width 0.2s ease, margin-right 0.2s ease, opacity 0.2s ease;
|
||||
margin-right: 8px;
|
||||
cursor: pointer;
|
||||
|
||||
&.active {
|
||||
width: 22px;
|
||||
margin-right: 8px;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.card-select-checkbox {
|
||||
margin: 0;
|
||||
line-height: 0;
|
||||
@@ -3900,13 +4019,6 @@ async function createNewSession(value: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .card-nav-check,
|
||||
&.has-selection .card-nav-check {
|
||||
width: 22px;
|
||||
margin-right: 8px;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.card-content {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -4,10 +4,13 @@ import { useI18n } from 'vue-i18n';
|
||||
defineProps<{
|
||||
count: number;
|
||||
loading?: boolean;
|
||||
// When true the bar stays visible even with 0 selections, so users can exit
|
||||
// batch mode from here without selecting anything first.
|
||||
visible?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'clear'): void;
|
||||
(e: 'cancel'): void;
|
||||
(e: 'delete'): void;
|
||||
}>();
|
||||
|
||||
@@ -16,11 +19,22 @@ const { t } = useI18n();
|
||||
|
||||
<template>
|
||||
<transition name="batch-bar-fade">
|
||||
<div v-if="count > 0" class="doc-batch-bar" role="region" :aria-label="t('knowledgeBase.selectedCount', { count })">
|
||||
<div
|
||||
v-if="visible || count > 0"
|
||||
class="doc-batch-bar"
|
||||
role="region"
|
||||
:aria-label="t('knowledgeBase.selectedCount', { count })"
|
||||
>
|
||||
<div class="batch-bar-inner">
|
||||
<div class="batch-bar-left">
|
||||
<span class="batch-bar-count">{{ t('knowledgeBase.selectedCount', { count }) }}</span>
|
||||
<t-button variant="text" theme="default" size="small" class="batch-bar-clear" @click="emit('clear')">
|
||||
<t-button
|
||||
variant="text"
|
||||
theme="default"
|
||||
size="small"
|
||||
class="batch-bar-clear"
|
||||
@click="emit('cancel')"
|
||||
>
|
||||
{{ t('knowledgeBase.clearSelection') }}
|
||||
</t-button>
|
||||
</div>
|
||||
@@ -29,6 +43,7 @@ const { t } = useI18n();
|
||||
theme="danger"
|
||||
variant="outline"
|
||||
size="small"
|
||||
:disabled="count === 0"
|
||||
:loading="loading"
|
||||
@click="emit('delete')"
|
||||
>
|
||||
|
||||
@@ -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