feat: add configurable sorting to document and resource lists (#3318)
* feat: add configurable sorting to document and resource lists * fix: use typography tokens in sort controls * fix: satisfy sorting lint checksmain
parent
402729341a
commit
ad20ea9c9b
|
|
@ -1,6 +1,9 @@
|
|||
import { get, post, put, del, postUpload, getDown } from "../../utils/request";
|
||||
import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess';
|
||||
import type { AuditLog, AuditOutcome, ListAuditLogResponse } from '@/api/tenant/audit-log';
|
||||
import { buildListKnowledgeFilesQuery } from './knowledgeFileListQuery';
|
||||
|
||||
export { buildListKnowledgeFilesQuery } from './knowledgeFileListQuery';
|
||||
|
||||
export type KnowledgeBaseActivity = AuditLog;
|
||||
|
||||
|
|
@ -299,44 +302,31 @@ export function createManualKnowledge(
|
|||
return post(`/api/v1/knowledge-bases/${kbId}/knowledge/manual`, data);
|
||||
}
|
||||
|
||||
export function listKnowledgeFiles(
|
||||
kbId: string,
|
||||
params: {
|
||||
page: number;
|
||||
page_size: number;
|
||||
tag_ids?: string;
|
||||
keyword?: string;
|
||||
file_type?: string;
|
||||
parse_status?: string;
|
||||
source?: string;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
/**
|
||||
* Folder to browse. An empty string means the knowledge base root, so the
|
||||
* parameter is only sent when it is defined — leaving it out lists every
|
||||
* folder (the flat view).
|
||||
*/
|
||||
folder_path?: string;
|
||||
/** Include documents stored in sub-folders of folder_path. */
|
||||
folder_recursive?: boolean;
|
||||
},
|
||||
) {
|
||||
const query = new URLSearchParams();
|
||||
query.append('page', String(params.page));
|
||||
query.append('page_size', String(params.page_size));
|
||||
if (params.tag_ids) query.append('tag_ids', params.tag_ids);
|
||||
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);
|
||||
if (params.folder_path !== undefined) {
|
||||
query.append('folder_path', params.folder_path);
|
||||
if (params.folder_recursive) query.append('folder_recursive', 'true');
|
||||
}
|
||||
const qs = query.toString();
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`);
|
||||
export type KnowledgeListSortField = 'updated_at' | 'created_at' | 'file_name';
|
||||
export type KnowledgeListSortOrder = 'asc' | 'desc';
|
||||
|
||||
export interface ListKnowledgeFilesParams {
|
||||
page: number;
|
||||
page_size: number;
|
||||
tag_ids?: string;
|
||||
keyword?: string;
|
||||
file_type?: string;
|
||||
parse_status?: string;
|
||||
source?: string;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
sort_by?: KnowledgeListSortField;
|
||||
sort_order?: KnowledgeListSortOrder;
|
||||
/**
|
||||
* 当前浏览的目录。空字符串表示知识库根目录;未定义时不按目录筛选。
|
||||
*/
|
||||
folder_path?: string;
|
||||
/** 是否同时包含 folder_path 下所有子目录中的文档。 */
|
||||
folder_recursive?: boolean;
|
||||
}
|
||||
|
||||
export function listKnowledgeFiles(kbId: string, params: ListKnowledgeFilesParams) {
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${buildListKnowledgeFilesQuery(params)}`);
|
||||
}
|
||||
|
||||
/** One node of the knowledge base folder tree. */
|
||||
|
|
|
|||
|
|
@ -0,0 +1,20 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { buildListKnowledgeFilesQuery } from './knowledgeFileListQuery';
|
||||
|
||||
test('知识文件列表请求会传递排序字段和方向', () => {
|
||||
const query = new URLSearchParams(buildListKnowledgeFilesQuery({
|
||||
page: 2,
|
||||
page_size: 35,
|
||||
sort_by: 'file_name',
|
||||
sort_order: 'asc',
|
||||
folder_path: '',
|
||||
}));
|
||||
|
||||
assert.equal(query.get('page'), '2');
|
||||
assert.equal(query.get('page_size'), '35');
|
||||
assert.equal(query.get('sort_by'), 'file_name');
|
||||
assert.equal(query.get('sort_order'), 'asc');
|
||||
assert.equal(query.get('folder_path'), '');
|
||||
});
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import type { ListKnowledgeFilesParams } from './index';
|
||||
|
||||
export function buildListKnowledgeFilesQuery(params: ListKnowledgeFilesParams): string {
|
||||
const query = new URLSearchParams();
|
||||
query.append('page', String(params.page));
|
||||
query.append('page_size', String(params.page_size));
|
||||
if (params.tag_ids) query.append('tag_ids', params.tag_ids);
|
||||
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);
|
||||
if (params.sort_by) query.append('sort_by', params.sort_by);
|
||||
if (params.sort_order) query.append('sort_order', params.sort_order);
|
||||
if (params.folder_path !== undefined) {
|
||||
query.append('folder_path', params.folder_path);
|
||||
if (params.folder_recursive) query.append('folder_recursive', 'true');
|
||||
}
|
||||
return query.toString();
|
||||
}
|
||||
|
|
@ -89,6 +89,8 @@ export interface SharedKnowledgeBase {
|
|||
type: string
|
||||
knowledge_count?: number
|
||||
chunk_count?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
share_id: string
|
||||
organization_id: string
|
||||
|
|
|
|||
|
|
@ -0,0 +1,188 @@
|
|||
<template>
|
||||
<t-popup v-model:visible="panelVisible" trigger="click" placement="bottom-right"
|
||||
overlay-class-name="resource-sort-popup" :overlay-inner-style="{ padding: 0 }">
|
||||
<template #content>
|
||||
<div class="resource-sort-panel" role="menu" :aria-label="t('resourceSort.title')">
|
||||
<section v-for="group in groups" :key="group.key" class="resource-sort-group">
|
||||
<div class="resource-sort-group__heading">
|
||||
<div class="resource-sort-group__label">{{ group.label }}</div>
|
||||
<div class="resource-sort-group__description">{{ group.description }}</div>
|
||||
</div>
|
||||
<div class="resource-sort-group__options">
|
||||
<button v-for="option in group.options" :key="option.value" type="button"
|
||||
class="resource-sort-option" :class="{ active: modelValue === option.value }"
|
||||
role="menuitemradio" :aria-checked="modelValue === option.value"
|
||||
@click.stop="selectOption(option.value)">
|
||||
<span>{{ optionLabel(option) }}</span>
|
||||
<t-icon v-if="modelValue === option.value" name="check" size="14px" />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
<button type="button" class="resource-sort-trigger" :class="{ active: panelVisible }"
|
||||
:title="`${t('resourceSort.title')}: ${activeLabel}`"
|
||||
:aria-label="`${t('resourceSort.title')}: ${activeLabel}`">
|
||||
<t-icon name="filter-sort" size="16px" />
|
||||
<span class="resource-sort-trigger__label">{{ t('resourceSort.title') }} · {{ activeLabel }}</span>
|
||||
<t-icon name="chevron-down" size="14px" class="resource-sort-trigger__caret"
|
||||
:class="{ open: panelVisible }" />
|
||||
</button>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import {
|
||||
RESOURCE_SORT_OPTIONS,
|
||||
getResourceSortOption,
|
||||
type ResourceSortOption,
|
||||
type ResourceSortValue,
|
||||
} from '@/utils/resourceSorting'
|
||||
|
||||
const props = defineProps<{ modelValue: ResourceSortValue }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: ResourceSortValue] }>()
|
||||
const { t } = useI18n()
|
||||
const panelVisible = ref(false)
|
||||
|
||||
const optionLabel = (option: ResourceSortOption) => t(`resourceSort.${option.labelKey}`)
|
||||
|
||||
const groups = computed(() => [
|
||||
{
|
||||
key: 'updated_at',
|
||||
label: t('resourceSort.updatedTime'),
|
||||
description: t('resourceSort.updatedTimeDescription'),
|
||||
options: RESOURCE_SORT_OPTIONS.filter(option => option.sortBy === 'updated_at'),
|
||||
},
|
||||
{
|
||||
key: 'created_at',
|
||||
label: t('resourceSort.createdTime'),
|
||||
description: t('resourceSort.createdTimeDescription'),
|
||||
options: RESOURCE_SORT_OPTIONS.filter(option => option.sortBy === 'created_at'),
|
||||
},
|
||||
{
|
||||
key: 'name',
|
||||
label: t('resourceSort.name'),
|
||||
description: t('resourceSort.nameDescription'),
|
||||
options: RESOURCE_SORT_OPTIONS.filter(option => option.sortBy === 'name'),
|
||||
},
|
||||
])
|
||||
|
||||
const activeLabel = computed(() => optionLabel(getResourceSortOption(props.modelValue)))
|
||||
|
||||
function selectOption(value: ResourceSortValue) {
|
||||
panelVisible.value = false
|
||||
emit('update:modelValue', value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.resource-sort-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
max-width: 180px;
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 6px;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-sm);
|
||||
cursor: pointer;
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, var(--td-bg-color-container) 72%, transparent);
|
||||
transition: color 0.12s ease, background-color 0.12s ease, border-color 0.12s ease;
|
||||
|
||||
&:hover,
|
||||
&.active {
|
||||
color: var(--td-brand-color);
|
||||
border-color: color-mix(in srgb, var(--td-brand-color) 38%, var(--td-component-stroke));
|
||||
background: var(--td-brand-color-light);
|
||||
}
|
||||
|
||||
&__label {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&__caret {
|
||||
flex-shrink: 0;
|
||||
transition: transform 0.15s ease;
|
||||
|
||||
&.open {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.resource-sort-panel {
|
||||
width: 330px;
|
||||
max-width: calc(100vw - 32px);
|
||||
padding: 6px;
|
||||
box-sizing: border-box;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.resource-sort-group {
|
||||
padding: 7px 6px 8px;
|
||||
|
||||
& + & {
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
&__heading {
|
||||
padding: 0 4px 6px;
|
||||
}
|
||||
|
||||
&__label {
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&__description {
|
||||
margin-top: 1px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 17px;
|
||||
}
|
||||
|
||||
&__options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.resource-sort-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
height: 32px;
|
||||
padding: 0 10px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-md);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--td-brand-color-light);
|
||||
color: var(--td-brand-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -5,6 +5,7 @@ import {
|
|||
listKnowledgeFiles,
|
||||
getKnowledgeDetails,
|
||||
getKnowledgeDetailsCon,
|
||||
type ListKnowledgeFilesParams,
|
||||
} from "@/api/knowledge-base/index";
|
||||
import { knowledgeStore } from "@/stores/knowledge";
|
||||
import { useRoute } from 'vue-router';
|
||||
|
|
@ -39,19 +40,7 @@ export default function (knowledgeBaseId?: string) {
|
|||
let chunkRequestGeneration = 0;
|
||||
let activeKnowledgeId = '';
|
||||
const getKnowled = (
|
||||
query: {
|
||||
page: number;
|
||||
page_size: number;
|
||||
tag_ids?: string;
|
||||
keyword?: string;
|
||||
file_type?: string;
|
||||
parse_status?: string;
|
||||
source?: string;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
folder_path?: string;
|
||||
folder_recursive?: boolean;
|
||||
} = { page: 1, page_size: 35 },
|
||||
query: ListKnowledgeFilesParams = { page: 1, page_size: 35 },
|
||||
kbId?: string,
|
||||
): Promise<void> => {
|
||||
const targetKbId = kbId || knowledgeBaseId;
|
||||
|
|
|
|||
|
|
@ -172,6 +172,21 @@ export default {
|
|||
description: 'Try a different keyword or file type'
|
||||
}
|
||||
},
|
||||
resourceSort: {
|
||||
title: 'Sort',
|
||||
updatedTime: 'Updated time',
|
||||
updatedTimeDescription: 'Default option.',
|
||||
createdTime: 'Created time',
|
||||
createdTimeDescription: 'View the newest or earliest created items',
|
||||
name: 'Name',
|
||||
nameDescription: 'Quickly find an item when you know its name',
|
||||
recentlyUpdated: 'Recently updated',
|
||||
earliestUpdated: 'Earliest updated',
|
||||
recentlyCreated: 'Recently created',
|
||||
earliestCreated: 'Earliest created',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
menu: {
|
||||
sessionInProgress: 'Conversation in progress',
|
||||
knowledgeBase: 'Knowledge Base',
|
||||
|
|
@ -544,6 +559,21 @@ export default {
|
|||
name: 'Name',
|
||||
description: 'Description',
|
||||
settings: 'Settings',
|
||||
sort: {
|
||||
title: 'Sort',
|
||||
updatedTime: 'Updated time',
|
||||
updatedTimeDescription: 'Sort by the latest change made to each file.',
|
||||
createdTime: 'Upload/created time',
|
||||
createdTimeDescription: 'Default. Review the newest additions or the earliest accumulated material.',
|
||||
fileName: 'File name',
|
||||
fileNameDescription: 'Quickly find a file whose name you already know.',
|
||||
recentlyUpdated: 'Recently updated',
|
||||
earliestUpdated: 'Earliest updated',
|
||||
newestCreated: 'Newest uploaded',
|
||||
earliestCreated: 'Earliest uploaded',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
tagUpdateSuccess: 'Tag updated successfully',
|
||||
tagEditDialogHeading: 'Edit tags',
|
||||
folderTree: {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,19 @@
|
|||
export default {
|
||||
resourceSort: {
|
||||
title: '並び替え',
|
||||
updatedTime: '更新日時',
|
||||
updatedTimeDescription: '既定の並び順です。',
|
||||
createdTime: '作成日時',
|
||||
createdTimeDescription: '新しく作成した項目や古い項目を確認',
|
||||
name: '名前',
|
||||
nameDescription: '名前が分かっている項目をすばやく検索',
|
||||
recentlyUpdated: '更新が新しい順',
|
||||
earliestUpdated: '更新が古い順',
|
||||
recentlyCreated: '作成が新しい順',
|
||||
earliestCreated: '作成が古い順',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
localBrowser: {
|
||||
pipOpen: "プレビューを別ウィンドウで表示",
|
||||
pipReturn: "会話内のプレビューに戻す",
|
||||
|
|
@ -545,6 +560,21 @@ export default {
|
|||
description: '説明',
|
||||
settings: '設定',
|
||||
tagUpdateSuccess: 'タグを更新しました',
|
||||
sort: {
|
||||
title: '並び替え',
|
||||
updatedTime: '更新日時',
|
||||
updatedTimeDescription: 'ファイルに最後の変更が加えられた日時で並べ替えます',
|
||||
createdTime: 'アップロード・作成日時',
|
||||
createdTimeDescription: '既定の並び順です。新しく追加した資料や古い資料を確認',
|
||||
fileName: 'ファイル名',
|
||||
fileNameDescription: '名前が分かっているファイルをすばやく検索',
|
||||
recentlyUpdated: '更新が新しい順',
|
||||
earliestUpdated: '更新が古い順',
|
||||
newestCreated: 'アップロードが新しい順',
|
||||
earliestCreated: 'アップロードが古い順',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
tagEditDialogHeading: 'タグを編集',
|
||||
folderTree: {
|
||||
totalDocuments: '全 {count} 件',
|
||||
|
|
|
|||
|
|
@ -125,6 +125,21 @@ export default {
|
|||
"locateWindow": "브라우저 표시",
|
||||
"reconnectShort": "재연결 대기 중",
|
||||
},
|
||||
resourceSort: {
|
||||
title: '정렬',
|
||||
updatedTime: '업데이트 시간',
|
||||
updatedTimeDescription: '기본 옵션입니다.',
|
||||
createdTime: '생성 시간',
|
||||
createdTimeDescription: '최근 또는 가장 먼저 생성된 항목을 확인합니다',
|
||||
name: '이름',
|
||||
nameDescription: '이름을 알고 있는 항목을 빠르게 찾습니다',
|
||||
recentlyUpdated: '최근 업데이트',
|
||||
earliestUpdated: '오래된 업데이트',
|
||||
recentlyCreated: '최근 생성',
|
||||
earliestCreated: '가장 먼저 생성',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
platformApiKeys: {
|
||||
title: '플랫폼 API 키',
|
||||
description: '워크스페이스 간 자동화를 위한 플랫폼 자격 증명입니다. 워크스페이스 API에는 X-Tenant-ID를 사용하세요.',
|
||||
|
|
@ -6725,6 +6740,21 @@ export default {
|
|||
name: '이름',
|
||||
description: '설명',
|
||||
settings: '설정',
|
||||
sort: {
|
||||
title: '정렬',
|
||||
updatedTime: '업데이트 시간',
|
||||
updatedTimeDescription: '파일이 마지막으로 변경된 시간을 기준으로 정렬합니다.',
|
||||
createdTime: '업로드/생성 시간',
|
||||
createdTimeDescription: '기본 옵션입니다. 새로 추가된 자료나 가장 오래된 자료를 확인합니다.',
|
||||
fileName: '파일 이름',
|
||||
fileNameDescription: '이름을 알고 있는 파일을 빠르게 찾습니다.',
|
||||
recentlyUpdated: '최근 업데이트',
|
||||
earliestUpdated: '가장 오래된 업데이트',
|
||||
newestCreated: '최신 업로드',
|
||||
earliestCreated: '가장 오래된 업로드',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
tagUpdateSuccess: '태그 업데이트 성공',
|
||||
tagEditDialogHeading: '태그 편집',
|
||||
folderTree: {
|
||||
|
|
|
|||
|
|
@ -125,6 +125,21 @@ export default {
|
|||
"locateWindow": "Показать браузер",
|
||||
"reconnectShort": "Ожидание подключения",
|
||||
},
|
||||
resourceSort: {
|
||||
title: 'Сортировка',
|
||||
updatedTime: 'Время обновления',
|
||||
updatedTimeDescription: 'Вариант по умолчанию.',
|
||||
createdTime: 'Время создания',
|
||||
createdTimeDescription: 'Показать недавно или давно созданные элементы',
|
||||
name: 'Название',
|
||||
nameDescription: 'Быстро найти элемент по известному названию',
|
||||
recentlyUpdated: 'Сначала обновлённые',
|
||||
earliestUpdated: 'Сначала давно обновлённые',
|
||||
recentlyCreated: 'Сначала новые',
|
||||
earliestCreated: 'Сначала старые',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
platformApiKeys: {
|
||||
title: 'Платформенные API-ключи',
|
||||
description: 'Учетные данные для автоматизации между рабочими пространствами. Для API пространства используйте X-Tenant-ID.',
|
||||
|
|
@ -6725,6 +6740,21 @@ export default {
|
|||
name: 'Название',
|
||||
description: 'Описание',
|
||||
settings: 'Настройки',
|
||||
sort: {
|
||||
title: 'Сортировка',
|
||||
updatedTime: 'Время обновления',
|
||||
updatedTimeDescription: 'Сортировка по времени последнего изменения файла.',
|
||||
createdTime: 'Время загрузки/создания',
|
||||
createdTimeDescription: 'По умолчанию. Просматривайте самые новые или самые ранние материалы.',
|
||||
fileName: 'Имя файла',
|
||||
fileNameDescription: 'Быстро находите файл, имя которого вам известно.',
|
||||
recentlyUpdated: 'Недавно обновлённые',
|
||||
earliestUpdated: 'Обновлённые раньше',
|
||||
newestCreated: 'Сначала новые',
|
||||
earliestCreated: 'Сначала старые',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
tagUpdateSuccess: 'Тег успешно обновлен',
|
||||
tagEditDialogHeading: 'Редактировать теги',
|
||||
folderTree: {
|
||||
|
|
|
|||
|
|
@ -125,6 +125,21 @@ export default {
|
|||
"locateWindow": "定位到浏览器",
|
||||
"reconnectShort": "等待浏览器重连",
|
||||
},
|
||||
resourceSort: {
|
||||
title: '排序',
|
||||
updatedTime: '更新时间',
|
||||
updatedTimeDescription: '默认选项。',
|
||||
createdTime: '创建时间',
|
||||
createdTimeDescription: '查看最新或最早创建的内容',
|
||||
name: '名称',
|
||||
nameDescription: '快速寻找明确知道名称的内容',
|
||||
recentlyUpdated: '最近更新',
|
||||
earliestUpdated: '最早更新',
|
||||
recentlyCreated: '最近创建',
|
||||
earliestCreated: '最早创建',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
platformApiKeys: {
|
||||
title: '平台 API Key',
|
||||
description: '为跨空间自动化创建平台级凭据;调用空间接口时通过 X-Tenant-ID 指定目标空间。',
|
||||
|
|
@ -6727,6 +6742,21 @@ export default {
|
|||
name: '名称',
|
||||
description: '描述',
|
||||
settings: '设置',
|
||||
sort: {
|
||||
title: '排序',
|
||||
updatedTime: '更新时间',
|
||||
updatedTimeDescription: '按文件最近发生变化的时间排序',
|
||||
createdTime: '上传/创建时间',
|
||||
createdTimeDescription: '默认选项。查看新加入或最早积累的资料',
|
||||
fileName: '文件名称',
|
||||
fileNameDescription: '快速寻找明确知道名称的文件',
|
||||
recentlyUpdated: '最近更新',
|
||||
earliestUpdated: '最早更新',
|
||||
newestCreated: '最新上传',
|
||||
earliestCreated: '最早上传',
|
||||
nameAscending: 'A–Z',
|
||||
nameDescending: 'Z–A',
|
||||
},
|
||||
tagUpdateSuccess: '标签已更新',
|
||||
tagEditDialogHeading: '编辑标签',
|
||||
folderTree: {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,98 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
DEFAULT_RESOURCE_SORT,
|
||||
RESOURCE_SORT_OPTIONS,
|
||||
getResourceSortOption,
|
||||
sortResourceItems,
|
||||
sortResourcesWithinGroups,
|
||||
type ResourceSortAccessors,
|
||||
} from './resourceSorting'
|
||||
|
||||
interface Item {
|
||||
id: string
|
||||
group: 'mine' | 'shared'
|
||||
name?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
const accessors: ResourceSortAccessors<Item> = {
|
||||
getName: item => item.name,
|
||||
getCreatedAt: item => item.created_at,
|
||||
getUpdatedAt: item => item.updated_at,
|
||||
}
|
||||
|
||||
const items: Item[] = [
|
||||
{ id: 'old-z', group: 'mine', name: 'Zulu 10', created_at: '2024-01-01', updated_at: '2024-03-01' },
|
||||
{ id: 'new-a', group: 'mine', name: 'Alpha 2', created_at: '2024-02-01', updated_at: '2024-04-01' },
|
||||
{ id: 'middle-a', group: 'mine', name: 'Alpha 11', created_at: '2024-01-15', updated_at: '2024-03-15' },
|
||||
]
|
||||
|
||||
test('资源排序默认使用更新时间倒序并提供三组共六个选项', () => {
|
||||
assert.equal(DEFAULT_RESOURCE_SORT, 'updated_desc')
|
||||
assert.deepEqual(
|
||||
RESOURCE_SORT_OPTIONS.map(({ value, sortBy, sortOrder }) => [value, sortBy, sortOrder]),
|
||||
[
|
||||
['updated_desc', 'updated_at', 'desc'],
|
||||
['updated_asc', 'updated_at', 'asc'],
|
||||
['created_desc', 'created_at', 'desc'],
|
||||
['created_asc', 'created_at', 'asc'],
|
||||
['name_asc', 'name', 'asc'],
|
||||
['name_desc', 'name', 'desc'],
|
||||
],
|
||||
)
|
||||
assert.deepEqual(
|
||||
sortResourceItems(items, DEFAULT_RESOURCE_SORT, accessors).map(item => item.id),
|
||||
['new-a', 'middle-a', 'old-z'],
|
||||
)
|
||||
})
|
||||
|
||||
test('未知资源排序值会安全回退到默认选项', () => {
|
||||
assert.equal(getResourceSortOption('invalid' as never).value, DEFAULT_RESOURCE_SORT)
|
||||
})
|
||||
|
||||
test('资源排序支持创建时间和名称的双向排序', () => {
|
||||
assert.deepEqual(
|
||||
sortResourceItems(items, 'created_asc', accessors).map(item => item.id),
|
||||
['old-z', 'middle-a', 'new-a'],
|
||||
)
|
||||
assert.deepEqual(
|
||||
sortResourceItems(items, 'name_asc', accessors).map(item => item.id),
|
||||
['new-a', 'middle-a', 'old-z'],
|
||||
)
|
||||
assert.deepEqual(
|
||||
sortResourceItems(items, 'name_desc', accessors).map(item => item.id),
|
||||
['old-z', 'middle-a', 'new-a'],
|
||||
)
|
||||
})
|
||||
|
||||
test('排序保留固定分组顺序,只调整组内条目', () => {
|
||||
const mixed: Item[] = [
|
||||
{ ...items[0], group: 'shared' },
|
||||
{ ...items[1], group: 'mine' },
|
||||
{ ...items[2], group: 'shared' },
|
||||
]
|
||||
assert.deepEqual(
|
||||
sortResourcesWithinGroups(mixed, 'updated_desc', item => item.group, ['mine', 'shared'], accessors)
|
||||
.map(item => `${item.group}:${item.id}`),
|
||||
['mine:new-a', 'shared:middle-a', 'shared:old-z'],
|
||||
)
|
||||
})
|
||||
|
||||
test('缺少排序字段的旧数据始终排在末尾,值相同时保持原顺序', () => {
|
||||
const legacy: Item[] = [
|
||||
{ id: 'first', group: 'mine', name: 'Same', updated_at: '2024-01-01' },
|
||||
{ id: 'missing', group: 'mine' },
|
||||
{ id: 'second', group: 'mine', name: 'same', updated_at: '2024-01-01' },
|
||||
]
|
||||
assert.deepEqual(
|
||||
sortResourceItems(legacy, 'updated_asc', accessors).map(item => item.id),
|
||||
['first', 'second', 'missing'],
|
||||
)
|
||||
assert.deepEqual(
|
||||
sortResourceItems(legacy, 'name_desc', accessors).map(item => item.id),
|
||||
['first', 'second', 'missing'],
|
||||
)
|
||||
})
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
export type ResourceSortValue =
|
||||
| 'updated_desc'
|
||||
| 'updated_asc'
|
||||
| 'created_desc'
|
||||
| 'created_asc'
|
||||
| 'name_asc'
|
||||
| 'name_desc'
|
||||
|
||||
export type ResourceSortField = 'updated_at' | 'created_at' | 'name'
|
||||
|
||||
export interface ResourceSortOption {
|
||||
value: ResourceSortValue
|
||||
sortBy: ResourceSortField
|
||||
sortOrder: 'asc' | 'desc'
|
||||
labelKey:
|
||||
| 'recentlyUpdated'
|
||||
| 'earliestUpdated'
|
||||
| 'recentlyCreated'
|
||||
| 'earliestCreated'
|
||||
| 'nameAscending'
|
||||
| 'nameDescending'
|
||||
}
|
||||
|
||||
export interface ResourceSortAccessors<T> {
|
||||
getName: (item: T) => string | null | undefined
|
||||
getUpdatedAt: (item: T) => string | number | Date | null | undefined
|
||||
getCreatedAt: (item: T) => string | number | Date | null | undefined
|
||||
}
|
||||
|
||||
export const DEFAULT_RESOURCE_SORT: ResourceSortValue = 'updated_desc'
|
||||
|
||||
export const RESOURCE_SORT_OPTIONS: readonly ResourceSortOption[] = [
|
||||
{ value: 'updated_desc', sortBy: 'updated_at', sortOrder: 'desc', labelKey: 'recentlyUpdated' },
|
||||
{ value: 'updated_asc', sortBy: 'updated_at', sortOrder: 'asc', labelKey: 'earliestUpdated' },
|
||||
{ value: 'created_desc', sortBy: 'created_at', sortOrder: 'desc', labelKey: 'recentlyCreated' },
|
||||
{ value: 'created_asc', sortBy: 'created_at', sortOrder: 'asc', labelKey: 'earliestCreated' },
|
||||
{ value: 'name_asc', sortBy: 'name', sortOrder: 'asc', labelKey: 'nameAscending' },
|
||||
{ value: 'name_desc', sortBy: 'name', sortOrder: 'desc', labelKey: 'nameDescending' },
|
||||
]
|
||||
|
||||
export function getResourceSortOption(value: ResourceSortValue): ResourceSortOption {
|
||||
return RESOURCE_SORT_OPTIONS.find(option => option.value === value) ?? RESOURCE_SORT_OPTIONS[0]
|
||||
}
|
||||
|
||||
function parseTimestamp(value: string | number | Date | null | undefined): number | null {
|
||||
if (value === null || value === undefined || value === '') return null
|
||||
const timestamp = value instanceof Date
|
||||
? value.getTime()
|
||||
: typeof value === 'number'
|
||||
? value
|
||||
: Date.parse(value)
|
||||
return Number.isFinite(timestamp) ? timestamp : null
|
||||
}
|
||||
|
||||
function compareNullable<T>(
|
||||
left: T | null,
|
||||
right: T | null,
|
||||
direction: 1 | -1,
|
||||
compare: (a: T, b: T) => number,
|
||||
): number {
|
||||
// 缺少时间或名称的旧数据始终排在末尾,避免切换升序后突然跑到最前面。
|
||||
if (left === null && right === null) return 0
|
||||
if (left === null) return 1
|
||||
if (right === null) return -1
|
||||
return compare(left, right) * direction
|
||||
}
|
||||
|
||||
export function sortResourceItems<T>(
|
||||
items: readonly T[],
|
||||
value: ResourceSortValue,
|
||||
accessors: ResourceSortAccessors<T>,
|
||||
): T[] {
|
||||
const option = getResourceSortOption(value)
|
||||
const direction: 1 | -1 = option.sortOrder === 'asc' ? 1 : -1
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
|
||||
|
||||
return items
|
||||
.map((item, index) => ({ item, index }))
|
||||
.sort((left, right) => {
|
||||
let result = 0
|
||||
if (option.sortBy === 'name') {
|
||||
const leftName = accessors.getName(left.item)?.trim() || null
|
||||
const rightName = accessors.getName(right.item)?.trim() || null
|
||||
result = compareNullable(leftName, rightName, direction, (a, b) => collator.compare(a, b))
|
||||
} else {
|
||||
const getter = option.sortBy === 'updated_at'
|
||||
? accessors.getUpdatedAt
|
||||
: accessors.getCreatedAt
|
||||
result = compareNullable(
|
||||
parseTimestamp(getter(left.item)),
|
||||
parseTimestamp(getter(right.item)),
|
||||
direction,
|
||||
(a, b) => a - b,
|
||||
)
|
||||
}
|
||||
return result || left.index - right.index
|
||||
})
|
||||
.map(entry => entry.item)
|
||||
}
|
||||
|
||||
export function sortResourcesWithinGroups<T, TGroup extends string>(
|
||||
items: readonly T[],
|
||||
value: ResourceSortValue,
|
||||
getGroup: (item: T) => TGroup,
|
||||
groupOrder: readonly TGroup[],
|
||||
accessors: ResourceSortAccessors<T>,
|
||||
): T[] {
|
||||
const groups = new Map<TGroup, T[]>()
|
||||
for (const group of groupOrder) groups.set(group, [])
|
||||
for (const item of items) {
|
||||
const group = getGroup(item)
|
||||
const bucket = groups.get(group)
|
||||
if (bucket) bucket.push(item)
|
||||
else groups.set(group, [item])
|
||||
}
|
||||
|
||||
return [...groups.values()].flatMap(group => sortResourceItems(group, value, accessors))
|
||||
}
|
||||
|
|
@ -8,31 +8,34 @@
|
|||
<ResourceIcon type="agent" :size="24" />
|
||||
{{ $t('agent.title') }}
|
||||
</h2>
|
||||
<t-tooltip v-if="authStore.hasRole('contributor')" :content="$t('agent.createAgent')" placement="bottom">
|
||||
<t-button variant="text" theme="default" size="small" class="header-action-btn"
|
||||
data-guide="agent-list-create" style="--wails-draggable: no-drag" @click="handleCreateAgent">
|
||||
<template #icon>
|
||||
<span class="btn-icon-wrapper">
|
||||
<svg class="sparkles-icon" width="19" height="19" viewBox="0 0 20 20" fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z"
|
||||
fill="currentColor" stroke="currentColor" stroke-width="0.8" stroke-linecap="round"
|
||||
stroke-linejoin="round" />
|
||||
<path
|
||||
d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z"
|
||||
fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linecap="round"
|
||||
stroke-linejoin="round" />
|
||||
<path
|
||||
d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z"
|
||||
fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linecap="round"
|
||||
stroke-linejoin="round" />
|
||||
</svg>
|
||||
</span>
|
||||
</template>
|
||||
{{ $t('agent.createAgent') }}
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
<div class="header-actions" style="--wails-draggable: no-drag">
|
||||
<ResourceSortControl v-model="selectedResourceSort" />
|
||||
<t-tooltip v-if="authStore.hasRole('contributor')" :content="$t('agent.createAgent')" placement="bottom">
|
||||
<t-button variant="text" theme="default" size="small" class="header-action-btn"
|
||||
data-guide="agent-list-create" style="--wails-draggable: no-drag" @click="handleCreateAgent">
|
||||
<template #icon>
|
||||
<span class="btn-icon-wrapper">
|
||||
<svg class="sparkles-icon" width="19" height="19" viewBox="0 0 20 20" fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z"
|
||||
fill="currentColor" stroke="currentColor" stroke-width="0.8" stroke-linecap="round"
|
||||
stroke-linejoin="round" />
|
||||
<path
|
||||
d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z"
|
||||
fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linecap="round"
|
||||
stroke-linejoin="round" />
|
||||
<path
|
||||
d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z"
|
||||
fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linecap="round"
|
||||
stroke-linejoin="round" />
|
||||
</svg>
|
||||
</span>
|
||||
</template>
|
||||
{{ $t('agent.createAgent') }}
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<p class="header-subtitle" style="--wails-draggable: drag">{{ $t('agent.subtitle') }}</p>
|
||||
</div>
|
||||
|
|
@ -758,12 +761,19 @@ import { useUIStore } from '@/stores/ui'
|
|||
import AgentAvatar from '@/components/AgentAvatar.vue'
|
||||
import ResourceListToolbar from '@/components/ResourceListToolbar.vue'
|
||||
import { matchesResourceQuery } from '@/utils/resourceListSearch'
|
||||
import ResourceSortControl from '@/components/ResourceSortControl.vue'
|
||||
import ResourceOriginBadge from '@/components/ResourceOriginBadge.vue'
|
||||
import { shouldShowResourceOriginBadge } from '@/utils/card-list-badge'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useListUrlState } from '@/composables/useListUrlState'
|
||||
import { useResourcePins } from '@/composables/useResourcePins'
|
||||
import { integrationSectionKey } from '@/config/settingsRoute'
|
||||
import {
|
||||
DEFAULT_RESOURCE_SORT,
|
||||
sortResourcesWithinGroups,
|
||||
type ResourceSortAccessors,
|
||||
type ResourceSortValue,
|
||||
} from '@/utils/resourceSorting'
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
|
|
@ -773,6 +783,7 @@ const uiStore = useUIStore()
|
|||
const orgStore = useOrganizationStore()
|
||||
const chatResources = useChatResourcesStore()
|
||||
const { loaded: modelsReadyLoaded, isReadyForAgent } = useTenantModelReadiness()
|
||||
const selectedResourceSort = ref<ResourceSortValue>(DEFAULT_RESOURCE_SORT)
|
||||
|
||||
interface AgentWithUI extends CustomAgent {
|
||||
showMore?: boolean
|
||||
|
|
@ -785,6 +796,32 @@ interface AgentWithUI extends CustomAgent {
|
|||
* `permission` drives the「可编辑 / 仅查看」分组,仅在 shared 分支携带。 */
|
||||
type DisplayAgent = (AgentWithUI & { isMine: true }) | (CustomAgent & { isMine: false; org_name: string; source_tenant_id: number; share_id: string; permission?: string; showMore?: boolean; disabled_by_me?: boolean })
|
||||
|
||||
const flatAgentSortAccessors: ResourceSortAccessors<any> = {
|
||||
getName: item => item?.name,
|
||||
getUpdatedAt: item => item?.updated_at ?? item?.shared_at,
|
||||
getCreatedAt: item => item?.created_at ?? item?.shared_at,
|
||||
}
|
||||
|
||||
const sharedAgentSortAccessors: ResourceSortAccessors<OrganizationSharedAgentItem> = {
|
||||
getName: item => item.agent?.name,
|
||||
getUpdatedAt: item => item.agent?.updated_at ?? item.shared_at,
|
||||
getCreatedAt: item => item.agent?.created_at ?? item.shared_at,
|
||||
}
|
||||
|
||||
const displayAgentSortGroup = (item: DisplayAgent) => {
|
||||
if (item.is_builtin) return 'builtin'
|
||||
if (item.isMine) return isMyAgent(item) ? 'mine' : 'tenantOthers'
|
||||
return isSharedAgentEditable(item.permission) ? 'sharedEditable' : 'sharedReadonly'
|
||||
}
|
||||
|
||||
const sortDisplayAgents = (items: readonly DisplayAgent[]) => sortResourcesWithinGroups(
|
||||
items,
|
||||
selectedResourceSort.value,
|
||||
displayAgentSortGroup,
|
||||
['builtin', 'mine', 'tenantOthers', 'sharedEditable', 'sharedReadonly'],
|
||||
flatAgentSortAccessors,
|
||||
)
|
||||
|
||||
// 左侧空间选择:默认根据当前角色决定。
|
||||
// 与 KnowledgeBaseList 同款逻辑:Viewer 在当前空间里通常没有自建智能体,
|
||||
// 默认落到 "all" 才能看到内置 + 共享给我的;Contributor 以上仍默认 "mine"。
|
||||
|
|
@ -899,10 +936,10 @@ const recentsAgentList = computed<DisplayAgent[]>(() => {
|
|||
})
|
||||
|
||||
const unsearchedFilteredAgents = computed<DisplayAgent[]>(() => {
|
||||
if (spaceSelection.value === 'favorites') return favoritesAgentList.value
|
||||
if (spaceSelection.value === 'recents') return recentsAgentList.value
|
||||
if (spaceSelection.value === 'favorites') return sortDisplayAgents(favoritesAgentList.value)
|
||||
if (spaceSelection.value === 'recents') return sortDisplayAgents(recentsAgentList.value)
|
||||
if (spaceSelection.value === 'mine') {
|
||||
return agents.value.map(a => ({ ...a, isMine: true as const }))
|
||||
return sortDisplayAgents(agents.value.map(a => ({ ...a, isMine: true as const })))
|
||||
}
|
||||
if (spaceSelection.value !== 'all') return []
|
||||
const list: DisplayAgent[] = []
|
||||
|
|
@ -943,36 +980,33 @@ const unsearchedFilteredAgents = computed<DisplayAgent[]>(() => {
|
|||
showMore: false
|
||||
} as DisplayAgent)
|
||||
})
|
||||
return list
|
||||
return sortDisplayAgents(list)
|
||||
})
|
||||
const filteredAgents = computed(() => unsearchedFilteredAgents.value.filter(item => matchesResourceQuery(item, keyword.value)))
|
||||
|
||||
// 「工作空间」视图下的稳定排序:本空间内「我创建」在前、「同事创建 / 内建」
|
||||
// 在后。给 contributor 视图把「本空间 · 仅查看」分组标题正好插在过渡处。
|
||||
// 「工作空间」固定保持“内置 → 我创建 → 同事创建”,用户选择只影响组内顺序。
|
||||
const unsearchedSortedMineAgents = computed(() => {
|
||||
// 内置 → 我创建 → 同事创建。与 filteredAgents 的"全部"视图保持同序。
|
||||
const builtin: AgentWithUI[] = []
|
||||
const own: AgentWithUI[] = []
|
||||
const teammate: AgentWithUI[] = []
|
||||
agents.value.forEach(a => {
|
||||
if (a.is_builtin) builtin.push(a)
|
||||
else if (isMyAgent(a)) own.push(a)
|
||||
else teammate.push(a)
|
||||
})
|
||||
return [...builtin, ...own, ...teammate]
|
||||
return sortResourcesWithinGroups(
|
||||
agents.value,
|
||||
selectedResourceSort.value,
|
||||
item => item.is_builtin ? 'builtin' : isMyAgent(item) ? 'mine' : 'tenantOthers',
|
||||
['builtin', 'mine', 'tenantOthers'],
|
||||
flatAgentSortAccessors,
|
||||
)
|
||||
})
|
||||
const sortedMineAgents = computed(() => unsearchedSortedMineAgents.value.filter(item => matchesResourceQuery(item, keyword.value)))
|
||||
|
||||
// 空间视角下的稳定排序:我自己创建的(is_mine)放前面,其余按 permission 切分。
|
||||
// 空间视角固定保持“我共享的 → 可编辑 → 仅查看”,用户选择只影响组内顺序。
|
||||
const unsearchedSortedSpaceAgentsList = computed(() => {
|
||||
return [...spaceAgentsList.value].sort((a, b) => {
|
||||
const aMine = a.is_mine ? 0 : 1
|
||||
const bMine = b.is_mine ? 0 : 1
|
||||
if (aMine !== bMine) return aMine - bMine
|
||||
const aE = isSharedAgentEditable(a.permission) ? 0 : 1
|
||||
const bE = isSharedAgentEditable(b.permission) ? 0 : 1
|
||||
return aE - bE
|
||||
})
|
||||
return sortResourcesWithinGroups(
|
||||
spaceAgentsList.value,
|
||||
selectedResourceSort.value,
|
||||
item => item.is_mine
|
||||
? 'sharedByMe'
|
||||
: isSharedAgentEditable(item.permission) ? 'sharedEditable' : 'sharedReadonly',
|
||||
['sharedByMe', 'sharedEditable', 'sharedReadonly'],
|
||||
sharedAgentSortAccessors,
|
||||
)
|
||||
})
|
||||
const sortedSpaceAgentsList = computed(() => unsearchedSortedSpaceAgentsList.value.filter(item => matchesResourceQuery(item.agent, keyword.value)))
|
||||
const loading = ref(false)
|
||||
|
|
@ -1575,6 +1609,13 @@ watch(keyword, () => { collapsedAgentSections.value = new Set() })
|
|||
line-height: 20px;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.header-action-btn {
|
||||
padding: 0;
|
||||
min-width: 28px;
|
||||
|
|
|
|||
|
|
@ -71,6 +71,14 @@ import {
|
|||
isFilteringDocuments,
|
||||
ROOT_FOLDER_PATH,
|
||||
} from './folderTree';
|
||||
import {
|
||||
DEFAULT_DOCUMENT_SORT,
|
||||
DOCUMENT_SORT_OPTIONS,
|
||||
getDocumentSortOption,
|
||||
getDocumentSortParams,
|
||||
type DocumentSortOption,
|
||||
type DocumentSortValue,
|
||||
} from './documentSorting';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useMarqueeSelect } from '@/hooks/useMarqueeSelect';
|
||||
import type { ParserEngineInfo } from '@/api/system';
|
||||
|
|
@ -682,6 +690,52 @@ const clearDocumentFilters = () => {
|
|||
};
|
||||
// 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 documentSortPanelVisible = ref(false);
|
||||
const selectedDocumentSort = ref<DocumentSortValue>(DEFAULT_DOCUMENT_SORT);
|
||||
|
||||
const documentSortOptionLabel = (option: DocumentSortOption) => {
|
||||
switch (option.labelKey) {
|
||||
case 'earliestUpdated':
|
||||
return t('knowledgeBase.sort.earliestUpdated');
|
||||
case 'newestCreated':
|
||||
return t('knowledgeBase.sort.newestCreated');
|
||||
case 'earliestCreated':
|
||||
return t('knowledgeBase.sort.earliestCreated');
|
||||
case 'nameAscending':
|
||||
return t('knowledgeBase.sort.nameAscending');
|
||||
case 'nameDescending':
|
||||
return t('knowledgeBase.sort.nameDescending');
|
||||
default:
|
||||
return t('knowledgeBase.sort.recentlyUpdated');
|
||||
}
|
||||
};
|
||||
|
||||
const documentSortGroups = computed(() => [
|
||||
{
|
||||
key: 'updated_at',
|
||||
label: t('knowledgeBase.sort.updatedTime'),
|
||||
description: t('knowledgeBase.sort.updatedTimeDescription'),
|
||||
options: DOCUMENT_SORT_OPTIONS.filter((option) => option.sortBy === 'updated_at'),
|
||||
},
|
||||
{
|
||||
key: 'created_at',
|
||||
label: t('knowledgeBase.sort.createdTime'),
|
||||
description: t('knowledgeBase.sort.createdTimeDescription'),
|
||||
options: DOCUMENT_SORT_OPTIONS.filter((option) => option.sortBy === 'created_at'),
|
||||
},
|
||||
{
|
||||
key: 'file_name',
|
||||
label: t('knowledgeBase.sort.fileName'),
|
||||
description: t('knowledgeBase.sort.fileNameDescription'),
|
||||
options: DOCUMENT_SORT_OPTIONS.filter((option) => option.sortBy === 'file_name'),
|
||||
},
|
||||
]);
|
||||
|
||||
const activeDocumentSortLabel = computed(() => {
|
||||
const option = getDocumentSortOption(selectedDocumentSort.value);
|
||||
const group = documentSortGroups.value.find((item) => item.key === option.sortBy);
|
||||
return `${group?.label || ''} · ${documentSortOptionLabel(option)}`;
|
||||
});
|
||||
|
||||
// ── Folder tree (documents uploaded as a folder keep their relative path) ──
|
||||
// The directory sidebar is now the sole folder navigation and starts expanded.
|
||||
|
|
@ -737,11 +791,27 @@ const filterParams = computed(() => {
|
|||
source: selectedSource.value || undefined,
|
||||
start_time: start ? `${start} 00:00:00` : undefined,
|
||||
end_time: end ? `${end} 23:59:59` : undefined,
|
||||
...getDocumentSortParams(selectedDocumentSort.value),
|
||||
folder_path: selectedFolderPath.value,
|
||||
// Filtering searches descendants; browsing shows this folder's documents.
|
||||
folder_recursive: isFiltering.value,
|
||||
};
|
||||
});
|
||||
|
||||
const handleDocumentSortSelect = (value: DocumentSortValue) => {
|
||||
documentSortPanelVisible.value = false;
|
||||
if (selectedDocumentSort.value === value) return;
|
||||
|
||||
selectedDocumentSort.value = value;
|
||||
clearSelection();
|
||||
resetPage();
|
||||
if (knowledgeScroll.value) {
|
||||
knowledgeScroll.value.scrollTop = 0;
|
||||
}
|
||||
if (kbId.value && !isFAQ.value) {
|
||||
loadKnowledgeFiles(kbId.value);
|
||||
}
|
||||
};
|
||||
const tagMap = computed<Record<string, any>>(() => {
|
||||
const map: Record<string, any> = {};
|
||||
tagList.value.forEach((tag) => {
|
||||
|
|
@ -2346,6 +2416,39 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
|
|||
<t-icon :name="batchMode ? 'close' : 'check-rectangle'" size="16px" />
|
||||
{{ $t(batchMode ? 'common.cancel' : 'menu.batchManage') }}
|
||||
</button>
|
||||
<t-popup v-model:visible="documentSortPanelVisible" trigger="click" placement="bottom-right"
|
||||
overlay-class-name="document-sort-popup" :overlay-inner-style="{ padding: 0 }">
|
||||
<template #content>
|
||||
<div class="document-sort-panel" role="menu" :aria-label="$t('knowledgeBase.sort.title')">
|
||||
<section v-for="group in documentSortGroups" :key="group.key" class="document-sort-group">
|
||||
<div class="document-sort-group__heading">
|
||||
<div class="document-sort-group__label">{{ group.label }}</div>
|
||||
<div class="document-sort-group__description">{{ group.description }}</div>
|
||||
</div>
|
||||
<div class="document-sort-group__options">
|
||||
<button v-for="option in group.options" :key="option.value" type="button"
|
||||
class="document-sort-option"
|
||||
:class="{ active: selectedDocumentSort === option.value }"
|
||||
role="menuitemradio" :aria-checked="selectedDocumentSort === option.value"
|
||||
@click.stop="handleDocumentSortSelect(option.value)">
|
||||
<span>{{ documentSortOptionLabel(option) }}</span>
|
||||
<t-icon v-if="selectedDocumentSort === option.value" name="check" size="14px" />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
<button type="button" class="doc-sort-trigger" :class="{ active: documentSortPanelVisible }"
|
||||
:title="`${$t('knowledgeBase.sort.title')}: ${activeDocumentSortLabel}`"
|
||||
:aria-label="`${$t('knowledgeBase.sort.title')}: ${activeDocumentSortLabel}`">
|
||||
<t-icon name="filter-sort" size="16px" />
|
||||
<span class="doc-sort-trigger__label">
|
||||
{{ $t('knowledgeBase.sort.title') }} · {{ activeDocumentSortLabel }}
|
||||
</span>
|
||||
<t-icon name="chevron-down" size="14px" class="doc-sort-trigger__caret"
|
||||
:class="{ open: documentSortPanelVisible }" />
|
||||
</button>
|
||||
</t-popup>
|
||||
<div class="doc-view-toggle" role="group" :aria-label="$t('knowledgeBase.viewModeToggle')">
|
||||
<t-tooltip :content="$t('knowledgeBase.viewModeGrid')" placement="top">
|
||||
<button type="button" class="doc-view-toggle-btn" :class="{ active: viewMode === 'grid' }"
|
||||
|
|
@ -2762,6 +2865,71 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
|
|||
:deep(.t-date-range-picker) { width: 100%; }
|
||||
}
|
||||
}
|
||||
|
||||
.document-sort-panel {
|
||||
width: 330px;
|
||||
max-width: min(330px, calc(100vw - 32px));
|
||||
padding: 6px;
|
||||
box-sizing: border-box;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.document-sort-group {
|
||||
padding: 7px 6px 8px;
|
||||
|
||||
& + & {
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
&__heading {
|
||||
padding: 0 4px 6px;
|
||||
}
|
||||
|
||||
&__label {
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&__description {
|
||||
margin-top: 1px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 17px;
|
||||
}
|
||||
|
||||
&__options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.document-sort-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
height: 32px;
|
||||
padding: 0 10px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-md);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--td-brand-color-light);
|
||||
color: var(--td-brand-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
.doc-filter-tags {
|
||||
margin-top: 16px;
|
||||
padding-top: 14px;
|
||||
|
|
@ -2795,6 +2963,43 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
|
|||
.doc-filter-bar .doc-search-input { flex: 1; width: auto; }
|
||||
}
|
||||
|
||||
.doc-sort-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
max-width: 220px;
|
||||
height: 32px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-md);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover,
|
||||
&.active {
|
||||
color: var(--td-text-color-primary);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
&__label {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&__caret {
|
||||
flex-shrink: 0;
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&.open { transform: rotate(180deg); }
|
||||
}
|
||||
}
|
||||
|
||||
@container doc-card-area (max-width: 540px) {
|
||||
.doc-filter-bar__trailing { flex-wrap: wrap; }
|
||||
.doc-filter-bar .doc-search-input { flex: 1 0 100%; }
|
||||
|
|
|
|||
|
|
@ -8,13 +8,16 @@
|
|||
<ResourceIcon type="knowledge" :size="24" />
|
||||
{{ $t('knowledgeBase.title') }}
|
||||
</h2>
|
||||
<t-tooltip v-if="authStore.hasRole('contributor')" :content="$t('knowledgeList.create')" placement="bottom">
|
||||
<t-button variant="text" theme="default" size="small" class="header-action-btn"
|
||||
data-guide="kb-list-create" style="--wails-draggable: no-drag" @click="handleCreateKnowledgeBase">
|
||||
<template #icon><t-icon name="folder-add" size="16px" /></template>
|
||||
{{ $t('knowledgeList.create') }}
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
<div class="header-actions" style="--wails-draggable: no-drag">
|
||||
<ResourceSortControl v-model="selectedResourceSort" />
|
||||
<t-tooltip v-if="authStore.hasRole('contributor')" :content="$t('knowledgeList.create')" placement="bottom">
|
||||
<t-button variant="text" theme="default" size="small" class="header-action-btn"
|
||||
data-guide="kb-list-create" style="--wails-draggable: no-drag" @click="handleCreateKnowledgeBase">
|
||||
<template #icon><t-icon name="folder-add" size="16px" /></template>
|
||||
{{ $t('knowledgeList.create') }}
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<p class="header-subtitle" style="--wails-draggable: drag">{{ $t('knowledgeList.subtitle') }}</p>
|
||||
</div>
|
||||
|
|
@ -727,11 +730,18 @@ import ResourceOriginBadge from '@/components/ResourceOriginBadge.vue'
|
|||
import { shouldShowResourceOriginBadge } from '@/utils/card-list-badge'
|
||||
import { permissionCanManageKB } from '@/utils/kbPermission'
|
||||
import ContextualGuide from '@/components/ContextualGuide.vue'
|
||||
import ResourceSortControl from '@/components/ResourceSortControl.vue'
|
||||
import { isContextualGuideDone, markContextualGuideDone } from '@/config/contextualGuides'
|
||||
import { useTenantModelReadiness } from '@/composables/useTenantModelReadiness'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useListUrlState } from '@/composables/useListUrlState'
|
||||
import { useResourcePins } from '@/composables/useResourcePins'
|
||||
import {
|
||||
DEFAULT_RESOURCE_SORT,
|
||||
sortResourcesWithinGroups,
|
||||
type ResourceSortAccessors,
|
||||
type ResourceSortValue,
|
||||
} from '@/utils/resourceSorting'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
|
@ -741,6 +751,7 @@ const { loaded: modelsReadyLoaded, isReadyForDocumentKb } = useTenantModelReadin
|
|||
const orgStore = useOrganizationStore()
|
||||
const chatResources = useChatResourcesStore()
|
||||
const { t } = useI18n()
|
||||
const selectedResourceSort = ref<ResourceSortValue>(DEFAULT_RESOURCE_SORT)
|
||||
|
||||
// 左侧空间选择:默认根据当前角色决定。
|
||||
// Viewer 在该空间里通常 0 KB owned,"我的"会显示空状态、又把共享 KB 藏起来,
|
||||
|
|
@ -797,6 +808,18 @@ interface KB {
|
|||
creator_name?: string;
|
||||
}
|
||||
|
||||
const flatKnowledgeBaseSortAccessors: ResourceSortAccessors<any> = {
|
||||
getName: item => item?.name,
|
||||
getUpdatedAt: item => item?.updated_at ?? item?.shared_at,
|
||||
getCreatedAt: item => item?.created_at ?? item?.shared_at,
|
||||
}
|
||||
|
||||
const sharedKnowledgeBaseSortAccessors: ResourceSortAccessors<OrganizationSharedKnowledgeBaseItem> = {
|
||||
getName: item => item.knowledge_base?.name,
|
||||
getUpdatedAt: item => item.knowledge_base?.updated_at ?? item.shared_at,
|
||||
getCreatedAt: item => item.knowledge_base?.created_at ?? item.shared_at,
|
||||
}
|
||||
|
||||
const kbs = ref<KB[]>([])
|
||||
const loading = ref(false)
|
||||
const confirmDelete = useConfirmDelete()
|
||||
|
|
@ -828,50 +851,29 @@ const spaceSelectionOrgId = computed(() => {
|
|||
const spaceKbsList = ref<OrganizationSharedKnowledgeBaseItem[]>([])
|
||||
const spaceKbsLoading = ref(false)
|
||||
|
||||
// 「工作空间」视图下的稳定排序:本空间内「我创建」在前、「同事创建」在后;
|
||||
// 子段内保留服务端的置顶优先顺序。给 contributor 视图把「本空间 · 仅查看」
|
||||
// 分组标题正好插在过渡处;其他角色看不到标题,纯排序变化也无害。
|
||||
// Ordering for the 「本空间」 tab:
|
||||
// 1. pinned KBs (mine or teammate), newest pin first
|
||||
// 2. my non-pinned KBs
|
||||
// 3. teammate non-pinned KBs (rendered under the「本空间 · 仅查看」header)
|
||||
//
|
||||
// Pin is per-user as of migration 000050, so a teammate-created KB that
|
||||
// the caller has personally pinned must float into the pinned section
|
||||
// even though it would otherwise live in the teammate sub-group. The
|
||||
// previous version only bucketed by isMyKb and silently demoted these
|
||||
// pinned-but-teammate KBs.
|
||||
// 「工作空间」固定保持“置顶 → 我创建 → 同事创建”,用户选择只影响组内顺序。
|
||||
const unsearchedSortedMineKbs = computed<KB[]>(() => {
|
||||
return [...kbs.value].sort((a, b) => {
|
||||
const ap = a.is_pinned ? 0 : 1
|
||||
const bp = b.is_pinned ? 0 : 1
|
||||
if (ap !== bp) return ap - bp
|
||||
if (a.is_pinned && b.is_pinned) {
|
||||
const at = a.pinned_at ? Date.parse(a.pinned_at as string) : 0
|
||||
const bt = b.pinned_at ? Date.parse(b.pinned_at as string) : 0
|
||||
if (at !== bt) return bt - at
|
||||
}
|
||||
const am = isMyKb(a) ? 0 : 1
|
||||
const bm = isMyKb(b) ? 0 : 1
|
||||
if (am !== bm) return am - bm
|
||||
const ac = a.created_at ? Date.parse(a.created_at as string) : 0
|
||||
const bc = b.created_at ? Date.parse(b.created_at as string) : 0
|
||||
return bc - ac
|
||||
})
|
||||
return sortResourcesWithinGroups(
|
||||
kbs.value,
|
||||
selectedResourceSort.value,
|
||||
kb => kb.is_pinned ? 'pinned' : isMyKb(kb) ? 'mine' : 'tenantOthers',
|
||||
['pinned', 'mine', 'tenantOthers'],
|
||||
flatKnowledgeBaseSortAccessors,
|
||||
)
|
||||
})
|
||||
const sortedMineKbs = computed(() => unsearchedSortedMineKbs.value.filter(item => matchesResourceQuery(item, keyword.value)))
|
||||
|
||||
// 空间视角下的稳定排序:我创建的(is_mine)放在前面,剩下的共享部分再按
|
||||
// 可编辑 / 仅查看 排序——这样空间列表跟「全部」视图的视觉顺序一致。
|
||||
// 空间视角固定保持“我共享的 → 可编辑 → 仅查看”,用户选择只影响组内顺序。
|
||||
const unsearchedSortedSpaceKbsList = computed(() => {
|
||||
return [...spaceKbsList.value].sort((a, b) => {
|
||||
const aMine = a.is_mine ? 0 : 1
|
||||
const bMine = b.is_mine ? 0 : 1
|
||||
if (aMine !== bMine) return aMine - bMine
|
||||
const aE = isSharedKbEditable(a.permission) ? 0 : 1
|
||||
const bE = isSharedKbEditable(b.permission) ? 0 : 1
|
||||
return aE - bE
|
||||
})
|
||||
return sortResourcesWithinGroups(
|
||||
spaceKbsList.value,
|
||||
selectedResourceSort.value,
|
||||
item => item.is_mine
|
||||
? 'sharedByMe'
|
||||
: isSharedKbEditable(item.permission) ? 'sharedEditable' : 'sharedReadonly',
|
||||
['sharedByMe', 'sharedEditable', 'sharedReadonly'],
|
||||
sharedKnowledgeBaseSortAccessors,
|
||||
)
|
||||
})
|
||||
const sortedSpaceKbsList = computed(() => unsearchedSortedSpaceKbsList.value.filter(item => matchesResourceQuery(item.knowledge_base, keyword.value)))
|
||||
const spaceCountByOrg = ref<Record<string, number>>({})
|
||||
|
|
@ -1054,21 +1056,28 @@ const spaceKbSectionCounts = computed<Record<KbSectionKey, number>>(() => {
|
|||
return c
|
||||
})
|
||||
|
||||
// Filtered knowledge bases: 全部 = 我的 + 全部共享;我的 = 仅我的
|
||||
//
|
||||
// Favorites / Recents reuse the same render path as `all` — they're just
|
||||
// pre-filtered, pre-ordered slices, so the existing kb-card / shared
|
||||
// kb-card templates render them with zero extra markup. Order is
|
||||
// preserved via the upstream array (pins order is ts-desc).
|
||||
// 收藏、最近、全部和工作空间都使用同一排序选项,同时保持原有分组顺序。
|
||||
const unsearchedFilteredKnowledgeBases = computed(() => {
|
||||
if (spaceSelection.value === 'favorites') {
|
||||
return favoritesList.value
|
||||
return sortResourcesWithinGroups(
|
||||
favoritesList.value,
|
||||
selectedResourceSort.value,
|
||||
kbSectionOf,
|
||||
['pinned', 'mine', 'tenantOthers', 'sharedEditable', 'sharedReadonly'],
|
||||
flatKnowledgeBaseSortAccessors,
|
||||
)
|
||||
}
|
||||
if (spaceSelection.value === 'recents') {
|
||||
return recentsList.value
|
||||
return sortResourcesWithinGroups(
|
||||
recentsList.value,
|
||||
selectedResourceSort.value,
|
||||
kbSectionOf,
|
||||
['pinned', 'mine', 'tenantOthers', 'sharedEditable', 'sharedReadonly'],
|
||||
flatKnowledgeBaseSortAccessors,
|
||||
)
|
||||
}
|
||||
if (spaceSelection.value === 'mine') {
|
||||
return kbs.value.map(kb => ({ ...kb, isMine: true as const }))
|
||||
return sortedMineKbs.value.map(kb => ({ ...kb, isMine: true as const }))
|
||||
}
|
||||
if (spaceSelection.value !== 'all') {
|
||||
return []
|
||||
|
|
@ -1080,11 +1089,18 @@ const unsearchedFilteredKnowledgeBases = computed(() => {
|
|||
// ≥2 entries (#795). mergeAllScopeKnowledgeBases de-duplicates by KB id
|
||||
// (owned wins; most-privileged share kept) while preserving the existing
|
||||
// pinned → mine → teammate → shared(editable-first) ordering.
|
||||
return mergeAllScopeKnowledgeBases(
|
||||
const merged = mergeAllScopeKnowledgeBases(
|
||||
kbs.value as unknown as OwnedKnowledgeBase[],
|
||||
sharedKbs.value as unknown as SharedKnowledgeBaseLike[],
|
||||
authStore.user?.id,
|
||||
) as unknown as Array<(KB & { isMine: true }) | (SharedKnowledgeBase['knowledge_base'] & { isMine: false; permission: string; shared_at: string; share_id: string } & any)>
|
||||
return sortResourcesWithinGroups(
|
||||
merged,
|
||||
selectedResourceSort.value,
|
||||
kbSectionOf,
|
||||
['pinned', 'mine', 'tenantOthers', 'sharedEditable', 'sharedReadonly'],
|
||||
flatKnowledgeBaseSortAccessors,
|
||||
)
|
||||
})
|
||||
const filteredKnowledgeBases = computed(() => unsearchedFilteredKnowledgeBases.value.filter(item => matchesResourceQuery(item, keyword.value)))
|
||||
|
||||
|
|
@ -1602,6 +1618,13 @@ watch(keyword, () => { collapsedKbSections.value = new Set() })
|
|||
line-height: 20px;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.header-action-btn {
|
||||
padding: 0;
|
||||
min-width: 28px;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
DEFAULT_DOCUMENT_SORT,
|
||||
DOCUMENT_SORT_OPTIONS,
|
||||
getDocumentSortOption,
|
||||
getDocumentSortParams,
|
||||
} from './documentSorting';
|
||||
|
||||
test('文档排序默认使用创建时间倒序', () => {
|
||||
assert.equal(DEFAULT_DOCUMENT_SORT, 'created_desc');
|
||||
assert.deepEqual(getDocumentSortParams(DEFAULT_DOCUMENT_SORT), {
|
||||
sort_by: 'created_at',
|
||||
sort_order: 'desc',
|
||||
});
|
||||
});
|
||||
|
||||
test('文档排序提供三组共六个选项并映射到服务端白名单参数', () => {
|
||||
assert.equal(DOCUMENT_SORT_OPTIONS.length, 6);
|
||||
assert.deepEqual(
|
||||
DOCUMENT_SORT_OPTIONS.map(({ value, sortBy, sortOrder }) => [value, sortBy, sortOrder]),
|
||||
[
|
||||
['updated_desc', 'updated_at', 'desc'],
|
||||
['updated_asc', 'updated_at', 'asc'],
|
||||
['created_desc', 'created_at', 'desc'],
|
||||
['created_asc', 'created_at', 'asc'],
|
||||
['name_asc', 'file_name', 'asc'],
|
||||
['name_desc', 'file_name', 'desc'],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('未知排序值会安全回退到默认选项', () => {
|
||||
assert.equal(getDocumentSortOption('invalid' as never).value, DEFAULT_DOCUMENT_SORT);
|
||||
});
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
import type {
|
||||
KnowledgeListSortField,
|
||||
KnowledgeListSortOrder,
|
||||
} from '@/api/knowledge-base';
|
||||
|
||||
export type DocumentSortValue =
|
||||
| 'updated_desc'
|
||||
| 'updated_asc'
|
||||
| 'created_desc'
|
||||
| 'created_asc'
|
||||
| 'name_asc'
|
||||
| 'name_desc';
|
||||
|
||||
export interface DocumentSortOption {
|
||||
value: DocumentSortValue;
|
||||
sortBy: KnowledgeListSortField;
|
||||
sortOrder: KnowledgeListSortOrder;
|
||||
groupKey: 'updatedTime' | 'createdTime' | 'fileName';
|
||||
labelKey:
|
||||
| 'recentlyUpdated'
|
||||
| 'earliestUpdated'
|
||||
| 'newestCreated'
|
||||
| 'earliestCreated'
|
||||
| 'nameAscending'
|
||||
| 'nameDescending';
|
||||
}
|
||||
|
||||
export const DEFAULT_DOCUMENT_SORT: DocumentSortValue = 'created_desc';
|
||||
|
||||
export const DOCUMENT_SORT_OPTIONS: readonly DocumentSortOption[] = [
|
||||
{
|
||||
value: 'updated_desc',
|
||||
sortBy: 'updated_at',
|
||||
sortOrder: 'desc',
|
||||
groupKey: 'updatedTime',
|
||||
labelKey: 'recentlyUpdated',
|
||||
},
|
||||
{
|
||||
value: 'updated_asc',
|
||||
sortBy: 'updated_at',
|
||||
sortOrder: 'asc',
|
||||
groupKey: 'updatedTime',
|
||||
labelKey: 'earliestUpdated',
|
||||
},
|
||||
{
|
||||
value: 'created_desc',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'desc',
|
||||
groupKey: 'createdTime',
|
||||
labelKey: 'newestCreated',
|
||||
},
|
||||
{
|
||||
value: 'created_asc',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'asc',
|
||||
groupKey: 'createdTime',
|
||||
labelKey: 'earliestCreated',
|
||||
},
|
||||
{
|
||||
value: 'name_asc',
|
||||
sortBy: 'file_name',
|
||||
sortOrder: 'asc',
|
||||
groupKey: 'fileName',
|
||||
labelKey: 'nameAscending',
|
||||
},
|
||||
{
|
||||
value: 'name_desc',
|
||||
sortBy: 'file_name',
|
||||
sortOrder: 'desc',
|
||||
groupKey: 'fileName',
|
||||
labelKey: 'nameDescending',
|
||||
},
|
||||
];
|
||||
|
||||
export function getDocumentSortOption(value: DocumentSortValue): DocumentSortOption {
|
||||
return DOCUMENT_SORT_OPTIONS.find((option) => option.value === value)
|
||||
?? DOCUMENT_SORT_OPTIONS.find((option) => option.value === DEFAULT_DOCUMENT_SORT)
|
||||
?? DOCUMENT_SORT_OPTIONS[0];
|
||||
}
|
||||
|
||||
export function getDocumentSortParams(value: DocumentSortValue): {
|
||||
sort_by: KnowledgeListSortField;
|
||||
sort_order: KnowledgeListSortOrder;
|
||||
} {
|
||||
const option = getDocumentSortOption(value);
|
||||
return {
|
||||
sort_by: option.sortBy,
|
||||
sort_order: option.sortOrder,
|
||||
};
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@
|
|||
{{ $t('organization.title') }}
|
||||
</h2>
|
||||
<div class="header-actions" style="--wails-draggable: no-drag">
|
||||
<ResourceSortControl v-model="selectedResourceSort" />
|
||||
<t-tooltip :content="canManageOrg ? $t('organization.joinOrg') : noPermissionTip" placement="bottom">
|
||||
<t-button variant="text" theme="default" size="small" class="header-action-btn"
|
||||
style="--wails-draggable: no-drag" :disabled="!canManageOrg" @click="handleJoinOrganization">
|
||||
|
|
@ -446,7 +447,14 @@ import OrganizationSettingsModal from './OrganizationSettingsModal.vue'
|
|||
import SpaceAvatar from '@/components/SpaceAvatar.vue'
|
||||
import ResourceListToolbar from '@/components/ResourceListToolbar.vue'
|
||||
import { matchesResourceQuery } from '@/utils/resourceListSearch'
|
||||
import ResourceSortControl from '@/components/ResourceSortControl.vue'
|
||||
import { shouldShowOrgRelationTag } from '@/utils/card-list-badge'
|
||||
import {
|
||||
DEFAULT_RESOURCE_SORT,
|
||||
sortResourcesWithinGroups,
|
||||
type ResourceSortAccessors,
|
||||
type ResourceSortValue,
|
||||
} from '@/utils/resourceSorting'
|
||||
|
||||
type OrgWithUI = Organization
|
||||
|
||||
|
|
@ -455,6 +463,13 @@ const route = useRoute()
|
|||
const router = useRouter()
|
||||
const orgStore = useOrganizationStore()
|
||||
const authStore = useAuthStore()
|
||||
const selectedResourceSort = ref<ResourceSortValue>(DEFAULT_RESOURCE_SORT)
|
||||
|
||||
const organizationSortAccessors: ResourceSortAccessors<OrgWithUI> = {
|
||||
getName: organization => organization.name,
|
||||
getUpdatedAt: organization => organization.updated_at,
|
||||
getCreatedAt: organization => organization.created_at,
|
||||
}
|
||||
|
||||
// 后端 /api/v1/organizations 下的写操作(创建、加入、申请加入、邀请、审批、改设置等)
|
||||
// 在路由层都要求当前空间角色 ≥ admin。前端只用于 UI 渲染,安全边界仍在服务端。
|
||||
|
|
@ -666,14 +681,20 @@ const createdCount = computed(() => organizations.value.filter(o => o.is_owner).
|
|||
const joinedCount = computed(() => organizations.value.filter(o => !o.is_owner).length)
|
||||
|
||||
const unsearchedFilteredOrganizations = computed(() => {
|
||||
if (spaceSelection.value === 'created') return organizations.value.filter(o => o.is_owner)
|
||||
if (spaceSelection.value === 'joined') return organizations.value.filter(o => !o.is_owner)
|
||||
// 「全部」视图下把我创建的 owner 排在前面、我加入的排在后面,方便上面的
|
||||
// 分组标题在过渡处一次性打出来——和 KB / Agent 列表口径一致。
|
||||
return [...organizations.value].sort((a, b) => {
|
||||
if (a.is_owner === b.is_owner) return 0
|
||||
return a.is_owner ? -1 : 1
|
||||
})
|
||||
const visibleOrganizations = spaceSelection.value === 'created'
|
||||
? organizations.value.filter(organization => organization.is_owner)
|
||||
: spaceSelection.value === 'joined'
|
||||
? organizations.value.filter(organization => !organization.is_owner)
|
||||
: organizations.value
|
||||
|
||||
// 「全部」仍保持“我创建的 → 我加入的”两段,只在各段内部应用用户选择的顺序。
|
||||
return sortResourcesWithinGroups(
|
||||
visibleOrganizations,
|
||||
selectedResourceSort.value,
|
||||
organization => organization.is_owner ? 'created' : 'joined',
|
||||
['created', 'joined'],
|
||||
organizationSortAccessors,
|
||||
)
|
||||
})
|
||||
const filteredOrganizations = computed(() => unsearchedFilteredOrganizations.value.filter(item => matchesResourceQuery(item, keyword.value)))
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package repository
|
|||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
|
|
@ -195,6 +196,25 @@ func applyKnowledgeListFilter(query *gorm.DB, filter types.KnowledgeListFilter)
|
|||
return query
|
||||
}
|
||||
|
||||
// knowledgeListOrderClause 只从固定白名单生成排序语句,避免将请求参数直接拼入 SQL。
|
||||
func knowledgeListOrderClause(filter types.KnowledgeListFilter) string {
|
||||
// 零值保留仓储层和公开接口原有的创建时间倒序行为。
|
||||
column := "created_at"
|
||||
switch filter.SortBy {
|
||||
case types.KnowledgeListSortByUpdatedAt:
|
||||
column = "updated_at"
|
||||
case types.KnowledgeListSortByFileName:
|
||||
// 与前端展示名称保持一致:文件名为空时依次使用标题和来源。
|
||||
column = "LOWER(COALESCE(NULLIF(file_name, ''), NULLIF(title, ''), source))"
|
||||
}
|
||||
|
||||
direction := "DESC"
|
||||
if filter.SortOrder == types.KnowledgeListSortAscending {
|
||||
direction = "ASC"
|
||||
}
|
||||
return fmt.Sprintf("%s %s", column, direction)
|
||||
}
|
||||
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination
|
||||
func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx context.Context,
|
||||
|
|
@ -218,7 +238,9 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
|
|||
}
|
||||
|
||||
if err := scope(r.db.WithContext(ctx)).
|
||||
Order("created_at DESC").
|
||||
Order(knowledgeListOrderClause(filter)).
|
||||
// 相同排序值使用主键兜底,保证 OFFSET 分页顺序稳定。
|
||||
Order("id ASC").
|
||||
Offset(page.Offset()).
|
||||
Limit(page.Limit()).
|
||||
Find(&knowledges).Error; err != nil {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,160 @@
|
|||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type knowledgeSortSeed struct {
|
||||
id string
|
||||
fileName string
|
||||
title string
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
func insertKnowledgeSortSeed(t *testing.T, db *gorm.DB, seed knowledgeSortSeed) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Exec(`
|
||||
INSERT INTO knowledges
|
||||
(id, tenant_id, knowledge_base_id, type, title, source, file_name, parse_status, created_at, updated_at)
|
||||
VALUES (?, 1, 'kb-sort', 'file', ?, 'manual', ?, 'completed', ?, ?)
|
||||
`, seed.id, seed.title, seed.fileName, seed.createdAt, seed.updatedAt).Error)
|
||||
}
|
||||
|
||||
func knowledgeIDs(rows []*types.Knowledge) []string {
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func TestListPagedKnowledgeSortModes(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
ctx := context.Background()
|
||||
|
||||
jan := time.Date(2024, time.January, 1, 8, 0, 0, 0, time.UTC)
|
||||
feb := time.Date(2024, time.February, 1, 8, 0, 0, 0, time.UTC)
|
||||
mar := time.Date(2024, time.March, 1, 8, 0, 0, 0, time.UTC)
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-a", fileName: "Zulu.txt", title: "Zulu", createdAt: jan, updatedAt: mar,
|
||||
})
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-b", fileName: "alpha.txt", title: "Alpha", createdAt: feb, updatedAt: jan,
|
||||
})
|
||||
// file_name 为空时,名称排序应使用前端同样会展示的 title。
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-c", fileName: "", title: "Bravo note", createdAt: mar, updatedAt: feb,
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
filter types.KnowledgeListFilter
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "更新时间从新到旧",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByUpdatedAt, SortOrder: types.KnowledgeListSortDescending,
|
||||
},
|
||||
want: []string{"doc-a", "doc-c", "doc-b"},
|
||||
},
|
||||
{
|
||||
name: "更新时间从旧到新",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByUpdatedAt, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
want: []string{"doc-b", "doc-c", "doc-a"},
|
||||
},
|
||||
{
|
||||
name: "创建时间从新到旧",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByCreatedAt, SortOrder: types.KnowledgeListSortDescending,
|
||||
},
|
||||
want: []string{"doc-c", "doc-b", "doc-a"},
|
||||
},
|
||||
{
|
||||
name: "创建时间从旧到新",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByCreatedAt, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
want: []string{"doc-a", "doc-b", "doc-c"},
|
||||
},
|
||||
{
|
||||
name: "文件名称从 A 到 Z 且忽略大小写",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByFileName, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
want: []string{"doc-b", "doc-c", "doc-a"},
|
||||
},
|
||||
{
|
||||
name: "文件名称从 Z 到 A 且忽略大小写",
|
||||
filter: types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByFileName, SortOrder: types.KnowledgeListSortDescending,
|
||||
},
|
||||
want: []string{"doc-a", "doc-c", "doc-b"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rows, total, err := repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
ctx,
|
||||
1,
|
||||
"kb-sort",
|
||||
&types.Pagination{Page: 1, PageSize: 100},
|
||||
tt.filter,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(3), total)
|
||||
assert.Equal(t, tt.want, knowledgeIDs(rows))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPagedKnowledgeSortUsesStableIDTieBreaker(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
|
||||
sameTime := time.Date(2024, time.April, 1, 8, 0, 0, 0, time.UTC)
|
||||
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-b", fileName: "same.txt", title: "Same", createdAt: sameTime, updatedAt: sameTime,
|
||||
})
|
||||
insertKnowledgeSortSeed(t, db, knowledgeSortSeed{
|
||||
id: "doc-a", fileName: "same.txt", title: "Same", createdAt: sameTime, updatedAt: sameTime,
|
||||
})
|
||||
|
||||
rows, _, err := repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
context.Background(),
|
||||
1,
|
||||
"kb-sort",
|
||||
&types.Pagination{Page: 1, PageSize: 100},
|
||||
types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByFileName, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"doc-a", "doc-b"}, knowledgeIDs(rows))
|
||||
|
||||
// 每页只取一条,确认相同排序值的文档跨页不会重复或遗漏。
|
||||
for page, wantID := range []string{"doc-a", "doc-b"} {
|
||||
rows, total, err := repo.ListPagedKnowledgeByKnowledgeBaseID(
|
||||
context.Background(), 1, "kb-sort",
|
||||
&types.Pagination{Page: page + 1, PageSize: 1},
|
||||
types.KnowledgeListFilter{
|
||||
SortBy: types.KnowledgeListSortByFileName, SortOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(2), total)
|
||||
assert.Equal(t, []string{wantID}, knowledgeIDs(rows))
|
||||
}
|
||||
}
|
||||
|
|
@ -981,6 +981,8 @@ func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProces
|
|||
// @Param end_time query string false "更新时间终点,RFC3339 格式"
|
||||
// @Param folder_path query string false "文件夹路径筛选,空字符串表示知识库根目录;不传该参数则不按文件夹过滤"
|
||||
// @Param folder_recursive query bool false "为 true 时同时返回子文件夹内的文档"
|
||||
// @Param sort_by query string false "排序字段: updated_at/created_at/file_name,默认 created_at"
|
||||
// @Param sort_order query string false "排序方向: asc/desc,默认 desc"
|
||||
// @Success 200 {object} map[string]interface{} "知识列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
|
|
@ -1015,6 +1017,20 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
|
|||
FileType: c.Query("file_type"),
|
||||
ParseStatus: c.Query("parse_status"),
|
||||
Source: c.Query("source"),
|
||||
SortBy: types.KnowledgeListSortField(
|
||||
c.DefaultQuery("sort_by", string(types.KnowledgeListSortByCreatedAt)),
|
||||
),
|
||||
SortOrder: types.KnowledgeListSortOrder(
|
||||
c.DefaultQuery("sort_order", string(types.KnowledgeListSortDescending)),
|
||||
),
|
||||
}
|
||||
if !filter.SortBy.Valid() {
|
||||
_ = c.Error(errors.NewBadRequestError("invalid sort_by: must be updated_at, created_at, or file_name"))
|
||||
return
|
||||
}
|
||||
if !filter.SortOrder.Valid() {
|
||||
_ = c.Error(errors.NewBadRequestError("invalid sort_order: must be asc or desc"))
|
||||
return
|
||||
}
|
||||
if raw := c.Query("start_time"); raw != "" {
|
||||
t, err := parseFilterTime(raw)
|
||||
|
|
@ -1045,7 +1061,9 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
|
|||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Retrieving knowledge list under knowledge base, kb_id=%s tag_ids=%s keyword=%s file_type=%s parse_status=%s source=%s start_time=%s end_time=%s folder_path=%s folder_scope=%s page=%d page_size=%d effectiveTenantID=%d",
|
||||
"Retrieving knowledge list under knowledge base, kb_id=%s tag_ids=%s keyword=%s file_type=%s "+
|
||||
"parse_status=%s source=%s start_time=%s end_time=%s folder_path=%s folder_scope=%s "+
|
||||
"sort_by=%s sort_order=%s page=%d page_size=%d effectiveTenantID=%d",
|
||||
secutils.SanitizeForLog(kbID),
|
||||
secutils.SanitizeForLog(strings.Join(filter.TagIDs, ",")),
|
||||
secutils.SanitizeForLog(filter.Keyword),
|
||||
|
|
@ -1056,6 +1074,8 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
|
|||
secutils.SanitizeForLog(c.Query("end_time")),
|
||||
secutils.SanitizeForLog(filter.FolderPath),
|
||||
string(filter.FolderScope),
|
||||
string(filter.SortBy),
|
||||
string(filter.SortOrder),
|
||||
pagination.Page,
|
||||
pagination.PageSize,
|
||||
effectiveTenantID,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,78 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestListKnowledgeSortQuery(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
wantCode int
|
||||
wantBy types.KnowledgeListSortField
|
||||
wantOrder types.KnowledgeListSortOrder
|
||||
}{
|
||||
{
|
||||
name: "未传参数时默认最新创建",
|
||||
wantCode: http.StatusOK,
|
||||
wantBy: types.KnowledgeListSortByCreatedAt,
|
||||
wantOrder: types.KnowledgeListSortDescending,
|
||||
},
|
||||
{
|
||||
name: "接受创建时间升序",
|
||||
query: "?sort_by=created_at&sort_order=asc",
|
||||
wantCode: http.StatusOK,
|
||||
wantBy: types.KnowledgeListSortByCreatedAt,
|
||||
wantOrder: types.KnowledgeListSortAscending,
|
||||
},
|
||||
{
|
||||
name: "接受文件名称降序",
|
||||
query: "?sort_by=file_name&sort_order=desc",
|
||||
wantCode: http.StatusOK,
|
||||
wantBy: types.KnowledgeListSortByFileName,
|
||||
wantOrder: types.KnowledgeListSortDescending,
|
||||
},
|
||||
{
|
||||
name: "拒绝未知排序字段",
|
||||
query: "?sort_by=deleted_at&sort_order=desc",
|
||||
wantCode: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "拒绝未知排序方向",
|
||||
query: "?sort_by=updated_at&sort_order=random",
|
||||
wantCode: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "拒绝排序字段中的 SQL 片段",
|
||||
query: "?sort_by=updated_at%3BDELETE%20FROM%20knowledges",
|
||||
wantCode: http.StatusBadRequest,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
kg := &stubFolderKGService{}
|
||||
router := newFolderRouter(kg)
|
||||
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/knowledge"+tt.query, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != tt.wantCode {
|
||||
t.Fatalf("status = %d, want %d; body=%s", w.Code, tt.wantCode, w.Body.String())
|
||||
}
|
||||
if tt.wantCode == http.StatusOK {
|
||||
if kg.gotFilter.SortBy != tt.wantBy {
|
||||
t.Fatalf("sort_by = %q, want %q", kg.gotFilter.SortBy, tt.wantBy)
|
||||
}
|
||||
if kg.gotFilter.SortOrder != tt.wantOrder {
|
||||
t.Fatalf("sort_order = %q, want %q", kg.gotFilter.SortOrder, tt.wantOrder)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -117,6 +117,47 @@ type KnowledgeListFilter struct {
|
|||
// FolderScope selects whether FolderPath matches exactly or includes
|
||||
// descendant folders. FolderScopeAny (the default) ignores folders.
|
||||
FolderScope KnowledgeFolderScope
|
||||
// SortBy 指定列表排序字段;公开列表接口会显式提供默认值。
|
||||
SortBy KnowledgeListSortField
|
||||
// SortOrder 指定升序或降序;零值与 desc 等价。
|
||||
SortOrder KnowledgeListSortOrder
|
||||
}
|
||||
|
||||
// KnowledgeListSortField 是知识文件列表允许使用的排序字段。
|
||||
type KnowledgeListSortField string
|
||||
|
||||
const (
|
||||
// KnowledgeListSortByUpdatedAt 表示按最后更新时间排序。
|
||||
KnowledgeListSortByUpdatedAt KnowledgeListSortField = "updated_at"
|
||||
// KnowledgeListSortByCreatedAt 表示按创建时间排序。
|
||||
KnowledgeListSortByCreatedAt KnowledgeListSortField = "created_at"
|
||||
// KnowledgeListSortByFileName 表示按展示文件名排序。
|
||||
KnowledgeListSortByFileName KnowledgeListSortField = "file_name"
|
||||
)
|
||||
|
||||
// Valid 返回排序字段是否属于公开接口允许的白名单。
|
||||
func (field KnowledgeListSortField) Valid() bool {
|
||||
switch field {
|
||||
case KnowledgeListSortByUpdatedAt, KnowledgeListSortByCreatedAt, KnowledgeListSortByFileName:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// KnowledgeListSortOrder 是知识文件列表允许使用的排序方向。
|
||||
type KnowledgeListSortOrder string
|
||||
|
||||
const (
|
||||
// KnowledgeListSortAscending 表示按升序排列。
|
||||
KnowledgeListSortAscending KnowledgeListSortOrder = "asc"
|
||||
// KnowledgeListSortDescending 表示按降序排列。
|
||||
KnowledgeListSortDescending KnowledgeListSortOrder = "desc"
|
||||
)
|
||||
|
||||
// Valid 返回排序方向是否属于公开接口允许的白名单。
|
||||
func (order KnowledgeListSortOrder) Valid() bool {
|
||||
return order == KnowledgeListSortAscending || order == KnowledgeListSortDescending
|
||||
}
|
||||
|
||||
// Knowledge represents a knowledge entity in the system.
|
||||
|
|
|
|||
|
|
@ -292,6 +292,10 @@ curl -X POST $BASE/api/v1/knowledge-bases/kb-1/knowledge/manual -H "Authorizatio
|
|||
| `parse_status` | string | 否 | `pending/processing/completed/failed` |
|
||||
| `source` | string | 否 | 渠道或 `manual`/`url` |
|
||||
| `start_time` / `end_time` | string | 否 | RFC3339,按 `updated_at` 过滤 |
|
||||
| `sort_by` | string | 否 | 排序字段:`updated_at`、`created_at` 或 `file_name`;默认 `created_at` |
|
||||
| `sort_order` | string | 否 | 排序方向:`asc` 或 `desc`;默认 `desc` |
|
||||
|
||||
未传排序参数时,接口保持原有的 `created_at desc` 行为。显式使用 `updated_at` 时,重新解析、编辑或状态变化会影响顺序;使用 `file_name` 时按展示文件名忽略大小写排序,文件名为空会依次回退到标题和来源。所有排序都会使用知识 ID 作为稳定的次级排序条件,避免相同排序值下翻页结果漂移。
|
||||
|
||||
响应:200 `{"success":true,"data":[Knowledge],"total","page","page_size"}`
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue