feat(shipping-notice): 新增货代客户管理功能,支持客户导入、识别证据管理与客户确认

This commit is contained in:
hugo committed 2026-07-16 08:16:19 +08:00
1 parent b595e157e9
commit 4fbaed2b4c
176 files changed
+14011 -994

No files matched your search

@@ -21,7 +21,7 @@ export interface ShippingConversationContext {
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; display_query?: string },
) => Promise<void>;
) => Promise<boolean | void>;
}
/** 发送菜单类消息后,若当前会话尚未出现在侧栏历史中则刷新列表 */
@@ -1,11 +1,10 @@
/**
* features/chat/shipping/shippingTaskId.ts
* 用途:从消息或会话历史中识别发货任务编号(SN- 格式)。
* 用途:从聊天消息中识别发货任务编号(SN- 格式)。
* 依赖:constants/shipping.SHIPPING_TASK_ID_RE、chat.types。
* 逻辑:useChatShipping 切换任务/恢复会话时调用。
* 逻辑:useChatShipping 与 shipping refresh 只把这里作为消息级兜底,不再承担历史标题猜测。
*/
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
import type { ChatSessionItem } from '../types/chat.types';
/** 从消息列表倒序查找最近出现的 SN- 任务编号。 */
export function findLatestShippingTaskId(msgs: Array<{ content?: string }>): string {
@@ -15,13 +14,3 @@ export function findLatestShippingTaskId(msgs: Array<{ content?: string }>): str
}
return '';
}
/** 在侧栏历史中按标题模糊匹配含 taskId 的会话。 */
export function findHistorySessionForShippingTask(
history: ChatSessionItem[],
taskId: string,
): ChatSessionItem | null {
const needle = taskId.trim().toUpperCase();
if (!needle) return null;
return history.find((item) => String(item.title || '').toUpperCase().includes(needle)) || null;
}
@@ -23,6 +23,7 @@ export interface ShippingMenuHandlerContext {
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
openShippingInventoryPicker: (taskId?: string) => boolean;
openShippingNoticePicker: (taskId?: string) => boolean;
openShippingCustomerDialog: (taskId: string) => Promise<void>;
executeShippingDecision: (
decision: string,
displayText?: string,
@@ -142,6 +143,15 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
}
return;
}
if (action.id === 'confirm_customer') {
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
await ctx.openShippingCustomerDialog(taskId);
return;
}
const chatTurnActionIds = new Set([
'generate_excel',
@@ -21,13 +21,12 @@ describe('useChatShippingRefresh', () => {
getWorkspaceShippingTaskUiState.mockReset();
});
it('prefers current batch focus task over message and history fallbacks', () => {
it('prefers current batch focus task over other explicit anchors', () => {
expect(resolvePreferredShippingTaskId({
batchTaskId: 'sn-batch-001',
messageTaskId: 'sn-message-001',
resolvedTaskId: 'sn-resolved-001',
queryTaskId: 'sn-query-001',
historyTaskId: 'sn-history-001',
})).toBe('SN-BATCH-001');
});
@@ -37,7 +36,6 @@ describe('useChatShippingRefresh', () => {
messageTaskId: '',
resolvedTaskId: '',
queryTaskId: '',
historyTaskId: '',
})).toBe('');
});
@@ -88,7 +86,6 @@ describe('useChatShippingRefresh', () => {
messages,
conversationId: ref('conv-focus-switch'),
isThinking: ref(false),
history: ref([]),
resolvedShippingTaskId,
shippingTaskIdFromQuery: computed(() => ''),
getActiveBatchTaskId: () => 'SN-FOCUS-B',
@@ -159,7 +156,6 @@ describe('useChatShippingRefresh', () => {
messages,
conversationId: ref('conv-source'),
isThinking: ref(false),
history: ref([]),
resolvedShippingTaskId: ref('SN-SOURCE-001'),
shippingTaskIdFromQuery: computed(() => ''),
getActiveBatchTaskId: () => 'SN-SOURCE-001',
@@ -170,4 +166,27 @@ describe('useChatShippingRefresh', () => {
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['download_excel']);
expect(messages.value[0].shipping_ui_state?.action_buttons?.map((item) => item.id)).toEqual(['download_excel']);
});
it('does not guess a task id from history metadata when no explicit anchor exists', async () => {
const messages = ref([
{
role: 'assistant' as const,
content: '请继续处理当前任务',
},
]);
const { refreshShippingActions } = createShippingActionsRefresher({
isShippingNoticeAgent: computed(() => true),
messages,
conversationId: ref('conv-no-anchor'),
isThinking: ref(false),
resolvedShippingTaskId: ref(''),
shippingTaskIdFromQuery: computed(() => ''),
getActiveBatchTaskId: () => '',
});
await refreshShippingActions();
expect(getWorkspaceShippingTaskUiState).not.toHaveBeenCalled();
expect(messages.value[0].shipping_actions).toBeUndefined();
});
});
@@ -2,14 +2,13 @@
* features/chat/shipping/useChatShippingRefresh.ts
* 用途:刷新聊天区发货通知 UI State,把后端状态机 action_buttons 同步到消息气泡。
* 依赖:shipping.api、shippingTaskId、shippingNoticeActions 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从 Dify 正文解析按钮。
* 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从会话标题猜任务号或从 Dify 正文解析按钮。
*/
import { getWorkspaceShippingTaskUiState } from '@/features/chat/api/shipping.api';
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
import { findLatestShippingTaskId } from './shippingTaskId';
import { stripShippingActionListByButtons, stripShippingPlainActionMenu } from './shippingText';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingActionButton } from '../types/shipping.types';
import type { ShippingTaskUiState } from '../types/shipping.api.types';
import type { ComputedRef, Ref } from 'vue';
@@ -19,7 +18,6 @@ export interface ShippingRefreshContext {
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
isThinking: Ref<boolean>;
history: Ref<ChatSessionItem[]>;
resolvedShippingTaskId: Ref<string>;
shippingTaskIdFromQuery: ComputedRef<string>;
getActiveBatchTaskId: () => string;
@@ -29,7 +27,7 @@ export interface ShippingRefreshContext {
* 解析当前聊天页最可靠的发货任务编号。
*
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
* 禁止再按 conversation 扫任务列表“猜”一票,避免多票会话把动作按钮挂错任务。
* 禁止再按 conversation 标题“猜”一票,避免多票会话把动作按钮挂错任务。
* @param params - 当前聊天页中可用的任务定位线索
* @returns 可信的任务编号;无法明确定位时返回空字符串
*/
@@ -38,14 +36,12 @@ export function resolvePreferredShippingTaskId(params: {
messageTaskId?: string | null;
resolvedTaskId?: string | null;
queryTaskId?: string | null;
historyTaskId?: string | null;
}) {
return String(
params.batchTaskId
|| params.messageTaskId
|| params.resolvedTaskId
|| params.queryTaskId
|| params.historyTaskId
|| '',
).trim().toUpperCase();
}
@@ -74,20 +70,11 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
if (!ctx.isShippingNoticeAgent.value) return;
const msgs = ctx.messages.value;
if (!msgs.length) return;
const cid = String(ctx.conversationId.value || '').trim();
const historyTaskId = (() => {
if (!cid) return '';
const session = ctx.history.value.find((item) => String(item.conversation_id || '') === cid);
const title = String(session?.title || '');
const match = title.match(SHIPPING_TASK_ID_RE);
return match?.[0] ? match[0].toUpperCase() : '';
})();
const taskId = resolvePreferredShippingTaskId({
batchTaskId: ctx.getActiveBatchTaskId(),
messageTaskId: findLatestShippingTaskId(msgs),
resolvedTaskId: ctx.resolvedShippingTaskId.value,
queryTaskId: ctx.shippingTaskIdFromQuery.value,
historyTaskId,
});
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
let lastOpenAssistantIndex = -1;
@@ -22,7 +22,14 @@ const createContext = (
conversationId: ref('conv-send'),
history: ref([]),
input: ref(''),
attachments: ref([{ kind: 'local', file: new File(['notice'], 'notice.txt', { type: 'text/plain' }) }]),
attachments: ref([{
id: 'local-notice',
kind: 'local',
file: new File(['notice'], 'notice.txt', { type: 'text/plain' }),
type: 'document',
uploadStatus: 'waiting',
uploadProgress: 0,
}]),
shippingAutoFlowRequested: ref(true),
resolvedShippingTaskId: ref(''),
getActiveShippingBatchNo: () => '',
@@ -32,7 +39,7 @@ const createContext = (
getActiveShippingTaskId: () => '',
lastAssistantMessageContent: () => '',
lastAssistantShippingActions: () => [],
sendMessage: vi.fn(async () => undefined),
sendMessage: vi.fn(async () => true),
buildFileSpecsForSend: vi.fn(async () => []),
loadHistory: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
@@ -44,6 +51,9 @@ const createContext = (
handleShippingAutoUploadFile: vi.fn(async () => undefined),
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
markOrderExtractionStarted: vi.fn(),
rollbackOrderExtractionStarted: vi.fn(),
syncShippingConversationWorkspace: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
shippingSuggestedPrompt: computed(() => ''),
isShippingShortageQueryIntent: () => false,
@@ -73,6 +83,7 @@ describe('useChatShippingSendHandler', () => {
});
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
const completionOrder: string[] = [];
const attachment = {
id: 'notice-1',
kind: 'shipping_notice' as const,
@@ -89,8 +100,11 @@ describe('useChatShippingSendHandler', () => {
hasCandidateReviewIssues: () => true,
hasSelectedNoticeCandidates: () => true,
getParsedIntakeNos: () => ['SNI-1'],
refreshNoticeIntakeStatuses: vi.fn(async () => undefined),
clearConsumedNoticeAttachments: vi.fn(),
applyShippingMessageRecovery: vi.fn(async () => { completionOrder.push('recovery'); return true; }),
refreshNoticeIntakeStatuses: vi.fn(async () => { completionOrder.push('intakes'); }),
syncShippingConversationWorkspace: vi.fn(async () => { completionOrder.push('workspace'); return true; }),
clearConsumedNoticeAttachments: vi.fn(() => { completionOrder.push('clear'); }),
refreshShippingActions: vi.fn(async () => { completionOrder.push('actions'); }),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
@@ -107,8 +121,26 @@ describe('useChatShippingSendHandler', () => {
shipping_intake_nos: ['SNI-1'],
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
},
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
expect.objectContaining({
userAttachments: [{
id: 'notice-1',
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
onAssistantMessageFinished: expect.any(Function),
}),
);
expect(ctx.markOrderExtractionStarted).toHaveBeenCalledWith(['SNI-1']);
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
const assistantMessage = { role: 'assistant', content: '已打开已有任务' } as const;
await hooks?.onAssistantMessageFinished?.(assistantMessage, []);
expect(ctx.applyShippingMessageRecovery).toHaveBeenCalledWith(assistantMessage);
expect(completionOrder).toEqual(['recovery', 'intakes', 'workspace', 'clear', 'actions']);
expect(ctx.syncShippingConversationWorkspace).toHaveBeenCalledWith({ preferLatest: true });
});
it('uses the user query for full extraction even when no candidate exists before send', async () => {
@@ -144,7 +176,102 @@ describe('useChatShippingSendHandler', () => {
shipping_intake_nos: ['SNI-1'],
display_query: '请解析这些附件',
},
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
expect.objectContaining({
userAttachments: [{
id: 'notice-1',
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
onAssistantMessageFinished: expect.any(Function),
}),
);
});
it('retries the conversation workspace once when the first refresh fails', async () => {
const syncWorkspace = vi.fn()
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true);
const ctx = createContext({
attachments: ref([{
id: 'notice-retry',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-RETRY',
}]),
getParsedIntakeNos: () => ['SNI-RETRY'],
syncShippingConversationWorkspace: syncWorkspace,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
await hooks?.onAssistantMessageFinished?.({} as never, []);
expect(syncWorkspace).toHaveBeenCalledTimes(2);
expect(syncWorkspace).toHaveBeenNthCalledWith(1, { preferLatest: true });
expect(syncWorkspace).toHaveBeenNthCalledWith(2, { preferLatest: true });
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('rolls back the local extracting state when the chat request fails', async () => {
const rollback = vi.fn();
const ctx = createContext({
attachments: ref([{
id: 'notice-failed-send',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-FAILED-SEND',
}]),
getParsedIntakeNos: () => ['SNI-FAILED-SEND'],
sendMessage: vi.fn(async () => { throw new Error('network failed'); }),
rollbackOrderExtractionStarted: rollback,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(rollback).toHaveBeenCalledWith(['SNI-FAILED-SEND']);
expect(ctx.msg.warning).toHaveBeenCalledWith('network failed');
});
it('rolls back extraction state when sendMessage reports a handled stream failure', async () => {
const rollback = vi.fn();
const ctx = createContext({
attachments: ref([{
id: 'notice-handled-failure',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-HANDLED-FAILURE',
}]),
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
sendMessage: vi.fn(async () => false),
rollbackOrderExtractionStarted: rollback,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
expect(ctx.loadHistory).not.toHaveBeenCalled();
});
});
@@ -22,6 +22,8 @@ import {
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
import { classifyShippingUploadFile } from './shippingUploadPrompt';
import { extractExt } from '../constants/shipping';
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import type { SendMessageLifecycleHooks } from '../composables/useChat';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
@@ -51,8 +53,8 @@ export interface ShippingSendHandlerContext {
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
hooks?: SendMessageLifecycleHooks,
) => Promise<boolean | void>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadHistory: () => Promise<void>;
sendShippingMenuMessage: (message: string) => Promise<void>;
@@ -71,8 +73,13 @@ export interface ShippingSendHandlerContext {
hasSelectedNoticeCandidates?: () => boolean;
openShippingDuplicateDialog?: (attachmentId?: string) => void;
getParsedIntakeNos?: () => string[];
markOrderExtractionStarted?: (intakeNos: string[]) => void;
rollbackOrderExtractionStarted?: (intakeNos: string[]) => void;
refreshNoticeIntakeStatuses?: () => Promise<void>;
clearConsumedNoticeAttachments?: () => void;
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
isShippingShortageQueryIntent: (text: string) => boolean;
@@ -211,11 +218,13 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
}
const intakeNos = ctx.getParsedIntakeNos?.() || [];
if (intakeNos.length) {
const userAttachments = createChatMessageAttachmentSnapshots(noticeItems);
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.markOrderExtractionStarted?.(intakeNos);
try {
await ctx.sendMessage(
const sent = await ctx.sendMessage(
query,
ctx.currentAgentId.value,
ctx.selectedKb.value,
@@ -225,15 +234,30 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
display_query: query,
},
{
onAssistantMessageFinished: async () => {
userAttachments,
onAssistantMessageFinished: async (assistantMessage) => {
if (ctx.applyShippingMessageRecovery) {
await ctx.applyShippingMessageRecovery(assistantMessage);
} else {
ctx.applyShippingBatchSnapshot?.(assistantMessage);
}
await ctx.refreshNoticeIntakeStatuses?.();
if (!(await ctx.syncShippingConversationWorkspace({ preferLatest: true }))) {
await new Promise((resolve) => setTimeout(resolve, 300));
await ctx.syncShippingConversationWorkspace({ preferLatest: true });
}
ctx.clearConsumedNoticeAttachments?.();
await ctx.refreshShippingActions();
},
},
);
if (sent === false) {
ctx.rollbackOrderExtractionStarted?.(intakeNos);
return true;
}
await ctx.loadHistory();
} catch (e: unknown) {
ctx.rollbackOrderExtractionStarted?.(intakeNos);
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
}
@@ -0,0 +1,35 @@
/**
* features/chat/shipping/useShippingNoticeIntakes.spec.ts
* 用途:验证订单抽取阶段的轮询与本地即时状态合并规则。
* 依赖:Vitest、useShippingNoticeIntakes 纯函数导出。
* 逻辑:确保 parsed 不会提前停止 extracting 轮询,且服务端 not_started 不覆盖刚点击发送的本地状态。
*/
import { describe, expect, it } from 'vitest';
import {
resolveShippingOrderExtractionStatus,
shouldPollShippingNoticeIntake,
} from './useShippingNoticeIntakes';
describe('shipping notice order extraction state', () => {
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
expect(shouldPollShippingNoticeIntake({
parseStatus: 'parsed',
orderExtractionStatus: 'extracting',
})).toBe(true);
expect(shouldPollShippingNoticeIntake({
parseStatus: 'parsed',
orderExtractionStatus: 'completed',
})).toBe(false);
expect(shouldPollShippingNoticeIntake({
parseStatus: 'parsed',
orderExtractionStatus: 'failed',
})).toBe(false);
});
it('preserves the immediate extracting state until the backend leaves not_started', () => {
expect(resolveShippingOrderExtractionStatus('extracting', 'not_started')).toBe('extracting');
expect(resolveShippingOrderExtractionStatus('extracting', 'extracting')).toBe('extracting');
expect(resolveShippingOrderExtractionStatus('extracting', 'completed')).toBe('completed');
expect(resolveShippingOrderExtractionStatus(undefined, 'not_started')).toBe('not_started');
});
});
@@ -32,6 +32,23 @@ export { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttac
const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', 'cancelled', 'expired']);
const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']);
const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
export function shouldPollShippingNoticeIntake(
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus'>,
): boolean {
return !TERMINAL_PARSE.has(item.parseStatus)
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
}
/** 保留刚点击发送的本地 extracting,直到服务端进入真实抽取状态或返回终态。 */
export function resolveShippingOrderExtractionStatus(localStatus?: string, remoteStatus?: string | null): string | undefined {
const local = String(localStatus || '').trim().toLowerCase();
const remote = String(remoteStatus || '').trim().toLowerCase();
if (local === 'extracting' && (!remote || remote === 'not_started')) return 'extracting';
return remote || undefined;
}
function mapServerParseStatus(status: string): ShippingNoticePendingAttachment['parseStatus'] {
const normalized = String(status || '').trim().toLowerCase();
@@ -160,7 +177,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|| item.uploadStatus === 'waiting'
|| ACTIVE_PARSE.has(item.parseStatus)
|| item.parseStatus === 'queued'
|| item.parseStatus === 'parsing',
|| item.parseStatus === 'parsing'
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()),
),
);
@@ -223,7 +241,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
if (!intakeNos.length) return;
if (intakeNos.every((no) => {
const item = noticeAttachments.value.find((entry) => entry.intakeNo === no);
return item != null && TERMINAL_PARSE.has(item.parseStatus);
return item != null && !shouldPollShippingNoticeIntake(item);
})) {
return;
}
@@ -255,7 +273,10 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
if (!local) continue;
patchAttachment(local.id, {
parseStatus: mapServerParseStatus(remote.parse_status),
orderExtractionStatus: remote.order_extraction_status || undefined,
orderExtractionStatus: resolveShippingOrderExtractionStatus(
local.orderExtractionStatus,
remote.order_extraction_status,
),
orderExtractionVersion: remote.order_extraction_version || undefined,
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: remote.order_extraction_error_code || remote.error_code || undefined,
@@ -357,6 +378,32 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
)
.map((item) => String(item.intakeNo));
/** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */
const markOrderExtractionStarted = (intakeNos: string[]) => {
const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean));
for (const attachment of noticeAttachments.value) {
if (!attachment.intakeNo || !selected.has(attachment.intakeNo.toUpperCase())) continue;
patchAttachment(attachment.id, {
orderExtractionStatus: 'extracting',
errorCode: undefined,
errorMessage: undefined,
});
}
schedulePoll();
};
/** 聊天请求未成功发起时撤销本地即时状态;服务端真实状态由下一次刷新覆盖。 */
const rollbackOrderExtractionStarted = (intakeNos: string[]) => {
const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean));
for (const attachment of noticeAttachments.value) {
if (!attachment.intakeNo || !selected.has(attachment.intakeNo.toUpperCase())) continue;
if (attachment.orderExtractionStatus === 'extracting') {
patchAttachment(attachment.id, { orderExtractionStatus: 'not_started' });
}
}
schedulePoll();
};
const clearConsumedAttachments = () => {
options.attachments.value = options.attachments.value.filter(
(item) => item.kind !== 'shipping_notice' || item.parseStatus !== 'consumed',
@@ -391,7 +438,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
}));
const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
options.attachments.value = [...nonNotice, ...restored];
if (restored.some((item) => item.parseStatus === 'queued' || item.parseStatus === 'parsing')) {
if (restored.some((item) => shouldPollShippingNoticeIntake(item))) {
schedulePoll();
}
};
@@ -486,6 +533,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
setCandidateSelected,
updateCandidateSummary,
getParsedIntakeNos,
markOrderExtractionStarted,
rollbackOrderExtractionStarted,
getSelectedCandidateNos,
refreshStatuses,
clearConsumedAttachments,