Files
syops/frontend/src/views/KbWorkspaceView.vue
T

3145 lines
127 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, FolderPlus, Info, Pencil, RefreshCw, Trash2, Upload, X } from 'lucide-vue-next';
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import {
createKbGroup,
createKbDocument,
createKbPathUploadJob,
deleteKbPathJobFile,
deleteKbGroup,
deleteKbDocument,
getKbDocumentMarkdown,
getKbDocumentSyncRecords,
getKbDocumentVersionSourceFile,
getKbDocumentVersions,
getKbGroupFilesSafe,
getKbGroupsSafe,
getKbJobsSafe,
markKbPathJobFileFailed,
retryFailedKbPathUploadJob,
submitKbDocumentClean,
syncKbDocumentToDify,
uploadKbPathJobFile,
uploadKbDocumentVersion,
updateKbDocumentMarkdown,
updateKbGroup,
type KbDocumentItem,
type KbJob,
type KbDocumentMarkdown,
type KbSyncRecordItem,
type KbDocumentVersionItem,
type KbGroup
} from '../api/kb';
const props = defineProps<{
embedded?: boolean;
}>();
const router = useRouter();
const { t } = useI18n({ useScope: 'global' });
const isLoading = ref(true);
const isDocumentsLoading = ref(false);
const isSubmitting = ref(false);
const isGroupSubmitting = ref(false);
const isRecordLoading = ref(false);
const groups = ref<KbGroup[]>([]);
const documents = ref<KbDocumentItem[]>([]);
const jobs = ref<KbJob[]>([]);
const selectedGroupId = ref<number | null>(null);
const selectedDocumentId = ref<number | null>(null);
const activeUploadDocumentId = ref<number | null>(null);
const syncingDocumentId = ref<number | null>(null);
const selectedDocumentVersions = ref<KbDocumentVersionItem[]>([]);
const selectedDocumentSyncRecords = ref<KbSyncRecordItem[]>([]);
const feedback = ref('');
const feedbackType = ref<'success' | 'error' | ''>('');
const viewMode = ref<'group_overview' | 'group_detail'>(props.embedded ? 'group_overview' : 'group_detail');
const showGroupModal = ref(false);
const showMarkdownModal = ref(false);
const showRecordModal = ref(false);
const showSourceInfoModal = ref(false);
const showFailureModal = ref(false);
const showPathUploadModal = ref(false);
const showPathUploadHistoryModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const showPathUploadDetails = ref(false);
const fileInputRef = ref<HTMLInputElement | null>(null);
const pathUploadInputRef = ref<HTMLInputElement | null>(null);
const editingGroupId = ref<number | null>(null);
const markdownDocumentId = ref<number | null>(null);
const sourceInfoDocumentId = ref<number | null>(null);
const markdownContent = ref('');
const markdownKind = ref<'markdown' | 'preview'>('markdown');
const markdownVersionLabel = ref('');
const markdownError = ref('');
const isMarkdownLoading = ref(false);
const isMarkdownSaving = ref(false);
const isSourceInfoLoading = ref(false);
const openingSourceVersionId = ref<number | null>(null);
const failureModalType = ref<'upload' | 'clean' | 'sync' | null>(null);
const failureModalPage = ref(1);
const retryingFailureKey = ref('');
const documentStageFilter = ref<'all' | 'upload' | 'clean' | 'sync'>('all');
const documentListPage = ref(1);
const documentListPageSize = ref(50);
const batchSubmitting = ref(false);
const selectedDocumentIds = ref<number[]>([]);
const pathUploadDraftText = ref('');
const pathUploadSelectedFiles = ref<Array<{ key: string; file: File; displayPath: string; rootLabel: string }>>([]);
const isPathUploadStaging = ref(false);
const pathUploadJobId = ref<number | string | null>(null);
const selectedPathUploadHistoryJobId = ref<number | string | null>(null);
const selectedPathUploadHistoryItemKeys = ref<string[]>([]);
const retryingPathUploadKey = ref('');
const deletingPathUploadBatch = ref(false);
const groupForm = ref({
name: '',
description: '',
});
const openDeleteConfirmDialog = (
message: string,
onConfirm: () => Promise<void> | void
) => {
console.log('[KB] openDeleteConfirmDialog', message);
deleteConfirmMessage.value = message;
pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true;
console.log('[KB] showDeleteConfirmDialog set to', showDeleteConfirmDialog.value);
};
const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false;
deleteConfirmMessage.value = '';
pendingDeleteAction = null;
};
const handleDeleteConfirm = async () => {
if (!pendingDeleteAction) return;
try {
await pendingDeleteAction();
} catch (err) {
console.error('[deleteConfirm]', err);
feedback.value = String(err) || '操作失败';
feedbackType.value = 'error';
}
closeDeleteConfirmDialog();
};
const selectedDocument = computed(() => documents.value.find((item) => item.id === selectedDocumentId.value) || null);
const sourceInfoDocument = computed(() => documents.value.find((item) => item.id === sourceInfoDocumentId.value) || null);
const selectedGroup = computed(() => groups.value.find((item) => item.id === selectedGroupId.value) || null);
const groupFormTitle = computed(() => editingGroupId.value ? '编辑知识库分组' : '新建知识分组');
const groupSubmitText = computed(() => {
if (isGroupSubmitting.value) return editingGroupId.value ? '保存中...' : '创建中...';
return editingGroupId.value ? '保存修改' : '创建分组';
});
const markdownModalTitle = computed(() => {
const current = documents.value.find((item) => item.id === markdownDocumentId.value);
return current ? getDocumentDisplayTitle(current) : 'Markdown 编辑器';
});
const sourceInfoVersions = ref<KbDocumentVersionItem[]>([]);
const activeGroupJobs = computed(() => jobs.value.filter((item) => item.group_id === selectedGroupId.value));
let autoRefreshTimer: number | null = null;
type WorkflowStageState = {
code: 'pending' | 'running' | 'success' | 'failed' | 'idle';
label: string;
className: string;
errorMessage?: string | null;
};
type FailureModalItem = {
key: string;
document: KbDocumentItem;
stage: 'upload' | 'clean' | 'sync';
stageLabel: string;
errorMessage: string;
latestJob: KbJob | null;
updatedAt?: string | null;
};
type PathUploadStatus = 'queued' | 'uploading' | 'success' | 'failed';
type PathUploadTaskItem = {
key: string;
title: string;
displayPath: string;
rootLabel: string;
status: PathUploadStatus;
error?: string;
documentId?: number;
retryable?: boolean;
startedAt?: string;
finishedAt?: string;
};
type LoadListOptions = {
silent?: boolean;
};
const FAILURE_PAGE_SIZE = 15;
const PATH_UPLOAD_BATCH_SIZE = 30;
const PATH_UPLOAD_BATCH_INTERVAL_MS = 500;
const PATH_UPLOAD_CONCURRENCY = 3;
const DOCUMENT_PAGE_SIZE_OPTIONS = [20, 50, 100, 200] as const;
const pathUploadTask = ref<{
running: boolean;
groupId: number | null;
total: number;
success: number;
failed: number;
currentFile: string;
batchSize: number;
items: PathUploadTaskItem[];
}>({
running: false,
groupId: null,
total: 0,
success: 0,
failed: 0,
currentFile: '',
batchSize: PATH_UPLOAD_BATCH_SIZE,
items: [],
});
let pathUploadPollTimer: number | null = null;
const idleBadgeClass = 'border-default bg-surface-soft text-muted';
const getLatestJobForDocument = (doc: KbDocumentItem, jobType: string): KbJob | null => {
const currentVersionId = doc.latest_version?.id;
const candidates = activeGroupJobs.value.filter((job) => {
if (job.job_type !== jobType || job.document_id !== doc.id) return false;
if (currentVersionId) {
return job.document_version_id === currentVersionId;
}
return true;
});
if (!candidates.length) return null;
return [...candidates].sort((a, b) => {
const aTime = new Date(a.created_at || a.finished_at || a.started_at || 0).getTime();
const bTime = new Date(b.created_at || b.finished_at || b.started_at || 0).getTime();
if (aTime !== bTime) return bTime - aTime;
return Number(b.id) - Number(a.id);
})[0] ?? null;
};
const isUnreadableErrorMessage = (value: string | null | undefined) => {
const text = String(value || '').trim();
if (!text) return true;
const compact = text.replace(/[\s::,,。.!!;;\-_/\\()[\]【】]/g, '');
if (!compact) return true;
return /^[??]+$/.test(compact);
};
const normalizeWorkflowErrorMessage = (
value: string | null | undefined,
stage: 'upload' | 'clean' | 'sync',
) => {
const text = String(value || '').trim();
if (!text) return null;
const upper = text.toUpperCase();
if (isUnreadableErrorMessage(text)) {
if (stage === 'clean') {
return '历史失败任务原因不可读,请重新点击“清洗数据”发起清洗';
}
if (stage === 'sync') {
return '历史同步失败原因不可读,请重新发起同步';
}
return '历史上传失败原因不可读,请重新上传文件';
}
if (upper.includes('LEGACY_CLEAN_TASK_RECOVERED_MANUALLY')) {
return '历史遗留清洗任务已人工回收,请重新点击“清洗数据”发起清洗';
}
if (upper.includes('JOB_TIMEOUT_RECOVERED')) {
return '后台任务执行超时,系统已自动回收,请重新发起';
}
if (upper.includes('CLEAN_SOURCE_MISSING')) {
return '原始文件不存在,请重新上传后再清洗';
}
if (upper.includes('CLEAN_VERSION_MISSING')) {
return '关联版本不存在,请重新上传后再试';
}
if (upper.includes('CLEAN_TIMEOUT') || /file processing timed out|timed out after/i.test(text)) {
return '文件清洗超时,请稍后重试;若多次失败,请检查源文件是否损坏';
}
return text;
};
const getDocumentWorkflowState = (doc: KbDocumentItem) => {
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
const uploadJob = getLatestJobForDocument(doc, 'upload');
const cleanJob = getLatestJobForDocument(doc, 'clean');
const syncJob = getLatestJobForDocument(doc, 'sync_dify');
const uploadStage: WorkflowStageState = !doc.latest_version
? { code: 'pending', label: '待上传', className: getStatusBadgeClass('draft') }
: uploadJob?.status === 'failed'
? {
code: 'failed',
label: '失败',
className: getStatusBadgeClass('failed'),
errorMessage: normalizeWorkflowErrorMessage(uploadJob.error_message || uploadJob.message, 'upload'),
}
: { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
let cleanStage: WorkflowStageState;
if (!doc.latest_version) {
cleanStage = { code: 'idle', label: '未开始', className: idleBadgeClass };
} else if (cleanJob?.status === 'failed' || latestStatus === 'failed') {
cleanStage = {
code: 'failed',
label: '失败',
className: getStatusBadgeClass('failed'),
errorMessage: normalizeWorkflowErrorMessage(
cleanJob?.error_message || doc.latest_version?.error_message || cleanJob?.message || null,
'clean',
),
};
} else if (['cleaned', 'ready', 'syncing', 'synced'].includes(latestStatus)) {
cleanStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
} else if (['running', 'queued'].includes(String(cleanJob?.status || '').toLowerCase()) || latestStatus === 'processing') {
cleanStage = {
code: 'running',
label: latestStatus === 'processing' ? '清洗中' : '待清洗',
className: getStatusBadgeClass(latestStatus === 'processing' ? 'processing' : 'uploaded'),
};
} else if (latestStatus === 'uploaded') {
cleanStage = { code: 'pending', label: '待清洗', className: getStatusBadgeClass('uploaded') };
} else {
cleanStage = { code: 'idle', label: '未开始', className: idleBadgeClass };
}
let syncStage: WorkflowStageState;
if (!doc.latest_version || cleanStage.code === 'failed') {
syncStage = { code: 'idle', label: '未开始', className: idleBadgeClass };
} else if (syncJob?.status === 'failed') {
syncStage = {
code: 'failed',
label: '失败',
className: getStatusBadgeClass('failed'),
errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync'),
};
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
syncStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
} else if (['running', 'queued'].includes(String(syncJob?.status || '').toLowerCase()) || latestStatus === 'syncing') {
syncStage = {
code: 'running',
label: latestStatus === 'syncing' ? '同步中' : '待同步',
className: getStatusBadgeClass(latestStatus === 'syncing' ? 'processing' : 'uploaded'),
};
} else if (['cleaned', 'ready'].includes(latestStatus)) {
syncStage = { code: 'pending', label: '待同步', className: getStatusBadgeClass('uploaded') };
} else {
syncStage = { code: 'idle', label: '未开始', className: idleBadgeClass };
}
const primaryError =
syncStage.errorMessage ||
cleanStage.errorMessage ||
uploadStage.errorMessage ||
normalizeWorkflowErrorMessage(doc.latest_version?.error_message, 'clean') ||
null;
return {
upload: uploadStage,
clean: cleanStage,
sync: syncStage,
primaryError,
};
};
const groupSummaryItems = computed(() => {
const docItems = documents.value;
const groupName = selectedGroup.value?.name || '--';
const workflowStates = docItems.map((item) => getDocumentWorkflowState(item));
const pendingSyncCount = workflowStates.filter((item) => item.sync.code === 'pending').length;
const uploadFailedCount = workflowStates.filter((item) => item.upload.code === 'failed').length;
const cleanFailedCount = workflowStates.filter((item) => item.clean.code === 'failed').length;
const syncFailedCount = workflowStates.filter((item) => item.sync.code === 'failed').length;
return [
{ label: '当前知识库分组', value: groupName, wide: true, clickable: false },
{ label: '文档数量', value: String(docItems.length), wide: false, clickable: false },
{ label: '待同步数量', value: String(pendingSyncCount), wide: false, clickable: false },
{ label: '上传失败数量', value: String(uploadFailedCount), wide: false, clickable: uploadFailedCount > 0, failureType: 'upload' as const },
{ label: '清洗失败数量', value: String(cleanFailedCount), wide: false, clickable: cleanFailedCount > 0, failureType: 'clean' as const },
{ label: '同步失败数量', value: String(syncFailedCount), wide: false, clickable: syncFailedCount > 0, failureType: 'sync' as const },
];
});
const matchesDocumentStageFilter = (
doc: KbDocumentItem,
filter: 'all' | 'upload' | 'clean' | 'sync',
) => {
const workflow = getDocumentWorkflowState(doc);
if (filter === 'all') return true;
if (filter === 'upload') {
return workflow.upload.code !== 'success';
}
if (filter === 'clean') {
return ['pending', 'running', 'failed'].includes(workflow.clean.code);
}
return ['pending', 'running', 'failed'].includes(workflow.sync.code);
};
const stageFilterTabs = computed(() => {
const filters: Array<{ key: 'all' | 'upload' | 'clean' | 'sync'; label: string }> = [
{ key: 'all', label: '全部' },
{ key: 'upload', label: '上传' },
{ key: 'clean', label: '清洗' },
{ key: 'sync', label: '同步' },
];
return filters.map((item) => ({
...item,
count: documents.value.filter((doc) => matchesDocumentStageFilter(doc, item.key)).length,
}));
});
const filteredDocuments = computed(() =>
documents.value.filter((doc) => matchesDocumentStageFilter(doc, documentStageFilter.value))
);
const filteredDocumentTotalPages = computed(() =>
Math.max(1, Math.ceil(filteredDocuments.value.length / documentListPageSize.value))
);
const pagedFilteredDocuments = computed(() => {
const start = (documentListPage.value - 1) * documentListPageSize.value;
return filteredDocuments.value.slice(start, start + documentListPageSize.value);
});
const pagedDocumentRange = computed(() => {
if (filteredDocuments.value.length === 0) {
return { start: 0, end: 0 };
}
const start = (documentListPage.value - 1) * documentListPageSize.value + 1;
const end = Math.min(filteredDocuments.value.length, documentListPage.value * documentListPageSize.value);
return { start, end };
});
const selectedDocuments = computed(() =>
documents.value.filter((doc) => selectedDocumentIds.value.includes(doc.id))
);
const selectedCleanableDocuments = computed(() =>
selectedDocuments.value.filter((doc) => {
if (!doc.latest_version) return false;
const workflow = getDocumentWorkflowState(doc);
return ['failed', 'pending', 'idle'].includes(workflow.clean.code);
})
);
const isAllFilteredSelected = computed(() =>
filteredDocuments.value.length > 0
&& filteredDocuments.value.every((doc) => selectedDocumentIds.value.includes(doc.id))
);
const failureModalItems = computed<FailureModalItem[]>(() => {
if (!failureModalType.value) return [];
return documents.value.flatMap<FailureModalItem>((doc) => {
const workflow = getDocumentWorkflowState(doc);
if (failureModalType.value === 'clean' && workflow.clean.code === 'failed') {
const item: FailureModalItem = {
key: `${doc.id}-clean`,
document: doc,
stage: 'clean',
stageLabel: '清洗失败',
errorMessage: workflow.clean.errorMessage || workflow.primaryError || '清洗失败',
latestJob: getLatestJobForDocument(doc, 'clean'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
};
return [item];
}
if (failureModalType.value === 'sync' && workflow.sync.code === 'failed') {
const item: FailureModalItem = {
key: `${doc.id}-sync`,
document: doc,
stage: 'sync',
stageLabel: '同步失败',
errorMessage: workflow.sync.errorMessage || workflow.primaryError || '同步失败',
latestJob: getLatestJobForDocument(doc, 'sync_dify'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
};
return [item];
}
if (failureModalType.value === 'upload' && workflow.upload.code === 'failed') {
const item: FailureModalItem = {
key: `${doc.id}-upload`,
document: doc,
stage: 'upload',
stageLabel: '上传失败',
errorMessage: workflow.upload.errorMessage || workflow.primaryError || '上传失败',
latestJob: getLatestJobForDocument(doc, 'upload'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
};
return [item];
}
return [];
});
});
const failureModalTotalPages = computed(() =>
Math.max(1, Math.ceil(failureModalItems.value.length / FAILURE_PAGE_SIZE))
);
const pagedFailureModalItems = computed(() => {
const start = (failureModalPage.value - 1) * FAILURE_PAGE_SIZE;
return failureModalItems.value.slice(start, start + FAILURE_PAGE_SIZE);
});
const failureModalTitle = computed(() => {
const map = {
upload: '上传失败数据',
clean: '清洗失败数据',
sync: '同步失败数据',
};
return failureModalType.value ? map[failureModalType.value] : '失败数据';
});
const documentById = computed(() =>
new Map(documents.value.map((doc) => [doc.id, doc]))
);
const getPathUploadJobProgress = (job: KbJob | null) => {
const payload = job?.payload_json || {};
const result = job?.result_json || {};
const success = Number(result.success || 0);
const failed = Number(result.failed || 0);
const processed = Number(result.processed || success + failed || 0);
const total = Number(result.total || payload.total_files || 0);
return { total, success, failed, processed };
};
const getPathUploadJobPriority = (job: KbJob) => {
const normalizedStatus = String(job.status || '').toLowerCase();
const { processed, success, failed } = getPathUploadJobProgress(job);
const hasProgress = processed > 0 || success > 0 || failed > 0 || Boolean(job.started_at) || Boolean(job.finished_at);
const statusScore = normalizedStatus === 'running'
? 50
: normalizedStatus === 'success'
? 40
: normalizedStatus === 'failed'
? 35
: ['queued', 'staging', 'draft'].includes(normalizedStatus)
? 20
: 0;
return (hasProgress ? 1000 : 0) + statusScore;
};
const latestPathUploadJob = computed(() => {
const pathJobs = activeGroupJobs.value.filter((job) => job.job_type === 'path_upload');
if (!pathJobs.length) return null;
return [...pathJobs].sort((a, b) => {
const priorityDiff = getPathUploadJobPriority(b) - getPathUploadJobPriority(a);
if (priorityDiff !== 0) return priorityDiff;
const aTime = new Date(a.created_at || a.finished_at || a.started_at || 0).getTime();
const bTime = new Date(b.created_at || b.finished_at || b.started_at || 0).getTime();
if (aTime !== bTime) return bTime - aTime;
return Number(b.id) - Number(a.id);
})[0] ?? null;
});
const pathUploadHistoryJobs = computed(() =>
[...activeGroupJobs.value]
.filter((job) => job.job_type === 'path_upload')
.sort((a, b) => {
const aTime = new Date(a.created_at || a.finished_at || a.started_at || 0).getTime();
const bTime = new Date(b.created_at || b.finished_at || b.started_at || 0).getTime();
return bTime - aTime;
})
);
const selectedPathUploadHistoryJob = computed(() =>
pathUploadHistoryJobs.value.find((job) => String(job.id) === String(selectedPathUploadHistoryJobId.value))
|| latestPathUploadJob.value
|| null
);
const selectedPathUploadHistoryItems = computed(() =>
getPathUploadJobItems(selectedPathUploadHistoryJob.value)
);
const selectedPathUploadHistorySelectedItems = computed(() => {
const selectedKeySet = new Set(selectedPathUploadHistoryItemKeys.value);
return selectedPathUploadHistoryItems.value.filter((item) => selectedKeySet.has(item.key));
});
const isAllPathUploadHistoryItemsSelected = computed(() =>
selectedPathUploadHistoryItems.value.length > 0
&& selectedPathUploadHistoryItems.value.every((item) => selectedPathUploadHistoryItemKeys.value.includes(item.key))
);
const getPathUploadItemDisplayState = (item: PathUploadTaskItem) => {
if (item.status === 'failed') {
return {
normalized: 'failed',
label: '失败',
className: getStatusBadgeClass('failed'),
};
}
const doc = item.documentId ? documentById.value.get(item.documentId) || null : null;
const latestStatus = String(doc?.latest_version?.status || doc?.status || '').toLowerCase();
if (latestStatus === 'processing') {
return {
normalized: 'processing',
label: '清洗中',
className: getStatusBadgeClass('processing'),
};
}
if (['cleaned', 'ready'].includes(latestStatus)) {
return {
normalized: latestStatus,
label: '已清洗',
className: getStatusBadgeClass(latestStatus),
};
}
if (latestStatus === 'syncing') {
return {
normalized: 'syncing',
label: '同步中',
className: getStatusBadgeClass('processing'),
};
}
if (latestStatus === 'synced') {
return {
normalized: 'synced',
label: '已同步',
className: getStatusBadgeClass('synced'),
};
}
if (latestStatus === 'uploaded') {
return {
normalized: 'uploaded',
label: '待清洗',
className: getStatusBadgeClass('uploaded'),
};
}
if (item.status === 'success' || item.documentId) {
return {
normalized: 'success',
label: '已上传',
className: getStatusBadgeClass('success'),
};
}
if (item.status === 'uploading') {
return {
normalized: 'uploading',
label: '上传中',
className: getStatusBadgeClass('processing'),
};
}
return {
normalized: 'queued',
label: '待上传',
className: getStatusBadgeClass('queued'),
};
};
const pathUploadSummary = computed(() => {
const task = pathUploadTask.value;
const displayedStates = task.items.map((item) => getPathUploadItemDisplayState(item).normalized);
const queued = displayedStates.filter((status) => status === 'queued').length;
const uploading = displayedStates.filter((status) => status === 'uploading').length;
const failed = displayedStates.filter((status) => status === 'failed').length;
const uploaded = Math.max(task.total - queued - uploading - failed, 0);
return {
total: task.total,
pending: queued + uploading,
uploaded,
failed,
queued,
uploading,
};
});
const recentPathUploadItems = computed(() =>
[...pathUploadTask.value.items]
.sort((a, b) => {
const aTime = new Date(a.finishedAt || a.startedAt || 0).getTime();
const bTime = new Date(b.finishedAt || b.startedAt || 0).getTime();
return bTime - aTime;
})
.slice(0, 30)
);
const pathUploadRunning = computed(() =>
isPathUploadStaging.value
|| ['draft', 'staging', 'queued', 'running'].includes(String(latestPathUploadJob.value?.status || '').toLowerCase())
);
const kbJobPollingActive = computed(() =>
pathUploadRunning.value
|| activeGroupJobs.value.some((job) =>
['clean', 'sync_dify'].includes(String(job.job_type || '').toLowerCase())
&& ['queued', 'running'].includes(String(job.status || '').toLowerCase())
)
);
const selectedPathRoots = computed(() => {
const roots = new Set(pathUploadSelectedFiles.value.map((item) => item.rootLabel));
return Array.from(roots);
});
const mergeStableItems = <T extends { id: number | string }>(current: T[], incoming: T[]) => {
const incomingMap = new Map(incoming.map((item) => [String(item.id), item] as const));
const next: T[] = [];
const seen = new Set<string>();
current.forEach((item) => {
const key = String(item.id);
const incomingItem = incomingMap.get(key);
if (!incomingItem) return;
next.push(incomingItem);
seen.add(key);
});
incoming.forEach((item) => {
const key = String(item.id);
if (seen.has(key)) return;
next.push(item);
});
return next;
};
const loadGroups = async (options: LoadListOptions = {}) => {
if (!options.silent) {
isLoading.value = true;
}
try {
const result = await getKbGroupsSafe();
if (!result.ok) {
feedback.value = result.error || '加载知识库分组失败';
feedbackType.value = 'error';
return;
}
groups.value = options.silent ? mergeStableItems(groups.value, result.data) : result.data;
const firstGroup = groups.value[0];
if (!selectedGroupId.value && firstGroup && viewMode.value === 'group_detail') {
selectedGroupId.value = firstGroup.id;
}
} finally {
if (!options.silent) {
isLoading.value = false;
}
}
};
const loadJobs = async () => {
const hadActiveKbJobs = kbJobPollingActive.value;
const result = await getKbJobsSafe();
if (!result.ok) {
feedback.value = result.error || '加载任务列表失败';
feedbackType.value = 'error';
return;
}
jobs.value = result.data;
applyPathUploadJob(latestPathUploadJob.value);
if (latestPathUploadJob.value && getPathUploadJobSummary(latestPathUploadJob.value).failed > 0) {
showPathUploadDetails.value = true;
}
if (selectedPathUploadHistoryJobId.value && !pathUploadHistoryJobs.value.some((job) => String(job.id) === String(selectedPathUploadHistoryJobId.value))) {
selectedPathUploadHistoryJobId.value = latestPathUploadJob.value?.id || null;
}
if (kbJobPollingActive.value) {
startPathUploadPolling();
} else {
stopPathUploadPollTimer();
if (hadActiveKbJobs && viewMode.value === 'group_detail') {
await Promise.all([
loadDocuments(selectedGroupId.value, { silent: true }),
loadGroups({ silent: true }),
]);
}
}
};
const refreshWorkflowStatusOnly = async () => {
await Promise.all([
loadJobs(),
loadGroups({ silent: true }),
loadDocuments(selectedGroupId.value, { silent: true }),
]);
};
const refreshCurrentView = async () => {
if (viewMode.value === 'group_overview') {
await Promise.all([loadGroups(), loadJobs()]);
return;
}
await Promise.all([loadDocuments(selectedGroupId.value), loadJobs()]);
};
const startAutoRefresh = () => {
if (autoRefreshTimer !== null) {
window.clearInterval(autoRefreshTimer);
}
autoRefreshTimer = window.setInterval(() => {
void refreshCurrentView();
}, 120000);
};
const stopAutoRefresh = () => {
if (autoRefreshTimer !== null) {
window.clearInterval(autoRefreshTimer);
autoRefreshTimer = null;
}
};
const formatDateTime = (value?: string | null) => {
if (!value) return '--';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const pad = (n: number) => String(n).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};
const formatFileSize = (value?: number | null) => {
const size = Number(value || 0);
if (!Number.isFinite(size) || size <= 0) return '0 B';
if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`;
return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
};
const trimPathText = (value?: string | null) => {
const text = String(value || '').trim();
if (!text) return '';
return text.split(/[\\/]/).filter(Boolean).pop() || text;
};
const getDocumentDisplayTitle = (doc: KbDocumentItem) => trimPathText(doc.title) || '未命名文档';
const getDocumentDisplayDescription = (doc: KbDocumentItem) => {
const text = trimPathText(doc.description);
return text || getDocumentDisplayTitle(doc);
};
const normalizeDuplicateDocumentError = (message?: string | null) => {
const text = String(message || '').trim();
if (!text) return '知识库接口请求失败';
if (text.includes('当前分组下已存在同名文档') || text.includes('上传失败,文件已存在')) {
return '上传失败,文件已存在';
}
return text;
};
const getStatusLabel = (status?: string | null) => {
const normalized = String(status || '').toLowerCase();
const map: Record<string, string> = {
draft: '待上传',
uploaded: '已上传',
processing: '清洗中',
cleaned: '已清洗',
ready: '已就绪',
synced: '已同步',
syncing: '同步中',
failed: '失败',
queued: '排队中',
running: '进行中',
success: '成功',
cancelled: '已取消',
};
return map[normalized] || status || '未知状态';
};
const getStatusBadgeClass = (status?: string | null) => {
const normalized = String(status || '').toLowerCase();
if (['cleaned', 'ready', 'synced', 'success'].includes(normalized)) {
return 'border-emerald-200 bg-emerald-50 text-emerald-700';
}
if (['processing', 'running'].includes(normalized)) {
return 'border-amber-200 bg-amber-50 text-amber-700';
}
if (['uploaded', 'queued', 'draft'].includes(normalized)) {
return 'border-sky-200 bg-sky-50 text-sky-700';
}
if (normalized === 'failed') {
return 'border-rose-200 bg-rose-50 text-rose-700';
}
if (normalized === 'cancelled') {
return 'border-default bg-surface-soft text-secondary';
}
return 'border-default bg-surface-soft text-secondary';
};
const getWorkflowBadges = (doc: KbDocumentItem) => {
const workflow = getDocumentWorkflowState(doc);
return [
{ label: '上传', value: workflow.upload.label, className: workflow.upload.className },
{ label: '清洗', value: workflow.clean.label, className: workflow.clean.className },
{ label: '同步', value: workflow.sync.label, className: workflow.sync.className },
];
};
const getMarkdownUnavailableMessage = (
doc: KbDocumentItem,
fallback?: string | null,
) => {
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
const normalizedReason = normalizeWorkflowErrorMessage(
doc.latest_version?.error_message,
'clean',
);
if (latestStatus === 'failed') {
return normalizedReason
? `当前文档清洗失败,尚未生成 Markdown。失败原因:${normalizedReason}`
: '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试';
}
if (latestStatus === 'processing') {
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试';
}
if (latestStatus === 'uploaded') {
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗';
}
return fallback || '当前文档尚未生成 Markdown';
};
const resetGroupForm = () => {
editingGroupId.value = null;
groupForm.value = {
name: '',
description: '',
};
};
const openCreateGroupModal = () => {
resetGroupForm();
feedback.value = '';
feedbackType.value = '';
showGroupModal.value = true;
};
const closeGroupModal = () => {
showGroupModal.value = false;
};
const openGroupDetail = async (groupId: number) => {
selectedGroupId.value = groupId;
viewMode.value = 'group_detail';
feedback.value = '';
feedbackType.value = '';
await loadDocuments(groupId);
};
const backToGroupOverview = () => {
viewMode.value = 'group_overview';
selectedGroupId.value = null;
documents.value = [];
selectedDocumentId.value = null;
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
};
const handleEditGroup = (group: KbGroup) => {
editingGroupId.value = group.id;
groupForm.value = {
name: group.name,
description: group.description || '',
};
feedback.value = '';
feedbackType.value = '';
showGroupModal.value = true;
};
const handleSubmitGroup = async () => {
if (!groupForm.value.name.trim()) {
feedback.value = '请输入知识库分组名称';
feedbackType.value = 'error';
return;
}
isGroupSubmitting.value = true;
const payload = {
name: groupForm.value.name.trim(),
description: groupForm.value.description.trim(),
};
const result = editingGroupId.value
? await updateKbGroup(editingGroupId.value, payload)
: await createKbGroup(payload);
isGroupSubmitting.value = false;
if (!result.ok) {
feedback.value = result.error || '分组保存失败';
feedbackType.value = 'error';
return;
}
feedback.value = editingGroupId.value ? '分组已更新' : '分组已创建';
feedbackType.value = 'success';
showGroupModal.value = false;
resetGroupForm();
await loadGroups();
};
const handleDeleteGroup = async (group: KbGroup) => {
openDeleteConfirmDialog(`确认删除分组「${group.name}」吗?`, async () => {
const result = await deleteKbGroup(group.id);
if (!result.ok) {
feedback.value = result.error || '删除分组失败';
feedbackType.value = 'error';
return;
}
if (editingGroupId.value === group.id) {
resetGroupForm();
}
feedback.value = '分组已删除';
feedbackType.value = 'success';
await loadGroups();
await loadJobs();
});
};
const loadDocuments = async (groupId: number | null, options: LoadListOptions = {}) => {
if (!options.silent) {
isDocumentsLoading.value = true;
}
try {
if (!groupId) {
documents.value = [];
selectedDocumentId.value = null;
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
return;
}
const result = await getKbGroupFilesSafe(groupId);
if (!result.ok) {
feedback.value = result.error || '加载文档列表失败';
feedbackType.value = 'error';
return;
}
const nextDocuments = options.silent
? mergeStableItems(documents.value, result.data)
: result.data;
documents.value = nextDocuments;
if (selectedDocumentId.value && !documents.value.some((item) => item.id === selectedDocumentId.value)) {
selectedDocumentId.value = null;
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
showRecordModal.value = false;
}
if (sourceInfoDocumentId.value && !documents.value.some((item) => item.id === sourceInfoDocumentId.value)) {
sourceInfoDocumentId.value = null;
sourceInfoVersions.value = [];
showSourceInfoModal.value = false;
}
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => documents.value.some((item) => item.id === id));
} finally {
if (!options.silent) {
isDocumentsLoading.value = false;
}
}
};
const loadDocumentVersions = async (documentId: number | null) => {
if (!documentId) {
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
return;
}
selectedDocumentVersions.value = await getKbDocumentVersions(documentId);
selectedDocumentSyncRecords.value = await getKbDocumentSyncRecords(documentId);
};
const loadSourceInfoVersions = async (documentId: number | null) => {
if (!documentId) {
sourceInfoVersions.value = [];
return;
}
sourceInfoVersions.value = await getKbDocumentVersions(documentId);
};
const openDocumentDetail = async (documentId: number) => {
selectedDocumentId.value = documentId;
isRecordLoading.value = true;
showRecordModal.value = true;
await loadDocumentVersions(documentId);
isRecordLoading.value = false;
};
const closeDocumentDetail = () => {
showRecordModal.value = false;
};
const openSourceInfo = async (doc: KbDocumentItem) => {
sourceInfoDocumentId.value = doc.id;
isSourceInfoLoading.value = true;
showSourceInfoModal.value = true;
await loadSourceInfoVersions(doc.id);
isSourceInfoLoading.value = false;
};
const closeSourceInfoModal = () => {
showSourceInfoModal.value = false;
};
const openOriginalSourceFile = async (version: KbDocumentVersionItem) => {
openingSourceVersionId.value = version.id;
const result = await getKbDocumentVersionSourceFile(version.id);
openingSourceVersionId.value = null;
if (!result.ok || !result.blob) {
feedback.value = result.error || '读取原始文件失败';
feedbackType.value = 'error';
return;
}
const objectUrl = window.URL.createObjectURL(result.blob);
const opened = window.open(objectUrl, '_blank', 'noopener,noreferrer');
if (!opened) {
const link = document.createElement('a');
link.href = objectUrl;
link.download = result.filename || version.source_file_name || `source-${version.id}`;
link.click();
}
window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 60_000);
};
const openFailureModal = (type: 'upload' | 'clean' | 'sync') => {
failureModalType.value = type;
failureModalPage.value = 1;
showFailureModal.value = true;
};
const closeFailureModal = () => {
showFailureModal.value = false;
failureModalType.value = null;
failureModalPage.value = 1;
retryingFailureKey.value = '';
};
const resetPathUploadDraft = () => {
pathUploadDraftText.value = '';
pathUploadSelectedFiles.value = [];
};
const openPathUploadModal = () => {
if (pathUploadRunning.value) {
feedback.value = '有文件正在上传请稍等再试~';
feedbackType.value = 'error';
return;
}
resetPathUploadDraft();
showPathUploadModal.value = true;
};
const closePathUploadModal = () => {
if (pathUploadRunning.value) return;
showPathUploadModal.value = false;
resetPathUploadDraft();
};
const triggerPathUploadSelection = () => {
pathUploadInputRef.value?.click();
};
const handlePathFilesSelected = (event: Event) => {
const input = event.target as HTMLInputElement;
const files = Array.from(input.files || []);
if (!files.length) {
input.value = '';
return;
}
const existing = new Set(pathUploadSelectedFiles.value.map((item) => item.displayPath));
const nextItems = files.flatMap((file, index) => {
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
if (existing.has(relativePath)) return [];
const rootLabel = relativePath.includes('/') ? relativePath.split('/')[0] || file.name : file.name;
return [{
key: `${Date.now()}-${index}-${relativePath}`,
file,
displayPath: relativePath,
rootLabel,
}];
});
pathUploadSelectedFiles.value = [...pathUploadSelectedFiles.value, ...nextItems];
pathUploadDraftText.value = pathUploadSelectedFiles.value.map((item) => item.displayPath).join('\n');
input.value = '';
};
const removeSelectedPathFile = (key: string) => {
pathUploadSelectedFiles.value = pathUploadSelectedFiles.value.filter((item) => item.key !== key);
pathUploadDraftText.value = pathUploadSelectedFiles.value.map((item) => item.displayPath).join('\n');
};
const stopPathUploadPollTimer = () => {
if (pathUploadPollTimer !== null) {
window.clearInterval(pathUploadPollTimer);
pathUploadPollTimer = null;
}
};
const wait = (ms: number) => new Promise((resolve) => {
window.setTimeout(resolve, ms);
});
const updatePathUploadFeedback = () => {
const summary = pathUploadSummary.value;
if (!pathUploadTask.value.total) return;
feedback.value = `路径上传进度:总计 ${summary.total} 条,待上传 ${summary.pending} 条,已上传 ${summary.uploaded} 条,失败 ${summary.failed} 条`;
feedbackType.value = summary.failed > 0 ? 'error' : 'success';
};
const getPathUploadJobItems = (job: KbJob | null): PathUploadTaskItem[] => {
if (!job || job.job_type !== 'path_upload') return [];
const payload = job.payload_json || {};
const files = Array.isArray(payload.files) ? payload.files : [];
const failedCount = files.filter((item: any) => String(item?.status || '').toLowerCase() === 'failed').length;
return files.map((item: any, index: number) => ({
key: `${job.id}-${item.relative_path || item.original_name || index}`,
title: String(item.original_name || item.relative_path || `文件${index + 1}`),
displayPath: String(item.relative_path || item.original_name || ''),
rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status)) ? item.status : 'queued') as PathUploadStatus,
error: item.error
|| (String(item.status || '').toLowerCase() === 'failed' && failedCount === 1
? (job.error_message || job.message || '上传失败')
: undefined),
documentId: item.document_id || undefined,
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
startedAt: undefined,
finishedAt: undefined,
}));
};
const hasRetryablePathUploadFailure = (job: KbJob | null) =>
getPathUploadJobItems(job).some((item) => item.retryable);
const getPathUploadJobSummary = (job: KbJob | null) => {
const items = getPathUploadJobItems(job);
const total = Number(job?.payload_json?.total_files || job?.result_json?.total || items.length || 0);
const success = Number(job?.result_json?.success || items.filter((item) => item.status === 'success').length || 0);
const failed = Number(job?.result_json?.failed || items.filter((item) => item.status === 'failed').length || 0);
const pending = Math.max(total - success - failed, 0);
return { total, success, failed, pending };
};
const applyPathUploadJob = (job: KbJob | null) => {
if (!job || job.job_type !== 'path_upload') {
if (!isPathUploadStaging.value) {
pathUploadTask.value = {
running: false,
groupId: selectedGroupId.value,
total: 0,
success: 0,
failed: 0,
currentFile: '',
batchSize: PATH_UPLOAD_BATCH_SIZE,
items: [],
};
}
return;
}
const payload = job.payload_json || {};
const result = job.result_json || {};
const items = Array.isArray(payload.files)
? payload.files.map((item: any, index: number) => ({
key: String(item.relative_path || item.original_name || index),
title: String(item.original_name || item.relative_path || `文件${index + 1}`),
displayPath: String(item.relative_path || item.original_name || ''),
rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status)) ? item.status : 'queued') as PathUploadStatus,
error: item.error || undefined,
documentId: item.document_id || undefined,
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
}))
: [];
pathUploadJobId.value = job.id;
pathUploadTask.value = {
running: ['draft', 'staging', 'queued', 'running'].includes(String(job.status || '').toLowerCase()) || isPathUploadStaging.value,
groupId: job.group_id ? Number(job.group_id) : selectedGroupId.value,
total: Number(payload.total_files || result.total || items.length || 0),
success: Number(result.success || items.filter((item) => item.status === 'success').length || 0),
failed: Number(result.failed || items.filter((item) => item.status === 'failed').length || 0),
currentFile: String(payload.current_file || ''),
batchSize: PATH_UPLOAD_BATCH_SIZE,
items,
};
updatePathUploadFeedback();
};
const openPathUploadHistoryModal = (jobId?: number | string | null) => {
selectedPathUploadHistoryJobId.value = jobId || latestPathUploadJob.value?.id || pathUploadHistoryJobs.value[0]?.id || null;
showPathUploadHistoryModal.value = true;
};
const closePathUploadHistoryModal = () => {
showPathUploadHistoryModal.value = false;
selectedPathUploadHistoryJobId.value = null;
selectedPathUploadHistoryItemKeys.value = [];
};
const togglePathUploadHistoryItemSelection = (itemKey: string) => {
if (selectedPathUploadHistoryItemKeys.value.includes(itemKey)) {
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => key !== itemKey);
return;
}
selectedPathUploadHistoryItemKeys.value = [...selectedPathUploadHistoryItemKeys.value, itemKey];
};
const toggleSelectAllPathUploadHistoryItems = () => {
if (isAllPathUploadHistoryItemsSelected.value) {
selectedPathUploadHistoryItemKeys.value = [];
return;
}
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItems.value.map((item) => item.key);
};
const startPathUploadPolling = () => {
stopPathUploadPollTimer();
pathUploadPollTimer = window.setInterval(() => {
if (!kbJobPollingActive.value) {
stopPathUploadPollTimer();
return;
}
void Promise.all([
loadJobs(),
loadDocuments(selectedGroupId.value, { silent: true }),
loadGroups({ silent: true }),
]);
}, 3000);
};
const handleConfirmPathUpload = async () => {
if (pathUploadRunning.value) {
feedback.value = '有文件正在上传请稍等再试~';
feedbackType.value = 'error';
return;
}
if (!selectedGroupId.value) {
feedback.value = '请先选择知识库分组';
feedbackType.value = 'error';
return;
}
if (!pathUploadSelectedFiles.value.length) {
feedback.value = '请先选择至少一个本地目录或文件';
feedbackType.value = 'error';
return;
}
isPathUploadStaging.value = true;
const createResult = await createKbPathUploadJob(selectedGroupId.value, {
total_files: pathUploadSelectedFiles.value.length,
selected_paths: selectedPathRoots.value,
files: pathUploadSelectedFiles.value.map((item) => ({
relative_path: item.displayPath,
original_name: item.file.name,
})),
});
if (!createResult.ok || !createResult.job) {
feedback.value = createResult.error || '创建上传路径任务失败';
feedbackType.value = 'error';
isPathUploadStaging.value = false;
return;
}
const createdJob = createResult.job;
const existingJobItems = getPathUploadJobItems(createdJob);
const existingItemMap = new Map(existingJobItems.map((item) => [item.displayPath, item]));
const selectedPathSet = new Set(pathUploadSelectedFiles.value.map((item) => item.displayPath));
const pendingFiles = pathUploadSelectedFiles.value.filter((item) => {
const existingItem = existingItemMap.get(item.displayPath);
return !existingItem || existingItem.status !== 'success';
});
pathUploadJobId.value = createdJob.id;
showPathUploadDetails.value = false;
pathUploadTask.value = {
running: true,
groupId: selectedGroupId.value,
total: Number(createdJob.payload_json?.total_files || existingJobItems.length || pathUploadSelectedFiles.value.length),
success: Number(createdJob.result_json?.success || existingJobItems.filter((item) => item.status === 'success').length || 0),
failed: Number(createdJob.result_json?.failed || existingJobItems.filter((item) => item.status === 'failed').length || 0),
currentFile: String(createdJob.payload_json?.current_file || ''),
batchSize: PATH_UPLOAD_BATCH_SIZE,
items: [
...pathUploadSelectedFiles.value.map((item) => {
const existingItem = existingItemMap.get(item.displayPath);
return {
key: item.key,
title: item.file.name,
displayPath: item.displayPath,
rootLabel: item.rootLabel,
status: existingItem?.status || 'queued',
error: existingItem?.error,
documentId: existingItem?.documentId,
retryable: existingItem?.retryable,
} satisfies PathUploadTaskItem;
}),
...existingJobItems.filter((item) => !selectedPathSet.has(item.displayPath)),
],
};
updatePathUploadFeedback();
showPathUploadModal.value = false;
const stageSinglePathUploadFile = async (item: { key: string; file: File; displayPath: string; rootLabel: string }) => {
pathUploadTask.value.currentFile = item.displayPath;
const localItem = pathUploadTask.value.items.find((candidate) => candidate.key === item.key);
if (localItem) {
localItem.status = 'uploading';
}
const stageResult = await uploadKbPathJobFile(createdJob.id, item.file, item.displayPath);
if (!stageResult.ok) {
const errorMessage = normalizeDuplicateDocumentError(stageResult.error || '路径文件暂存失败');
const failedResult = await markKbPathJobFileFailed(createdJob.id, {
relative_path: item.displayPath,
original_name: item.file.name,
error: errorMessage,
});
if (failedResult.ok && failedResult.job) {
applyPathUploadJob(failedResult.job);
} else if (localItem) {
localItem.status = 'failed';
localItem.error = errorMessage;
updatePathUploadFeedback();
}
return;
}
if (stageResult.job) {
applyPathUploadJob(stageResult.job);
} else if (localItem) {
localItem.status = 'success';
localItem.error = undefined;
updatePathUploadFeedback();
}
await Promise.all([loadDocuments(selectedGroupId.value, { silent: true }), loadJobs()]);
};
const files = [...pendingFiles];
for (let batchStart = 0; batchStart < files.length; batchStart += PATH_UPLOAD_BATCH_SIZE) {
const batch = files.slice(batchStart, batchStart + PATH_UPLOAD_BATCH_SIZE);
for (let i = 0; i < batch.length; i += PATH_UPLOAD_CONCURRENCY) {
const chunk = batch.slice(i, i + PATH_UPLOAD_CONCURRENCY);
await Promise.all(chunk.map((item) => stageSinglePathUploadFile(item)));
}
if (batchStart + PATH_UPLOAD_BATCH_SIZE < files.length) {
await wait(PATH_UPLOAD_BATCH_INTERVAL_MS);
}
}
isPathUploadStaging.value = false;
pathUploadTask.value.currentFile = '';
feedback.value = '路径文件已逐个上传并提交清洗';
feedbackType.value = 'success';
startPathUploadPolling();
resetPathUploadDraft();
await refreshWorkflowStatusOnly();
};
const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTaskItem) => {
if (!job) return;
openDeleteConfirmDialog(`确认删除路径文件「${item.displayPath || item.title}」吗?`, async () => {
const result = await deleteKbPathJobFile(job.id, item.displayPath);
if (!result.ok) {
feedback.value = result.error || '删除路径上传文件失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.document_deleted ? '已删除路径记录,并同步删除对应文档' : '已删除路径记录';
feedbackType.value = 'success';
if (pathUploadTask.value.items.length <= 1) {
showPathUploadDetails.value = false;
}
await refreshWorkflowStatusOnly();
});
};
const handleBatchDeletePathUploadItems = async () => {
const job = selectedPathUploadHistoryJob.value;
const items = selectedPathUploadHistorySelectedItems.value;
if (!job || !items.length) {
feedback.value = '请先选择要删除的文件';
feedbackType.value = 'error';
return;
}
openDeleteConfirmDialog(`确认批量删除已选中的 ${items.length} 条路径文件吗?`, async () => {
deletingPathUploadBatch.value = true;
let successCount = 0;
let failCount = 0;
const errors: string[] = [];
try {
for (const item of items) {
const result = await deleteKbPathJobFile(job.id, item.displayPath);
if (result.ok) {
successCount += 1;
continue;
}
failCount += 1;
errors.push(`${item.displayPath}: ${result.error || '删除失败'}`);
}
feedback.value = failCount
? `批量删除完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量删除完成:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
selectedPathUploadHistoryItemKeys.value = [];
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
} finally {
deletingPathUploadBatch.value = false;
}
});
};
const handleRetryFailedPathUpload = async (
job: KbJob | null,
relativePaths?: string[],
) => {
if (!job) return;
const key = `${job.id}:${(relativePaths || []).join('|') || 'all'}`;
retryingPathUploadKey.value = key;
const result = await retryFailedKbPathUploadJob(job.id, relativePaths?.length ? { relative_paths: relativePaths } : {});
retryingPathUploadKey.value = '';
if (!result.ok || !result.job) {
feedback.value = result.error || '重试失败文件失败';
feedbackType.value = 'error';
return;
}
applyPathUploadJob(result.job);
startPathUploadPolling();
feedback.value = relativePaths?.length === 1 ? '已重新提交该失败文件' : '已重新提交失败文件';
feedbackType.value = 'success';
await refreshWorkflowStatusOnly();
};
const toggleDocumentSelection = (documentId: number) => {
if (selectedDocumentIds.value.includes(documentId)) {
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => id !== documentId);
return;
}
selectedDocumentIds.value = [...selectedDocumentIds.value, documentId];
};
const toggleSelectAllFiltered = () => {
if (isAllFilteredSelected.value) {
const filteredIds = new Set(filteredDocuments.value.map((doc) => doc.id));
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => !filteredIds.has(id));
return;
}
const merged = new Set(selectedDocumentIds.value);
filteredDocuments.value.forEach((doc) => merged.add(doc.id));
selectedDocumentIds.value = Array.from(merged);
};
const handleDeleteDocument = async (doc: KbDocumentItem) => {
console.log('[KB] handleDeleteDocument called', doc.id, doc.title);
openDeleteConfirmDialog(`确认删除文档「${getDocumentDisplayTitle(doc)}」吗?`, async () => {
const result = await deleteKbDocument(doc.id);
if (!result.ok) {
feedback.value = result.error || '删除文档失败';
feedbackType.value = 'error';
return;
}
if (selectedDocumentId.value === doc.id) {
selectedDocumentId.value = null;
showRecordModal.value = false;
}
feedback.value = '文档已删除';
feedbackType.value = 'success';
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
});
};
const handleBatchSync = async () => {
if (!selectedDocuments.value.length) {
feedback.value = '请先选择要批量同步的文档';
feedbackType.value = 'error';
return;
}
batchSubmitting.value = true;
try {
const results = await Promise.all(
selectedDocuments.value.map(async (doc) => ({
doc,
result: await syncKbDocumentToDify(doc.id),
}))
);
const successCount = results.filter(({ result }) => result.ok).length;
const failResults = results.filter(({ result }) => !result.ok);
const failCount = failResults.length;
const errors = failResults.map(({ doc, result }) => `${getDocumentDisplayTitle(doc)}: ${result.error || '同步失败'}`);
feedback.value = failCount
? `批量同步任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量同步任务已提交:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
if (successCount > 0) {
startPathUploadPolling();
}
await refreshWorkflowStatusOnly();
} finally {
batchSubmitting.value = false;
}
};
const handleBatchClean = async () => {
if (!selectedDocuments.value.length) {
feedback.value = '请先选择要清洗的文档';
feedbackType.value = 'error';
return;
}
if (!selectedCleanableDocuments.value.length) {
feedback.value = '当前所选文档没有可重新清洗的项';
feedbackType.value = 'error';
return;
}
batchSubmitting.value = true;
try {
const results = await Promise.all(
selectedCleanableDocuments.value.map(async (doc) => ({
doc,
result: await submitKbDocumentClean(doc.id),
}))
);
const successCount = results.filter(({ result }) => result.ok).length;
const failResults = results.filter(({ result }) => !result.ok);
const failCount = failResults.length;
const errors = failResults.map(({ doc, result }) => `${getDocumentDisplayTitle(doc)}: ${result.error || '提交清洗失败'}`);
feedback.value = failCount
? `批量清洗任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量清洗任务已提交:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
if (successCount > 0) {
startPathUploadPolling();
}
await refreshWorkflowStatusOnly();
} finally {
batchSubmitting.value = false;
}
};
const handleBatchDelete = async () => {
console.log('[KB] handleBatchDelete called, selected:', selectedDocuments.value.length);
if (!selectedDocuments.value.length) {
feedback.value = '请先选择要批量删除的文档';
feedbackType.value = 'error';
return;
}
openDeleteConfirmDialog(
`确认批量删除已选中的 ${selectedDocuments.value.length} 条文档吗?会同步删除 Dify 对应文档。`,
async () => {
batchSubmitting.value = true;
let successCount = 0;
let failCount = 0;
const errors: string[] = [];
try {
for (const doc of selectedDocuments.value) {
const result = await deleteKbDocument(doc.id);
if (result.ok) {
successCount += 1;
} else {
failCount += 1;
errors.push(`${getDocumentDisplayTitle(doc)}: ${result.error || '删除失败'}`);
}
}
feedback.value = failCount
? `批量删除完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量删除完成:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
selectedDocumentIds.value = [];
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
} finally {
batchSubmitting.value = false;
}
}
);
};
const handleRetryFailedItem = async (
item: FailureModalItem,
action: 'submit' | 'clean' | 'sync',
) => {
const actionKey = `${item.key}-${action}`;
retryingFailureKey.value = actionKey;
try {
if (action === 'submit') {
triggerUploadForDocument(item.document.id);
feedback.value = `请重新为「${getDocumentDisplayTitle(item.document)}」选择文件后提交`;
feedbackType.value = 'success';
return;
}
if (action === 'clean') {
const result = await submitKbDocumentClean(item.document.id);
if (!result.ok) {
feedback.value = result.error || '重新清洗失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.message || `已重新提交清洗:${getDocumentDisplayTitle(item.document)}`;
feedbackType.value = 'success';
startPathUploadPolling();
} else {
const result = await syncKbDocumentToDify(item.document.id);
if (!result.ok) {
feedback.value = result.error ? `重新同步失败:${result.error}` : '重新同步失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.job?.message || `已重新提交同步:${getDocumentDisplayTitle(item.document)}`;
feedbackType.value = 'success';
startPathUploadPolling();
}
await refreshWorkflowStatusOnly();
if (selectedDocumentId.value) {
await loadDocumentVersions(selectedDocumentId.value);
}
if (failureModalPage.value > failureModalTotalPages.value) {
failureModalPage.value = failureModalTotalPages.value;
}
} finally {
retryingFailureKey.value = '';
}
};
const triggerUploadForDocument = (documentId: number) => {
activeUploadDocumentId.value = documentId;
fileInputRef.value?.click();
};
const handleFileSelected = async (event: Event) => {
const input = event.target as HTMLInputElement;
const files = input.files;
if (!files || files.length === 0 || !selectedGroupId.value) {
input.value = '';
activeUploadDocumentId.value = null;
return;
}
isSubmitting.value = true;
feedback.value = '开始处理文件...';
feedbackType.value = 'success';
if (activeUploadDocumentId.value) {
const file = files[0];
if (!file) return;
const result = await uploadKbDocumentVersion(activeUploadDocumentId.value, file);
if (!result.ok) {
feedback.value = result.error || '文件上传失败';
feedbackType.value = 'error';
} else {
feedback.value = result.message || `版本文件「${file.name}」上传成功,清洗已排队`;
feedbackType.value = 'success';
startPathUploadPolling();
}
selectedDocumentId.value = activeUploadDocumentId.value;
activeUploadDocumentId.value = null;
} else {
let successCount = 0;
let failCount = 0;
const errors: string[] = [];
const fileArray = Array.from(files);
for (let i = 0; i < fileArray.length; i++) {
const file = fileArray[i];
if (!file) continue;
feedback.value = `正在上传 ${i + 1}/${fileArray.length}: ${file.name}`;
const createResult = await createKbDocument(selectedGroupId.value, {
title: file.name,
description: file.name,
});
if (!createResult.ok || !createResult.document) {
failCount++;
errors.push(`${file.name}: ${normalizeDuplicateDocumentError(createResult.error || '创建文档失败')}`);
continue;
}
const uploadResult = await uploadKbDocumentVersion(createResult.document.id, file);
if (!uploadResult.ok) {
failCount++;
const uploadError = uploadResult.error || '上传文档版本失败';
errors.push(`${file.name}: ${uploadError}`);
const cleanupResult = await deleteKbDocument(createResult.document.id);
if (!cleanupResult.ok) {
errors.push(`${file.name}: 上传失败后未能自动清理空文档(${cleanupResult.error || '删除失败'})`);
}
} else {
successCount++;
}
}
if (failCount > 0) {
feedback.value = `上传完成:成功 ${successCount} 个,失败 ${failCount} 个。${errors[0] || ''}`;
feedbackType.value = successCount > 0 ? 'success' : 'error';
} else {
feedback.value = `成功上传 ${successCount} 个文件,清洗任务已排队`;
feedbackType.value = 'success';
}
if (successCount > 0) {
startPathUploadPolling();
}
}
input.value = '';
isSubmitting.value = false;
await refreshWorkflowStatusOnly();
if (selectedDocumentId.value) {
await loadDocumentVersions(selectedDocumentId.value);
}
};
const triggerMultiUpload = () => {
activeUploadDocumentId.value = null;
fileInputRef.value?.click();
};
const handleSyncDocument = async (documentId: number) => {
syncingDocumentId.value = documentId;
const result = await syncKbDocumentToDify(documentId);
syncingDocumentId.value = null;
if (!result.ok) {
feedback.value = result.error ? `同步到 Dify 失败:${result.error}` : '同步到 Dify 失败';
feedbackType.value = 'error';
await loadDocuments(selectedGroupId.value, { silent: true });
await loadJobs();
return;
}
feedback.value = result.job?.message || '同步任务已提交,等待后台处理';
feedbackType.value = 'success';
startPathUploadPolling();
await loadDocuments(selectedGroupId.value, { silent: true });
await loadJobs();
selectedDocumentId.value = documentId;
await loadDocumentVersions(documentId);
};
const applyMarkdownPayload = (payload: KbDocumentMarkdown) => {
markdownContent.value = payload.content || '';
markdownKind.value = payload.kind;
markdownVersionLabel.value = payload.version
? `v${payload.version.version_no} · ${payload.version.source_file_name}`
: '暂无版本';
};
const openMarkdownEditor = async (doc: KbDocumentItem) => {
showMarkdownModal.value = true;
markdownDocumentId.value = doc.id;
markdownContent.value = '';
markdownKind.value = 'markdown';
markdownVersionLabel.value = '';
markdownError.value = '';
isMarkdownLoading.value = true;
const result = await getKbDocumentMarkdown(doc.id);
isMarkdownLoading.value = false;
if (!result.ok || !result.data) {
markdownError.value = getMarkdownUnavailableMessage(doc, result.error || '读取清洗后的 Markdown 失败');
return;
}
applyMarkdownPayload(result.data);
};
const closeMarkdownModal = () => {
if (isMarkdownSaving.value) return;
showMarkdownModal.value = false;
markdownDocumentId.value = null;
markdownContent.value = '';
markdownVersionLabel.value = '';
markdownError.value = '';
isMarkdownLoading.value = false;
};
const handleSaveMarkdown = async () => {
if (!markdownDocumentId.value) return;
isMarkdownSaving.value = true;
markdownError.value = '';
const result = await updateKbDocumentMarkdown(markdownDocumentId.value, {
content: markdownContent.value,
});
isMarkdownSaving.value = false;
if (!result.ok || !result.data) {
const currentDoc = documents.value.find((item) => item.id === markdownDocumentId.value) || null;
markdownError.value = currentDoc
? getMarkdownUnavailableMessage(currentDoc, result.error || '保存 Markdown 失败')
: (result.error || '保存 Markdown 失败');
return;
}
applyMarkdownPayload(result.data);
feedback.value = '清洗后的 Markdown 已保存';
feedbackType.value = 'success';
await loadDocuments(selectedGroupId.value);
await loadJobs();
selectedDocumentId.value = markdownDocumentId.value;
await loadDocumentVersions(markdownDocumentId.value);
closeMarkdownModal();
};
watch(selectedGroupId, (groupId) => {
feedback.value = '';
feedbackType.value = '';
documentListPage.value = 1;
selectedDocumentId.value = null;
selectedDocumentIds.value = [];
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
void loadDocuments(groupId);
applyPathUploadJob(latestPathUploadJob.value);
});
watch(documentStageFilter, () => {
documentListPage.value = 1;
});
watch(documentListPageSize, () => {
documentListPage.value = 1;
});
watch(filteredDocumentTotalPages, (totalPages) => {
if (documentListPage.value > totalPages) {
documentListPage.value = totalPages;
}
});
watch(selectedPathUploadHistoryJob, (job) => {
const validKeys = new Set(getPathUploadJobItems(job).map((item) => item.key));
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => validKeys.has(key));
if (!job) {
selectedPathUploadHistoryItemKeys.value = [];
}
});
onMounted(async () => {
await Promise.all([loadGroups(), loadJobs()]);
if (viewMode.value === 'group_detail') {
await loadDocuments(selectedGroupId.value);
}
startAutoRefresh();
});
onUnmounted(() => {
stopAutoRefresh();
stopPathUploadPollTimer();
});
</script>
<template>
<div :class="!embedded ? 'page-shell min-h-screen' : 'text-secondary'">
<div :class="!embedded ? 'mx-auto max-w-7xl page-shell-mobile py-6' : ''">
<div class="card mb-6 flex flex-col gap-4 p-6 md:flex-row md:items-center md:justify-between">
<div class="flex items-start gap-4">
<button
v-if="!embedded || (embedded && viewMode === 'group_detail')"
@click="embedded ? backToGroupOverview() : router.push('/workspace')"
class="kb-ws-icon-btn"
:title="embedded ? t('kbWorkspace.actions.backToOverview') : t('kbWorkspace.actions.backToWorkspace')"
>
<ArrowLeft class="h-5 w-5" />
</button>
<div>
<div class="flex items-center gap-3">
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 ">
<BookOpen class="h-6 w-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-primary">
{{ viewMode === 'group_overview' ? t('kbWorkspace.header.groupOverviewTitle') : t('kbWorkspace.header.workspaceTitle') }}
</h1>
<p class="mt-1 text-sm text-muted">
{{ viewMode === 'group_overview' ? t('kbWorkspace.header.groupOverviewSubtitle') : t('kbWorkspace.header.workspaceSubtitle') }}
</p>
</div>
</div>
</div>
</div>
<div class="flex flex-wrap items-center gap-3">
<button
@click="refreshCurrentView"
class="btn-secondary"
>
<RefreshCw class="h-4 w-4" />
{{ viewMode === 'group_overview' ? t('kbWorkspace.actions.refreshGroups') : t('kbWorkspace.actions.refreshDocuments') }}
</button>
</div>
</div>
<template v-if="viewMode === 'group_overview'">
<section class="kb-ws-section">
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold text-primary">{{ t('kbWorkspace.overview.title') }}</h2>
<span class="text-xs text-muted">`/api/kb/groups`</span>
</div>
<div v-if="isLoading" class="py-10 text-center text-sm text-muted">{{ t('kbWorkspace.overview.loadingGroups') }}</div>
<div v-else class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3 auto-rows-fr">
<div class="kb-ws-card">
<div class="mb-3 flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-xl bg-brand-50 text-brand-600">
<FolderPlus class="h-4 w-4" />
</div>
<div class="font-semibold text-primary">{{ t('kbWorkspace.overview.createGroupTitle') }}</div>
</div>
<div class="text-sm text-muted">{{ t('kbWorkspace.overview.createGroupDesc') }}</div>
<div class="mt-auto pt-3">
<button
@click="openCreateGroupModal"
class="btn-primary btn-sm w-full"
>
<FolderPlus class="h-4 w-4" />
{{ t('kbWorkspace.overview.createGroupButton') }}
</button>
<p
v-if="feedback"
class="text-xs"
:class="feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600'"
>
{{ feedback }}
</p>
</div>
</div>
<div
v-for="group in groups"
:key="group.id"
@click="openGroupDetail(group.id)"
class="kb-ws-card--interactive"
>
<div class="w-full text-left">
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="text-xl font-bold leading-tight text-primary break-words">{{ group.name }}</div>
<div class="mt-1 text-sm text-muted">{{ group.description || '暂无描述' }}</div>
</div>
<div class="rounded-full bg-surface-soft px-2.5 py-1 text-xs font-medium text-secondary whitespace-nowrap">
{{ group.document_count ?? 0 }} 文档
</div>
</div>
<div class="mt-4 text-xs text-muted">更新时间:{{ formatDateTime(group.updated_at) }}</div>
</div>
<div class="mt-auto pt-3 flex items-center gap-2">
<button
@click.stop="handleEditGroup(group)"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-2 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
<Pencil class="h-3.5 w-3.5" />
编辑
</button>
<button
@click.stop="handleDeleteGroup(group)"
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 border-rose-200 hover:bg-rose-50"
>
<Trash2 class="h-3.5 w-3.5" />
删除
</button>
</div>
</div>
</div>
</section>
</template>
<template v-else>
<div class="kb-ws-stat-grid">
<div
v-for="item in groupSummaryItems"
:key="item.label"
class="kb-ws-stat-tile "
:class="[
item.wide ? 'col-span-2 xl:col-span-2' : '',
item.clickable
? 'cursor-pointer hover:bg-rose-50 hover:bg-rose-50'
: '',
]"
@click="item.clickable && item.failureType ? openFailureModal(item.failureType) : undefined"
>
<div
class="text-base font-semibold text-primary break-words"
:style="item.wide ? '-webkit-line-clamp: 2; -webkit-box-orient: vertical; display: -webkit-box; overflow: hidden;' : undefined"
>
{{ item.value }}
</div>
<div class="mt-1 text-xs text-muted">{{ item.label }}</div>
</div>
</div>
<div class="grid grid-cols-1 gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
<input
ref="fileInputRef"
type="file"
multiple
class="hidden"
@change="handleFileSelected"
/>
<input
ref="pathUploadInputRef"
type="file"
multiple
webkitdirectory
directory
class="hidden"
@change="handlePathFilesSelected"
/>
<section class="kb-ws-section">
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold text-primary">分组列表</h2>
<span class="text-xs text-muted">接口壳已接入</span>
</div>
<div v-if="isLoading" class="py-10 text-center text-sm text-muted">正在加载分组...</div>
<div v-else-if="groups.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-8 text-center text-sm text-muted ">
暂无知识库分组。后续接通 `/api/kb/groups` 后将在这里显示真实数据。
</div>
<div v-else class="space-y-3">
<button
v-for="group in groups"
:key="group.id"
@click="selectedGroupId = group.id"
class="kb-ws-group-list-btn"
:class="{ 'kb-ws-group-list-btn--active': selectedGroupId === group.id }"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate font-semibold">{{ group.name }}</div>
<div class="mt-1 text-sm opacity-80">{{ group.description || '暂无描述' }}</div>
</div>
<span class="rounded-full bg-surface/70 px-2 py-1 text-xs ">
{{ group.document_count ?? 0 }}
</span>
</div>
</button>
</div>
</section>
<section class="space-y-6">
<div class="kb-ws-section">
<div class="mb-4 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-2">
<h2 class="text-lg font-semibold text-primary">文档列表</h2>
<div class="group relative">
<button
type="button"
class="inline-flex h-6 w-6 items-center justify-center rounded-full border border-default text-muted transition-colors hover:border-brand-300 hover:text-brand-500 hover:border-brand-300 hover:text-brand-600"
>
<Info class="h-3.5 w-3.5" />
</button>
<div class="pointer-events-none absolute left-0 top-8 z-10 hidden w-80 rounded-2xl border border-default bg-surface px-4 py-3 text-sm text-muted shadow-xl group-hover:block">
当前分组下的基础文档条目,上传文件后将自动创建文档并开始清洗流程。
</div>
</div>
</div>
<div class="flex flex-wrap items-center gap-3">
<button
v-if="selectedGroupId"
@click="openPathUploadModal"
:disabled="pathUploadRunning"
class="inline-flex items-center gap-2 rounded-2xl border border-brand-200 px-4 py-2.5 text-sm font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 border-brand-200 hover:bg-brand-50"
>
<Upload class="h-4 w-4" />
上传路径
</button>
<button
v-if="selectedGroupId"
@click="triggerMultiUpload"
:disabled="isSubmitting"
class="btn-primary"
>
<Upload class="h-4 w-4" />
上传文件
</button>
</div>
</div>
<div class="flex flex-wrap items-center gap-3">
<button
v-if="selectedGroupId"
@click="handleBatchClean"
:disabled="batchSubmitting || selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-2xl border border-amber-200 px-4 py-2.5 text-sm font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60"
>
<RefreshCw class="h-4 w-4" />
{{ batchSubmitting ? '处理中...' : `清洗数据${selectedDocuments.length ? `(${selectedDocuments.length})` : ''}` }}
</button>
<button
v-if="selectedGroupId"
@click="handleBatchSync"
:disabled="batchSubmitting || selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-2xl border border-emerald-200 px-4 py-2.5 text-sm font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60 border-emerald-200"
>
<RefreshCw class="h-4 w-4" />
{{ batchSubmitting ? '处理中...' : `批量同步${selectedDocuments.length ? `(${selectedDocuments.length})` : ''}` }}
</button>
<button
v-if="selectedGroupId"
@click="handleBatchDelete"
:disabled="batchSubmitting || selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-2xl border border-rose-200 px-4 py-2.5 text-sm font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
<Trash2 class="h-4 w-4" />
{{ batchSubmitting ? '处理中...' : `批量删除${selectedDocuments.length ? `(${selectedDocuments.length})` : ''}` }}
</button>
<button
v-if="selectedGroupId"
@click="openPathUploadHistoryModal()"
class="btn-secondary"
>
<FileText class="h-4 w-4" />
历史批次
</button>
</div>
</div>
<p
v-if="feedback"
class="mb-4 text-sm"
:class="feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600'"
>
{{ feedback }}
</p>
<div
v-if="pathUploadTask.total"
class="mb-4 rounded-2xl border border-default bg-surface-soft p-4"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<div class="text-sm font-semibold text-primary">
路径上传进度
<span
class="ml-2 inline-flex items-center rounded-full border px-2.5 py-1 text-xs"
:class="pathUploadRunning
? 'border-amber-200 bg-amber-50 text-amber-700 border-amber-200'
: 'border-emerald-200 bg-emerald-50 text-emerald-700 border-emerald-200 '"
>
{{ pathUploadRunning ? '上传中' : '已完成' }}
</span>
</div>
<div class="mt-1 text-sm text-muted">
建议每批 {{ pathUploadTask.batchSize }} 条,间隔 {{ PATH_UPLOAD_BATCH_INTERVAL_MS / 1000 }} 秒自动继续。
</div>
</div>
<div class="grid grid-cols-2 gap-2 text-sm text-secondary md:grid-cols-4">
<div>总计 {{ pathUploadSummary.total }}</div>
<div>待上传 {{ pathUploadSummary.pending }}</div>
<div>已上传 {{ pathUploadSummary.uploaded }}</div>
<div>失败 {{ pathUploadSummary.failed }}</div>
</div>
</div>
<div v-if="pathUploadTask.currentFile" class="mt-3 text-sm text-brand-600 ">
当前文件:{{ pathUploadTask.currentFile }}
</div>
<div class="mt-4 space-y-2">
<div class="flex flex-wrap items-center justify-between gap-2">
<button
type="button"
@click="showPathUploadDetails = !showPathUploadDetails"
class="inline-flex items-center gap-2 text-sm font-medium text-secondary transition-colors hover:text-brand-600 hover:text-brand-600"
>
<span>上传详情</span>
<ChevronDown v-if="!showPathUploadDetails" class="h-4 w-4" />
<ChevronUp v-else class="h-4 w-4" />
</button>
<div class="flex items-center gap-2">
<button
@click="openPathUploadHistoryModal(latestPathUploadJob?.id || null)"
class="inline-flex items-center rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
查看历史
</button>
<button
v-if="latestPathUploadJob && hasRetryablePathUploadFailure(latestPathUploadJob) && !pathUploadRunning"
@click="handleRetryFailedPathUpload(latestPathUploadJob)"
:disabled="retryingPathUploadKey === `${latestPathUploadJob.id}:all`"
class="inline-flex items-center rounded-xl border border-rose-200 px-3 py-1.5 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
{{ retryingPathUploadKey === `${latestPathUploadJob.id}:all` ? '处理中...' : '重试失败文件' }}
</button>
</div>
</div>
<div v-if="showPathUploadDetails" class="max-h-72 space-y-2 overflow-y-auto pr-1">
<div
v-for="item in recentPathUploadItems"
:key="item.key"
class="flex flex-wrap items-start justify-between gap-3 rounded-xl border border-default bg-surface px-3 py-3 text-sm"
>
<div class="min-w-0 flex-1">
<div class="truncate font-medium text-primary">{{ item.title }}</div>
<div class="mt-1 truncate text-xs text-muted">{{ item.displayPath }}</div>
<div v-if="item.error" class="mt-1 text-xs text-rose-500">失败原因:{{ item.error }}</div>
</div>
<div class="flex items-center gap-2">
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="getPathUploadItemDisplayState(item).className"
>
{{ getPathUploadItemDisplayState(item).label }}
</span>
<button
v-if="item.retryable && latestPathUploadJob && !pathUploadRunning"
@click="handleRetryFailedPathUpload(latestPathUploadJob, [item.displayPath])"
:disabled="retryingPathUploadKey === `${latestPathUploadJob.id}:${item.displayPath}`"
class="inline-flex items-center rounded-xl border border-rose-200 px-2.5 py-1 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
{{ retryingPathUploadKey === `${latestPathUploadJob.id}:${item.displayPath}` ? '处理中...' : '重试' }}
</button>
<button
v-if="latestPathUploadJob && !pathUploadRunning"
@click="handleDeletePathUploadItem(latestPathUploadJob, item)"
class="inline-flex items-center rounded-xl border border-default px-2.5 py-1 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
删除
</button>
</div>
</div>
</div>
</div>
</div>
<div
v-if="selectedGroupId"
class="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-surface-soft px-4 py-3 "
>
<div class="flex flex-wrap items-center gap-2">
<button
@click="toggleSelectAllFiltered"
class="inline-flex items-center gap-2 rounded-full border border-default bg-surface px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
{{ isAllFilteredSelected ? '取消全选' : '全选当前筛选' }}
</button>
<button
v-for="tab in stageFilterTabs"
:key="tab.key"
@click="documentStageFilter = tab.key"
class="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition-colors"
:class="documentStageFilter === tab.key
? 'border-brand-200 bg-brand-50 text-brand-700 border-brand-200 '
: 'border-default bg-surface text-secondary hover:bg-surface-soft hover-surface-soft'"
>
<span>{{ tab.label }}</span>
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs ">{{ tab.count }}</span>
</button>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
<label class="inline-flex items-center gap-2">
<span>每页</span>
<select
v-model.number="documentListPageSize"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary outline-none transition-colors focus:border-brand-300"
>
<option v-for="size in DOCUMENT_PAGE_SIZE_OPTIONS" :key="size" :value="size">{{ size }}</option>
</select>
<span>条</span>
</label>
<span>已选 {{ selectedDocuments.length }} 条 · 共 {{ filteredDocuments.length }} 条</span>
<span v-if="filteredDocuments.length > 0">当前显示 {{ pagedDocumentRange.start }}-{{ pagedDocumentRange.end }} 条</span>
</div>
</div>
<div v-if="!selectedGroupId" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
请选择一个知识库分组。
</div>
<div v-else-if="isDocumentsLoading" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
正在加载文档...
</div>
<div v-else-if="filteredDocuments.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
{{ documents.length === 0 ? '当前分组暂无文档,可直接在上方创建第一条文档记录。' : '当前筛选条件下暂无匹配文档。' }}
</div>
<div v-else class="space-y-3">
<div
v-for="doc in pagedFilteredDocuments"
:key="doc.id"
class="rounded-2xl border px-4 py-4 transition-colors"
:class="selectedDocumentId === doc.id
? 'border-brand-200 bg-brand-50/50 border-brand-200'
: 'border-default'"
>
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 flex-1 gap-3">
<label class="mt-1 inline-flex shrink-0 cursor-pointer items-center">
<input
type="checkbox"
class="h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
:checked="selectedDocumentIds.includes(doc.id)"
@change="toggleDocumentSelection(doc.id)"
/>
</label>
<div class="min-w-0 flex-1">
<button
@click="openMarkdownEditor(doc)"
class="block max-w-full truncate text-left font-semibold text-primary transition-colors hover:text-brand-600 hover:text-brand-600"
>
{{ getDocumentDisplayTitle(doc) }}
</button>
<button
type="button"
@click="openSourceInfo(doc)"
class="mt-1 block max-w-full text-left text-sm text-muted transition-colors hover:text-brand-600 hover:text-brand-600"
>
{{ getDocumentDisplayDescription(doc) }}
</button>
<div class="mt-2 text-xs text-muted">
<span>版本数:{{ doc.version_count ?? 0 }}</span>
<span v-if="doc.latest_version">
<span> · 当前版本:v{{ doc.latest_version.version_no }} · </span>
<button
type="button"
@click="openSourceInfo(doc)"
class="inline text-xs text-muted underline-offset-2 transition-colors hover:text-brand-600 hover:underline hover:text-brand-600"
>
{{ doc.latest_version.source_file_name }}
</button>
</span>
</div>
</div>
</div>
<div class="flex items-center gap-2">
<button
@click="openDocumentDetail(doc.id)"
class="inline-flex items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
>
<FileText class="h-3.5 w-3.5" />
查看记录
</button>
<button
@click="triggerUploadForDocument(doc.id)"
class="inline-flex items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 border-brand-200 hover:bg-brand-50"
>
<Upload class="h-3.5 w-3.5" />
上传版本
</button>
<button
@click="handleSyncDocument(doc.id)"
:disabled="syncingDocumentId === doc.id || !doc.latest_version"
class="inline-flex items-center gap-1 rounded-xl border border-emerald-200 px-3 py-2 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60 border-emerald-200"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ syncingDocumentId === doc.id ? '同步中...' : '同步 Dify' }}
</button>
<button
@click="handleDeleteDocument(doc)"
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 border-rose-200 hover:bg-rose-50"
>
<Trash2 class="h-3.5 w-3.5" />
删除
</button>
</div>
</div>
<div class="mt-4 flex items-end justify-between gap-3 border-t border-default pt-3 ">
<div class="space-y-1">
<div class="text-xs text-muted">
更新时间:{{ formatDateTime(doc.updated_at) }}
</div>
<div
v-if="getDocumentWorkflowState(doc).primaryError"
class="max-w-xl text-xs text-rose-500"
>
失败原因:{{ getDocumentWorkflowState(doc).primaryError }}
</div>
</div>
<div class="flex flex-wrap items-center justify-end gap-2">
<div
v-for="badge in getWorkflowBadges(doc)"
:key="`${doc.id}-${badge.label}`"
class="inline-flex items-center rounded-full border px-3 py-1 text-sm font-semibold"
:class="badge.className"
>
{{ badge.label }}:{{ badge.value }}
</div>
</div>
</div>
</div>
<div
v-if="filteredDocuments.length > documentListPageSize"
class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
>
<div class="text-sm text-muted">
第 {{ documentListPage }} / {{ filteredDocumentTotalPages }} 页 · 共 {{ filteredDocuments.length }} 条
</div>
<div class="flex items-center gap-2">
<button
@click="documentListPage = Math.max(1, documentListPage - 1)"
:disabled="documentListPage === 1"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60 hover-surface-soft"
>
上一页
</button>
<button
@click="documentListPage = Math.min(filteredDocumentTotalPages, documentListPage + 1)"
:disabled="documentListPage === filteredDocumentTotalPages"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60 hover-surface-soft"
>
下一页
</button>
</div>
</div>
</div>
</div>
</section>
</div>
</template>
</div>
</div>
<div
v-if="showGroupModal"
class="dialog-overlay z-50 items-center"
>
<div class="dialog-panel max-w-lg p-6">
<div class="mb-4 flex items-center justify-between">
<h3 class="text-lg font-semibold text-primary">{{ groupFormTitle }}</h3>
<button
@click="closeGroupModal"
class="rounded-full p-1 text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
<X class="h-5 w-5" />
</button>
</div>
<div class="space-y-4">
<div>
<label class="label-field block mb-2">分组名称</label>
<input v-model="groupForm.name" class="input-field" placeholder="例如:财务制度库" />
</div>
<div>
<label class="label-field block mb-2">分组描述</label>
<textarea v-model="groupForm.description" rows="4" class="input-field" placeholder="描述该分组的业务范围或清洗目标" />
</div>
<p
v-if="feedback"
class="text-sm"
:class="feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600'"
>
{{ feedback }}
</p>
</div>
<div class="mt-6 flex justify-end gap-3">
<button
type="button"
@click="closeGroupModal"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
取消
</button>
<button
@click="handleSubmitGroup"
:disabled="isGroupSubmitting"
class="btn-primary btn-sm"
>
<FolderPlus class="h-4 w-4" />
{{ groupSubmitText }}
</button>
</div>
</div>
</div>
<div
v-if="showRecordModal"
class="dialog-overlay z-[55] items-center"
>
<div class="dialog-panel max-w-5xl max-h-[90vh] p-6">
<div class="mb-4 flex items-start justify-between gap-4">
<div>
<h3 class="text-lg font-semibold text-primary">文档记录</h3>
<p class="mt-1 text-sm text-muted">
当前查看:{{ selectedDocument ? getDocumentDisplayTitle(selectedDocument) : `文档 #${selectedDocumentId}` }}
</p>
</div>
<button
@click="closeDocumentDetail"
class="rounded-full p-1 text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
<X class="h-5 w-5" />
</button>
</div>
<div v-if="isRecordLoading" class="flex min-h-[360px] items-center justify-center rounded-2xl border border-dashed border-default text-sm text-muted ">
正在加载文档记录...
</div>
<div v-else class="space-y-6 overflow-y-auto pr-1">
<div>
<div class="mb-3 flex items-center justify-between">
<h3 class="text-base font-semibold text-primary">版本记录</h3>
<span class="text-xs text-muted">{{ selectedDocumentVersions.length }} 条</span>
</div>
<div v-if="selectedDocumentVersions.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-8 text-center text-sm text-muted ">
暂无版本记录,上传版本后会显示在这里。
</div>
<div v-else class="space-y-3">
<div
v-for="version in selectedDocumentVersions"
:key="version.id"
class="rounded-2xl border border-default px-4 py-4 "
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-semibold text-primary">
v{{ version.version_no }} · {{ version.source_file_name }}
</div>
<div class="mt-2 flex flex-wrap items-center gap-2 text-sm text-muted">
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="getStatusBadgeClass(version.status)"
>
{{ getStatusLabel(version.status) }}
</span>
<span>大小:{{ version.source_file_size ?? 0 }} bytes</span>
</div>
</div>
<div class="text-sm text-muted">
{{ formatDateTime(version.created_at) }}
</div>
</div>
</div>
</div>
</div>
<div>
<div class="mb-3 flex items-center justify-between">
<h3 class="text-base font-semibold text-primary">Dify 同步记录</h3>
<span class="text-xs text-muted">{{ selectedDocumentSyncRecords.length }} 条</span>
</div>
<div v-if="selectedDocumentSyncRecords.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-8 text-center text-sm text-muted ">
暂无 Dify 同步记录,手动点击“同步 Dify”后会显示在这里。
</div>
<div v-else class="space-y-3">
<div
v-for="record in selectedDocumentSyncRecords"
:key="record.id"
class="rounded-2xl border border-default px-4 py-4 "
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-semibold text-primary">
{{ record.dataset_name || record.dataset_id }} · {{ record.remote_document_name || record.remote_document_id }}
</div>
<div class="mt-2 flex flex-wrap items-center gap-2 text-sm text-muted">
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="getStatusBadgeClass(record.status)"
>
{{ getStatusLabel(record.status) }}
</span>
<span>版本:{{ record.document_version_id }}</span>
</div>
</div>
<div class="text-sm text-muted">
{{ formatDateTime(record.updated_at) }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div
v-if="showMarkdownModal"
class="dialog-overlay z-[60] items-center"
>
<div class="dialog-panel max-w-5xl max-h-[90vh] p-6">
<div class="mb-4 flex items-start justify-between gap-4">
<div class="min-w-0">
<h3 class="truncate text-lg font-semibold text-primary">{{ markdownModalTitle }}</h3>
<p class="mt-1 text-sm text-muted">
{{ markdownVersionLabel || '正在读取当前版本...' }}
<span class="ml-2 rounded-full bg-surface-soft px-2 py-0.5 text-xs text-muted">
{{ markdownKind === 'preview' ? '预览文本' : '清洗 Markdown' }}
</span>
</p>
</div>
<button
@click="closeMarkdownModal"
class="rounded-full p-1 text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
<X class="h-5 w-5" />
</button>
</div>
<p
v-if="markdownError"
class="mb-4 text-sm text-rose-500"
>
{{ markdownError }}
</p>
<div v-if="isMarkdownLoading" class="flex min-h-[420px] items-center justify-center rounded-2xl border border-dashed border-default text-sm text-muted ">
正在加载清洗后的 Markdown...
</div>
<textarea
v-else
v-model="markdownContent"
spellcheck="false"
class="min-h-[420px] w-full flex-1 rounded-2xl border border-default bg-surface-soft px-4 py-3 font-mono text-sm text-primary outline-none transition-colors focus:border-brand-300 focus:bg-surface"
placeholder="当前文档尚未生成 Markdown,可在此粘贴或编辑内容。"
/>
<div class="mt-6 flex justify-end gap-3">
<button
type="button"
@click="closeMarkdownModal"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
关闭
</button>
<button
@click="handleSaveMarkdown"
:disabled="isMarkdownLoading || isMarkdownSaving || !markdownDocumentId"
class="inline-flex items-center justify-center rounded-xl bg-brand-600px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
>
{{ isMarkdownSaving ? '保存中...' : '保存 Markdown' }}
</button>
</div>
</div>
</div>
<div
v-if="showSourceInfoModal"
class="dialog-overlay z-[58] items-center"
>
<div class="dialog-panel max-w-4xl max-h-[90vh] p-6">
<div class="mb-4 flex items-start justify-between gap-4">
<div class="min-w-0">
<h3 class="truncate text-lg font-semibold text-primary">源文件信息</h3>
<p class="mt-1 text-sm text-muted">
当前查看:{{ sourceInfoDocument ? getDocumentDisplayTitle(sourceInfoDocument) : `文档 #${sourceInfoDocumentId}` }}
</p>
</div>
<button
@click="closeSourceInfoModal"
class="rounded-full p-1 text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
<X class="h-5 w-5" />
</button>
</div>
<div v-if="isSourceInfoLoading" class="flex min-h-[320px] items-center justify-center rounded-2xl border border-dashed border-default text-sm text-muted ">
正在加载源文件信息...
</div>
<div v-else-if="sourceInfoVersions.length === 0" class="flex min-h-[320px] items-center justify-center rounded-2xl border border-dashed border-default text-sm text-muted ">
暂无源文件信息,上传版本后会显示在这里。
</div>
<div v-else class="space-y-3 overflow-y-auto pr-1">
<div
v-for="version in sourceInfoVersions"
:key="version.id"
class="rounded-2xl border border-default px-4 py-4 "
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<button
type="button"
@click="openOriginalSourceFile(version)"
class="font-semibold text-primary underline-offset-2 transition-colors hover:text-brand-600 hover:underline hover:text-brand-600"
>
v{{ version.version_no }} · {{ version.source_file_name }}
</button>
<span
v-if="version.is_current"
class="inline-flex items-center rounded-full border border-brand-200 bg-brand-50 px-2.5 py-1 text-xs font-semibold text-brand-700 border-brand-200"
>
当前版本
</span>
<span
v-if="openingSourceVersionId === version.id"
class="text-xs text-muted"
>
正在打开...
</span>
</div>
<div class="mt-2 flex flex-wrap items-center gap-2 text-sm text-muted">
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="getStatusBadgeClass(version.status)"
>
{{ getStatusLabel(version.status) }}
</span>
<span>文件名:{{ version.source_file_name }}</span>
<span>大小:{{ formatFileSize(version.source_file_size) }}</span>
<span v-if="version.source_file_ext">类型:{{ version.source_file_ext }}</span>
</div>
<div v-if="version.error_message" class="mt-2 text-sm text-rose-500">
失败原因:{{ version.error_message }}
</div>
</div>
<div class="text-sm text-muted">
{{ formatDateTime(version.created_at) }}
</div>
</div>
</div>
</div>
<div class="mt-6 flex justify-end">
<button
type="button"
@click="closeSourceInfoModal"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
关闭
</button>
</div>
</div>
</div>
<div
v-if="showFailureModal"
class="dialog-overlay z-[65] items-center"
>
<div class="dialog-panel max-w-6xl max-h-[90vh] p-6">
<div class="mb-4 flex items-start justify-between gap-4">
<div>
<h3 class="text-lg font-semibold text-primary">{{ failureModalTitle }}</h3>
<p class="mt-1 text-sm text-muted">
当前分组共 {{ failureModalItems.length }} 条失败记录,每页 {{ FAILURE_PAGE_SIZE }} 条。
</p>
</div>
<button
@click="closeFailureModal"
class="rounded-full p-1 text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
<X class="h-5 w-5" />
</button>
</div>
<div v-if="failureModalItems.length === 0" class="flex min-h-[320px] items-center justify-center rounded-2xl border border-dashed border-default text-sm text-muted ">
当前没有失败数据。
</div>
<div v-else class="space-y-4 overflow-y-auto pr-1">
<div
v-for="item in pagedFailureModalItems"
:key="item.key"
class="rounded-2xl border border-default px-4 py-4 "
>
<div class="flex items-start justify-between gap-4">
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2">
<div class="max-w-full truncate text-base font-semibold text-primary">
{{ getDocumentDisplayTitle(item.document) }}
</div>
<span class="inline-flex items-center rounded-full border border-rose-200 bg-rose-50 px-2.5 py-1 text-xs font-semibold text-rose-700 border-rose-200">
{{ item.stageLabel }}
</span>
</div>
<div class="mt-2 text-sm text-muted">
当前版本:
<span v-if="item.document.latest_version">
v{{ item.document.latest_version.version_no }} · {{ item.document.latest_version.source_file_name }}
</span>
<span v-else>暂无版本</span>
</div>
<div class="mt-2 text-sm text-rose-500">
失败原因:{{ item.errorMessage }}
</div>
</div>
<div class="shrink-0 text-right text-sm text-muted">
{{ formatDateTime(item.updatedAt) }}
</div>
</div>
<div class="mt-4 flex flex-wrap items-center gap-2">
<button
@click="handleRetryFailedItem(item, 'submit')"
:disabled="retryingFailureKey === `${item.key}-submit`"
class="inline-flex items-center gap-2 rounded-xl border border-sky-200 px-3 py-2 text-xs font-medium text-sky-700 transition-colors hover:bg-sky-50 disabled:cursor-not-allowed disabled:opacity-60"
>
{{ retryingFailureKey === `${item.key}-submit` ? '处理中...' : '重新提交' }}
</button>
<button
@click="handleRetryFailedItem(item, 'clean')"
:disabled="retryingFailureKey === `${item.key}-clean` || !item.document.latest_version"
class="inline-flex items-center gap-2 rounded-xl border border-amber-200 px-3 py-2 text-xs font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60 border-amber-200"
>
{{ retryingFailureKey === `${item.key}-clean` ? '处理中...' : '重新清洗' }}
</button>
<button
@click="handleRetryFailedItem(item, 'sync')"
:disabled="retryingFailureKey === `${item.key}-sync` || !item.document.latest_version"
class="inline-flex items-center gap-2 rounded-xl border border-emerald-200 px-3 py-2 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60 border-emerald-200"
>
{{ retryingFailureKey === `${item.key}-sync` ? '处理中...' : '重新同步' }}
</button>
</div>
</div>
</div>
<div
v-if="failureModalItems.length > FAILURE_PAGE_SIZE"
class="mt-5 flex items-center justify-between gap-3 border-t border-default pt-4 "
>
<div class="text-sm text-muted">
第 {{ failureModalPage }} / {{ failureModalTotalPages }} 页
</div>
<div class="flex items-center gap-2">
<button
@click="failureModalPage = Math.max(1, failureModalPage - 1)"
:disabled="failureModalPage === 1"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60 hover-surface-soft"
>
上一页
</button>
<button
@click="failureModalPage = Math.min(failureModalTotalPages, failureModalPage + 1)"
:disabled="failureModalPage === failureModalTotalPages"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60 hover-surface-soft"
>
下一页
</button>
</div>
</div>
</div>
</div>
<div
v-if="showPathUploadModal"
class="dialog-overlay z-[66] items-center"
>
<div class="dialog-panel max-w-4xl max-h-[90vh] p-6">
<div class="mb-4 flex items-start justify-between gap-4">
<div>
<h3 class="text-lg font-semibold text-primary">上传路径</h3>
<p class="mt-1 text-sm text-muted">
选择本地目录后,系统会按批次将该路径下文件导入当前分组并自动进入清洗流程。
</p>
</div>
<button
@click="closePathUploadModal"
class="rounded-full p-1 text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
<X class="h-5 w-5" />
</button>
</div>
<div class="space-y-4 overflow-y-auto pr-1">
<div class="rounded-2xl border border-default bg-surface-soft p-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<div class="text-sm font-medium text-primary">本地路径选择</div>
<div class="mt-1 text-xs text-muted">
支持多次选择目录追加文件;当前浏览器安全限制下,手动粘贴任意本机路径不能直接读取文件内容。
</div>
</div>
<button
@click="triggerPathUploadSelection"
class="inline-flex items-center gap-2 rounded-2xl border border-brand-200 px-4 py-2.5 text-sm font-medium text-brand-700 transition-colors hover:bg-brand-50 border-brand-200 hover:bg-brand-50"
>
<Upload class="h-4 w-4" />
选择本地目录
</button>
</div>
</div>
<div>
<label class="label-field block mb-2">路径清单</label>
<textarea
v-model="pathUploadDraftText"
rows="5"
class="input-field"
placeholder="目录选择后会自动填充路径清单;如需记录多路径,可在此粘贴备注。"
/>
</div>
<div>
<div class="mb-2 flex items-center justify-between gap-3">
<div class="text-sm font-medium text-secondary">
待上传文件
<span class="ml-2 text-xs text-muted">{{ pathUploadSelectedFiles.length }} 条</span>
</div>
<div class="text-xs text-muted">
已选根路径:{{ selectedPathRoots.length ? selectedPathRoots.join('、') : '暂无' }}
</div>
</div>
<div v-if="pathUploadSelectedFiles.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-8 text-center text-sm text-muted ">
请选择本地目录后再确认上传。
</div>
<div v-else class="max-h-72 space-y-2 overflow-y-auto pr-1">
<div
v-for="item in pathUploadSelectedFiles"
:key="item.key"
class="flex items-start justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
>
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-medium text-primary">{{ item.file.name }}</div>
<div class="mt-1 truncate text-xs text-muted">{{ item.displayPath }}</div>
</div>
<button
@click="removeSelectedPathFile(item.key)"
class="inline-flex items-center rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
移除
</button>
</div>
</div>
</div>
</div>
<div class="mt-6 flex justify-end gap-3">
<button
type="button"
@click="closePathUploadModal"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
取消
</button>
<button
@click="handleConfirmPathUpload"
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-700"
>
<Upload class="h-4 w-4" />
确认上传
</button>
</div>
</div>
</div>
<div
v-if="showPathUploadHistoryModal"
class="dialog-overlay z-[67] items-center"
>
<div class="dialog-panel max-w-6xl max-h-[90vh] p-6">
<div class="mb-4 flex items-start justify-between gap-4">
<div>
<h3 class="text-lg font-semibold text-primary">上传路径历史批次</h3>
<p class="mt-1 text-sm text-muted">查看每次路径上传的批次结果、失败文件与重试入口。</p>
</div>
<button
@click="closePathUploadHistoryModal"
class="rounded-full p-1 text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
<X class="h-5 w-5" />
</button>
</div>
<div v-if="pathUploadHistoryJobs.length === 0" class="flex min-h-[320px] items-center justify-center rounded-2xl border border-dashed border-default text-sm text-muted ">
当前暂无上传路径历史批次。
</div>
<div v-else class="grid min-h-0 flex-1 grid-cols-1 gap-4 lg:grid-cols-[320px_minmax(0,1fr)]">
<div class="space-y-3 overflow-y-auto pr-1">
<button
v-for="job in pathUploadHistoryJobs"
:key="job.id"
@click="selectedPathUploadHistoryJobId = job.id"
class="w-full rounded-2xl border px-4 py-4 text-left transition-colors"
:class="String(selectedPathUploadHistoryJobId || selectedPathUploadHistoryJob?.id) === String(job.id)
? 'border-brand-200 bg-brand-50 border-brand-200 '
: 'border-default bg-surface hover:bg-surface-soft hover-surface-soft'"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate text-sm font-semibold text-primary">批次 #{{ job.id }}</div>
<div class="mt-1 text-xs text-muted">{{ formatDateTime(job.created_at) }}</div>
</div>
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="getStatusBadgeClass(job.status)"
>
{{ getStatusLabel(job.status) }}
</span>
</div>
<div class="mt-3 grid grid-cols-2 gap-2 text-xs text-muted">
<div>总计 {{ getPathUploadJobSummary(job).total }}</div>
<div>成功 {{ getPathUploadJobSummary(job).success }}</div>
<div>失败 {{ getPathUploadJobSummary(job).failed }}</div>
<div>待处理 {{ getPathUploadJobSummary(job).pending }}</div>
</div>
</button>
</div>
<div v-if="selectedPathUploadHistoryJob" class="min-h-0 rounded-2xl border border-default p-4 ">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<div class="text-base font-semibold text-primary">批次 #{{ selectedPathUploadHistoryJob.id }}</div>
<div class="mt-1 text-sm text-muted">
创建时间:{{ formatDateTime(selectedPathUploadHistoryJob.created_at) }}
<span v-if="selectedPathUploadHistoryJob.finished_at"> · 完成时间:{{ formatDateTime(selectedPathUploadHistoryJob.finished_at) }}</span>
</div>
<div class="mt-2 text-sm text-muted">{{ selectedPathUploadHistoryJob.message || '暂无批次说明' }}</div>
</div>
<div class="flex items-center gap-2">
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="getStatusBadgeClass(selectedPathUploadHistoryJob.status)"
>
{{ getStatusLabel(selectedPathUploadHistoryJob.status) }}
</span>
<button
v-if="selectedPathUploadHistoryItems.length && !pathUploadRunning"
@click="toggleSelectAllPathUploadHistoryItems"
class="inline-flex items-center rounded-xl border border-default px-3 py-2 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
{{ isAllPathUploadHistoryItemsSelected ? '取消全选' : '全选' }}
</button>
<button
v-if="!pathUploadRunning"
@click="handleBatchDeletePathUploadItems"
:disabled="!selectedPathUploadHistorySelectedItems.length || deletingPathUploadBatch"
class="inline-flex items-center rounded-xl border border-default px-3 py-2 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
>
{{ deletingPathUploadBatch ? '删除中...' : `批量删除${selectedPathUploadHistorySelectedItems.length ? ` (${selectedPathUploadHistorySelectedItems.length})` : ''}` }}
</button>
<button
v-if="hasRetryablePathUploadFailure(selectedPathUploadHistoryJob) && !pathUploadRunning"
@click="handleRetryFailedPathUpload(selectedPathUploadHistoryJob)"
:disabled="retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:all`"
class="inline-flex items-center rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
{{ retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:all` ? '处理中...' : '重试全部失败文件' }}
</button>
</div>
</div>
<div class="mt-4 grid grid-cols-2 gap-3 text-sm text-secondary md:grid-cols-4">
<div class="rounded-xl bg-surface-soft px-3 py-2 ">总计 {{ getPathUploadJobSummary(selectedPathUploadHistoryJob).total }}</div>
<div class="rounded-xl bg-surface-soft px-3 py-2 ">成功 {{ getPathUploadJobSummary(selectedPathUploadHistoryJob).success }}</div>
<div class="rounded-xl bg-surface-soft px-3 py-2 ">失败 {{ getPathUploadJobSummary(selectedPathUploadHistoryJob).failed }}</div>
<div class="rounded-xl bg-surface-soft px-3 py-2 ">待处理 {{ getPathUploadJobSummary(selectedPathUploadHistoryJob).pending }}</div>
</div>
<div class="mt-4 max-h-[50vh] space-y-2 overflow-y-auto pr-1">
<div
v-for="item in selectedPathUploadHistoryItems"
:key="item.key"
class="flex flex-wrap items-start justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
>
<label class="flex items-center pt-1">
<input
type="checkbox"
:checked="selectedPathUploadHistoryItemKeys.includes(item.key)"
@change="togglePathUploadHistoryItemSelection(item.key)"
class="h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
</label>
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-medium text-primary">{{ item.title }}</div>
<div class="mt-1 truncate text-xs text-muted">{{ item.displayPath }}</div>
<div v-if="item.error" class="mt-1 text-xs text-rose-500">失败原因:{{ item.error }}</div>
</div>
<div class="flex items-center gap-2">
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="getPathUploadItemDisplayState(item).className"
>
{{ getPathUploadItemDisplayState(item).label }}
</span>
<button
v-if="item.retryable && !pathUploadRunning"
@click="handleRetryFailedPathUpload(selectedPathUploadHistoryJob, [item.displayPath])"
:disabled="retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:${item.displayPath}`"
class="inline-flex items-center rounded-xl border border-rose-200 px-2.5 py-1 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
{{ retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:${item.displayPath}` ? '处理中...' : '重试' }}
</button>
<button
v-if="!pathUploadRunning"
@click="handleDeletePathUploadItem(selectedPathUploadHistoryJob, item)"
class="inline-flex items-center rounded-xl border border-default px-2.5 py-1 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
删除
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="handleDeleteConfirm"
@cancel="closeDeleteConfirmDialog"
/>
</template>