Files
syops/frontend/src/features/kb/utils/kb-workflow.utils.ts
T

203 lines
8.1 KiB
TypeScript
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.
/**
* 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';
import type { KbTranslateFn } from './kb-i18n.types';
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',
t: KbTranslateFn,
) => {
const text = String(value || '').trim();
if (!text) return null;
const upper = text.toUpperCase();
if (isUnreadableErrorMessage(text)) {
if (stage === 'clean') return t('kbWorkspace.errors.unreadableClean');
if (stage === 'sync') return t('kbWorkspace.errors.unreadableSync');
return t('kbWorkspace.errors.unreadableUpload');
}
if (upper.includes('LEGACY_CLEAN_TASK_RECOVERED_MANUALLY')) {
return t('kbWorkspace.errors.legacyCleanRecovered');
}
if (upper.includes('SOURCE_FILE_NOT_FOUND') || text.includes('源文件不存在')) {
return t('kbWorkspace.errors.sourceFileNotFound');
}
if (upper.includes('CLEAN_TIMEOUT') || text.includes('清洗超时')) {
return t('kbWorkspace.errors.cleanTimeout');
}
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,
t: KbTranslateFn,
) => {
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: t('kbWorkspace.status.draft'), className: getStatusBadgeClass('draft') }
: uploadJob?.status === 'failed'
? {
code: 'failed',
label: t('kbWorkspace.status.failed'),
className: getStatusBadgeClass('failed'),
errorMessage: normalizeWorkflowErrorMessage(uploadJob.error_message || uploadJob.message, 'upload', t),
}
: { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
let cleanStage: WorkflowStageState;
if (!doc.latest_version) {
cleanStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
} else if (cleanJob?.status === 'failed' || latestStatus === 'failed') {
cleanStage = {
code: 'failed',
label: t('kbWorkspace.status.failed'),
className: getStatusBadgeClass('failed'),
errorMessage: normalizeWorkflowErrorMessage(
cleanJob?.error_message || doc.latest_version?.error_message || cleanJob?.message || null,
'clean',
t,
),
};
} else if (['cleaned', 'ready', 'syncing', 'synced'].includes(latestStatus)) {
cleanStage = { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
} else if (String(cleanJob?.status || '').toLowerCase() === 'queued') {
cleanStage = {
code: 'queued',
label: t('kbWorkspace.status.queued'),
className: getStatusBadgeClass('queued'),
};
} else if (String(cleanJob?.status || '').toLowerCase() === 'running' || latestStatus === 'processing') {
cleanStage = {
code: 'running',
label: t('kbWorkspace.status.cleaning'),
className: getStatusBadgeClass('processing'),
};
} else if (latestStatus === 'uploaded') {
cleanStage = { code: 'pending', label: t('kbWorkspace.status.pendingClean'), className: getStatusBadgeClass('uploaded') };
} else {
cleanStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
}
let syncStage: WorkflowStageState;
if (!doc.latest_version || cleanStage.code === 'failed') {
syncStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
} else if (syncJob?.status === 'failed') {
syncStage = {
code: 'failed',
label: t('kbWorkspace.status.failed'),
className: getStatusBadgeClass('failed'),
errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync', t),
};
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
syncStage = { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
} else if (['running', 'queued'].includes(String(syncJob?.status || '').toLowerCase()) || latestStatus === 'syncing') {
syncStage = {
code: 'running',
label: latestStatus === 'syncing' ? t('kbWorkspace.status.syncing') : t('kbWorkspace.status.pendingSync'),
className: getStatusBadgeClass(latestStatus === 'syncing' ? 'processing' : 'uploaded'),
};
} else if (['cleaned', 'ready'].includes(latestStatus)) {
syncStage = { code: 'pending', label: t('kbWorkspace.status.pendingSync'), className: getStatusBadgeClass('uploaded') };
} else {
syncStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
}
const primaryError =
syncStage.errorMessage ||
cleanStage.errorMessage ||
uploadStage.errorMessage ||
normalizeWorkflowErrorMessage(doc.latest_version?.error_message, 'clean', t) ||
null;
return {
upload: uploadStage,
clean: cleanStage,
sync: syncStage,
primaryError,
};
};
export const getWorkflowBadges = (
doc: KbDocumentItem,
getLatestJobForDocument: GetLatestJobForDocument,
t: KbTranslateFn,
) => {
const workflow = getDocumentWorkflowState(doc, getLatestJobForDocument, t);
return [
{ label: t('kbWorkspace.workflow.upload'), value: workflow.upload.label, className: workflow.upload.className },
{ label: t('kbWorkspace.workflow.clean'), value: workflow.clean.label, className: workflow.clean.className },
{ label: t('kbWorkspace.workflow.sync'), value: workflow.sync.label, className: workflow.sync.className },
];
};
export const getMarkdownUnavailableMessage = (
doc: KbDocumentItem,
_getLatestJobForDocument: GetLatestJobForDocument,
t: KbTranslateFn,
fallback?: string | null,
) => {
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
const normalizedReason = normalizeWorkflowErrorMessage(
doc.latest_version?.error_message,
'clean',
t,
);
if (latestStatus === 'failed') {
return normalizedReason
? t('kbWorkspace.msg.markdownFailedWithReason', { reason: normalizedReason })
: t('kbWorkspace.msg.markdownFailedRetry');
}
if (latestStatus === 'processing') {
return t('kbWorkspace.msg.markdownProcessing');
}
if (latestStatus === 'uploaded') {
return t('kbWorkspace.msg.markdownPendingClean');
}
return fallback || t('kbWorkspace.msg.markdownNotGenerated');
};