feat(shipping-notice): 添加识别定义和规则集管理功能,支持客户和站点的可配置识别规则

This commit is contained in:
hugo committed 2026-07-20 19:28:17 +08:00
1 parent 88408490d7
commit 34d489a2d1
167 files changed
+10365 -7978

No files matched your search

+39 -3
View File
@@ -19,6 +19,8 @@ import type {
ShippingCreateBatchFromIntakesResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskBatchDispositionResponse,
ShippingTaskPage,
ShippingTaskSummary,
ShippingCustomerOption,
ShippingTaskUiState,
@@ -69,13 +71,20 @@ const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<str
reportShippingDebugEvent('shipping.api.ts', hypothesisId, msg, data);
// #endregion
export const listWorkspaceShippingTasks = (params?: { process_status?: string; limit?: number }) => {
export const listWorkspaceShippingTasks = (params?: {
process_status?: string;
lifecycle_status?: string;
page?: number;
page_size?: number;
}) => {
/** 拉取当前用户可见的发货任务列表。 */
const sp = new URLSearchParams();
if (params?.process_status) sp.set('process_status', params.process_status);
if (params?.limit) sp.set('limit', String(params.limit));
if (params?.lifecycle_status) sp.set('lifecycle_status', params.lifecycle_status);
if (params?.page) sp.set('page', String(params.page));
if (params?.page_size) sp.set('page_size', String(params.page_size));
const qs = sp.toString();
return requestJson<ShippingTaskSummary[]>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
return requestJson<ShippingTaskPage>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
};
export const listWorkspaceShippingBatches = (params?: { limit?: number }) => {
@@ -137,6 +146,30 @@ export async function downloadWorkspaceShippingExportArchive(payload: { batch_no
return { blob: await response.blob(), filename: encoded ? decodeURIComponent(encoded) : (plain || 'shipping_exports.zip') };
}
/** 批量移动任务到回收站;服务端按每条任务当前事实决定仅删除或作废后删除。 */
export const deleteWorkspaceShippingTasks = (taskNos: string[], reason: string) =>
requestJson<ShippingTaskBatchDispositionResponse>(
'/api/workspace/shipping-tasks/batch-delete', jsonPost({ task_nos: taskNos, reason }),
);
/** 批量归档任务,适用于外部上传中或已上传而禁止平台单方作废的任务。 */
export const archiveWorkspaceShippingTasks = (taskNos: string[]) =>
requestJson<ShippingTaskBatchDispositionResponse>(
'/api/workspace/shipping-tasks/batch-archive', jsonPost({ task_nos: taskNos }),
);
/** 批量恢复回收站中的纯误建任务。 */
export const restoreWorkspaceShippingTasks = (taskNos: string[]) =>
requestJson<ShippingTaskBatchDispositionResponse>(
'/api/workspace/shipping-tasks/batch-restore', jsonPost({ task_nos: taskNos }),
);
/** 仅管理员可永久清除回收站中的纯误建任务;服务端会重新统计所有阻断引用。 */
export const purgeWorkspaceShippingTasks = (taskNos: string[], reason: string) =>
requestJson<ShippingTaskBatchDispositionResponse>(
'/api/workspace/shipping-tasks/batch-purge', jsonPost({ task_nos: taskNos, reason }),
);
/**
* 确认当前任务的库存 RPA 来源。
* @param taskNo - 发货任务编号
@@ -671,6 +704,9 @@ export type {
ShippingCreateBatchFromIntakesResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskBatchDispositionResponse,
ShippingTaskDispositionResult,
ShippingTaskPage,
ShippingTaskSummary,
ShippingTaskUiState,
ShippingWorkflowStep,
@@ -190,6 +190,27 @@ describe('useChat shipping_order_extraction_state SSE', () => {
expect(isAllowedAfterStreamTerminal('agent_message')).toBe(false);
});
it('clears a generic stream failure after persisted partial completion', () => {
const message: ChatMessage = {
role: 'assistant',
content: '请求失败,请稍后重试。',
stream_error: true,
};
applyShippingOrderExtractionStateToMessage(message, {
status: 'partially_completed',
phase: 'result_persisted',
message: '仍有 1 个订单需要补充信息',
pending_count: 1,
terminal: true,
});
// 关键断言:已保存的订单部分完成结果不得被通用 SSE 断流提示覆盖。
expect(message.content).toBe('');
expect(message.stream_error).toBe(false);
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
});
it('hydrates persisted terminal state from ChatLog payload', () => {
const message: ChatMessage = {
role: 'assistant',
@@ -174,6 +174,13 @@ const SHIPPING_ORDER_EXTRACTION_STATUSES = new Set<ShippingOrderExtractionStatus
'failed',
]);
const STREAM_ERROR_FALLBACK_SUFFIXES = [
'请求失败,请稍后重试。',
'請求失敗,請稍後重試。',
'The request failed. Please try again.',
'คำขอล้มเหลว โปรดลองใหม่อีกครั้ง',
];
/**
* 将未知 SSE payload 规范为订单识别状态。
* 核心逻辑:只接受固定状态枚举;计数字段统一约束为非负整数,避免异常上游值破坏卡片布局。
@@ -219,6 +226,12 @@ export const applyShippingOrderExtractionStateToMessage = (
if (!state) return;
if (msg.shipping_order_extraction_state?.terminal && !state.terminal) return;
msg.shipping_order_extraction_state = state;
if (msg.stream_error && (state.status === 'completed' || state.status === 'partially_completed')) {
// 已持久化的订单事实优先于连接层通用断流提示,避免业务成功仍向用户误报失败。
const fallbackSuffix = STREAM_ERROR_FALLBACK_SUFFIXES.find((suffix) => msg.content.endsWith(suffix));
if (fallbackSuffix) msg.content = msg.content.slice(0, -fallbackSuffix.length).trimEnd();
msg.stream_error = false;
}
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_order_extraction_state: state,
@@ -260,7 +260,7 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
result = result
.replace(/\bcreate_task\b/gi, '新建任务')
.replace(/\bget_task_status\b/gi, '查询任务状态')
.replace(/\bparse_notice\b/gi, '解析发货通知')
.replace(/\bsubmit_order_extraction\b/gi, '提交订单抽取')
.replace(/\bsubmit_decision\b/gi, '提交处理结果')
.replace(/\bmatch_inventory\b/gi, '匹配库存')
.replace(/\bgenerate_excel\b/gi, '生成发货 Excel')
@@ -2,7 +2,7 @@
* features/chat/shipping/shippingUploadPrompt.ts
* 用途:通知上传后提示语构建、文件格式识别与临时库存声明判断。
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify LLM 解析续办。
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify 完整动态订单抽取。
*/
import i18n from '@/i18n';
@@ -10,7 +10,7 @@ import i18n from '@/i18n';
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
*/
/**
* 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发画布 LLM 抽取 + parse_notice)。
* 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发完整订单抽取链)。
*/
export function buildShippingNoticeUploadPrompt(
result: Record<string, unknown> | null | undefined,
@@ -43,13 +43,16 @@ describe('shipping notice order extraction state', () => {
expect(resolveShippingOrderExtractionStatus(undefined, 'not_started')).toBe('not_started');
});
it('restores only in-progress and retryable parsing attachments into the input area', () => {
it('restores in-progress, retryable, and pending-candidate attachments into the input area', () => {
expect(shouldRestoreShippingNoticeIntake('queued')).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsing')).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 2)).toBe(true);
// Parsed files are already persisted in the user message bubble.
// 已完成且没有待审核 Candidate 的文件仅保留在用户消息气泡中。
expect(shouldRestoreShippingNoticeIntake('parsed')).toBe(false);
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 0)).toBe(false);
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed', 2)).toBe(false);
expect(shouldRestoreShippingNoticeIntake('consumed')).toBe(false);
});
});
@@ -37,13 +37,23 @@ const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
/**
* 判断服务端 Intake 是否应恢复到输入栏。
* AI 触发时机:无;页面刷新或重新打开会话时调用。
* 已解析文件已作为用户消息附件固化在对话气泡中,不能再次显示在输入栏;仅恢复仍在处理中的文件和可手动重试的解析失败文件。
* @param parseStatus - 服务端返回的预解析状态
* 已解析文件已作为用户消息附件固化在对话气泡中,不能再次显示在输入栏;但存在待审核
* Candidate 的部分完成 Intake 必须恢复,否则用户无法补充字段并继续建单。
* @param parseStatus - 服务端返回的预解析状态。
* @param orderExtractionStatus - 服务端返回的订单抽取状态。
* @param candidateCount - 当前仍可审核的订单 Candidate 数量。
* @returns 是否恢复为待发送附件卡片
*/
export function shouldRestoreShippingNoticeIntake(parseStatus: string | null | undefined): boolean {
export function shouldRestoreShippingNoticeIntake(
parseStatus: string | null | undefined,
orderExtractionStatus?: string | null,
candidateCount = 0,
): boolean {
const status = String(parseStatus || '').trim().toLowerCase();
return ACTIVE_PARSE.has(status) || status === 'parse_failed';
const extractionStatus = String(orderExtractionStatus || '').trim().toLowerCase();
return ACTIVE_PARSE.has(status)
|| status === 'parse_failed'
|| (extractionStatus === 'partially_completed' && candidateCount > 0);
}
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
@@ -437,7 +447,11 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
const restoreForConversation = async (conversationId?: string | null) => {
const { items } = await listActiveShippingNoticeIntakes(conversationId);
const restored: ShippingNoticePendingAttachment[] = items
.filter((item) => shouldRestoreShippingNoticeIntake(item.parse_status))
.filter((item) => shouldRestoreShippingNoticeIntake(
item.parse_status,
item.order_extraction_status,
item.candidates?.length || 0,
))
.map((item) => ({
id: `restored_${item.intake_no}`,
kind: 'shipping_notice' as const,
@@ -81,6 +81,16 @@ export interface ShippingTaskSummary {
upload_attempt?: number | null;
pending_human_reason?: string | null;
error_message?: string | null;
lifecycle_status?: 'active' | 'voided' | 'archived' | string;
deleted_at?: string | null;
voided_at?: string | null;
void_reason?: string | null;
archived_at?: string | null;
disposition_capabilities?: Partial<Record<'delete' | 'void' | 'archive' | 'restore', {
allowed: boolean;
code?: string | null;
reason?: string | null;
}>>;
conversation_id?: string | null;
export_file_name?: string | null;
freight_ref_no?: string | null;
@@ -239,6 +249,26 @@ export interface ShippingFieldAdjudication {
conflicts?: Array<Record<string, unknown>>;
}
/** 工作台任务列表的数据库分页响应;items 仅包含当前页。 */
export interface ShippingTaskPage {
items: ShippingTaskSummary[];
page: number;
page_size: number;
total: number;
}
export interface ShippingTaskDispositionResult {
task_no: string;
status: 'deleted' | 'voided_and_deleted' | 'archived' | 'restored' | 'blocked' | string;
code?: string;
message?: string;
}
export interface ShippingTaskBatchDispositionResponse {
results: ShippingTaskDispositionResult[];
requested_count: number;
}
export interface ShippingOrderCustomerMatchCandidate {
customer_id: number;
standard_name: string;