refactor(frontend): 重构前端第三版
This commit is contained in:
1 parent
bf32f8b954
commit
dc141d19a2
49 files changed
+5333
-4234
No files matched your search
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* features/kb/utils/kb-display.utils.ts
|
||||
* 文档标题、时间、文件大小与状态徽标等纯展示工具。
|
||||
*/
|
||||
import type { KbDocumentItem } from '../api/kb.api';
|
||||
|
||||
export 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())}`;
|
||||
};
|
||||
|
||||
export 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;
|
||||
};
|
||||
|
||||
export const getDocumentDisplayTitle = (doc: KbDocumentItem) => trimPathText(doc.title) || '未命名文档';
|
||||
|
||||
export const getDocumentDisplayDescription = (doc: KbDocumentItem) => {
|
||||
const text = trimPathText(doc.description);
|
||||
return text || getDocumentDisplayTitle(doc);
|
||||
};
|
||||
|
||||
/** 将后端重复文档错误归一为前端可展示的简短文案 */
|
||||
export const normalizeDuplicateDocumentError = (message?: string | null) => {
|
||||
const text = String(message || '').trim();
|
||||
if (!text) return '知识库接口请求失败';
|
||||
if (text.includes('当前分组下已存在同名文档') || text.includes('上传失败,文件已存在')) {
|
||||
return '上传失败,文件已存在';
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
export 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 || '未知状态';
|
||||
};
|
||||
|
||||
export 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';
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* features/kb/utils/kb-list.utils.ts
|
||||
* 列表合并工具:轮询刷新时保持已有项顺序,减少 UI 跳动。
|
||||
*/
|
||||
|
||||
/** 按当前列表顺序合并服务端数据,新增项追加在末尾 */
|
||||
export function mergeStableItems<T extends { id: number | string }>(current: T[], incoming: T[]): 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;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* features/kb/utils/kb-path-upload.utils.ts
|
||||
* 路径上传任务(path_upload job)解析与排序权重。
|
||||
*/
|
||||
import type { KbJob } from '../api/kb.api';
|
||||
import type { PathUploadStatus, PathUploadTaskItem } from '../types/kb-workspace.types';
|
||||
|
||||
export 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 };
|
||||
};
|
||||
|
||||
/** 用于在历史批次列表中优先展示有进度或进行中的任务 */
|
||||
export 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;
|
||||
};
|
||||
|
||||
export 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: { status?: string }) => String(item?.status || '').toLowerCase() === 'failed').length;
|
||||
return files.map((item: Record<string, unknown>, 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 as string | undefined)
|
||||
|| (String(item.status || '').toLowerCase() === 'failed' && failedCount === 1
|
||||
? (job.error_message || job.message || '上传失败')
|
||||
: undefined),
|
||||
documentId: (item.document_id as number | undefined) || undefined,
|
||||
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
|
||||
startedAt: undefined,
|
||||
finishedAt: undefined,
|
||||
}));
|
||||
};
|
||||
|
||||
export const hasRetryablePathUploadFailure = (job: KbJob | null) =>
|
||||
getPathUploadJobItems(job).some((item) => item.retryable);
|
||||
|
||||
export 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 };
|
||||
};
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* features/kb/utils/kb-workflow.utils.ts
|
||||
* 文档工作流(上传/清洗/同步)状态推导与错误文案归一。
|
||||
*/
|
||||
import type { KbDocumentItem, KbJob } from '../api/kb.api';
|
||||
import { IDLE_BADGE_CLASS, type WorkflowStageState } from '../types/kb-workspace.types';
|
||||
import { getStatusBadgeClass } from './kb-display.utils';
|
||||
|
||||
export 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);
|
||||
};
|
||||
|
||||
export 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('SOURCE_FILE_NOT_FOUND') || text.includes('源文件不存在')) {
|
||||
return '原始文件不存在,请重新上传后再清洗';
|
||||
}
|
||||
if (upper.includes('CLEAN_TIMEOUT') || text.includes('清洗超时')) {
|
||||
return '文件清洗超时,请稍后重试;若多次失败,请检查源文件是否损坏';
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
/** 按文档与任务类型取当前分组下最新一条关联任务 */
|
||||
export function buildGetLatestJobForDocument(getActiveGroupJobs: () => KbJob[]) {
|
||||
return (doc: KbDocumentItem, jobType: string): KbJob | null => {
|
||||
const activeGroupJobs = getActiveGroupJobs();
|
||||
const currentVersionId = doc.latest_version?.id;
|
||||
const candidates = activeGroupJobs.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;
|
||||
};
|
||||
}
|
||||
|
||||
export type GetLatestJobForDocument = ReturnType<typeof buildGetLatestJobForDocument>;
|
||||
|
||||
export const getDocumentWorkflowState = (
|
||||
doc: KbDocumentItem,
|
||||
getLatestJobForDocument: GetLatestJobForDocument,
|
||||
) => {
|
||||
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: IDLE_BADGE_CLASS };
|
||||
} 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: IDLE_BADGE_CLASS };
|
||||
}
|
||||
|
||||
let syncStage: WorkflowStageState;
|
||||
if (!doc.latest_version || cleanStage.code === 'failed') {
|
||||
syncStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
} 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: IDLE_BADGE_CLASS };
|
||||
}
|
||||
|
||||
const primaryError =
|
||||
syncStage.errorMessage ||
|
||||
cleanStage.errorMessage ||
|
||||
uploadStage.errorMessage ||
|
||||
normalizeWorkflowErrorMessage(doc.latest_version?.error_message, 'clean') ||
|
||||
null;
|
||||
|
||||
return {
|
||||
upload: uploadStage,
|
||||
clean: cleanStage,
|
||||
sync: syncStage,
|
||||
primaryError,
|
||||
};
|
||||
};
|
||||
|
||||
export const getWorkflowBadges = (
|
||||
doc: KbDocumentItem,
|
||||
getLatestJobForDocument: GetLatestJobForDocument,
|
||||
) => {
|
||||
const workflow = getDocumentWorkflowState(doc, getLatestJobForDocument);
|
||||
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 },
|
||||
];
|
||||
};
|
||||
|
||||
export const getMarkdownUnavailableMessage = (
|
||||
doc: KbDocumentItem,
|
||||
_getLatestJobForDocument: GetLatestJobForDocument,
|
||||
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';
|
||||
};
|
||||
Reference in new issue
Block a user