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

@@ -1,13 +1,43 @@
/**
* features/chat/composables/useChat.spec.ts
* 用途:验证聊天流对发货通知 UI State SSE 事件的消息级回写行为。
* 依赖:vitest、useChat 导出的纯函数、chat.types。
* 逻辑:覆盖 batch_ui_state 到 focus_task_ui_state 的投影、focus 切换时按钮跟随更新,以及已消费按钮消息的防回挂保护。
* 用途:验证聊天流对发货通知 UI State 与订单识别生命周期 SSE 的消息级回写行为。
* 依赖:vitest、useChat/chat.api 导出的纯函数、chat.types。
* 逻辑:覆盖任务状态投影、订单识别终态保护、terminal 后事件放行及历史 payload 恢复。
*/
import { describe, expect, it } from 'vitest';
import { applyShippingUiStateToMessage } from './useChat';
import {
applyShippingOrderExtractionStateToMessage,
applyShippingUiStateToMessage,
createUserChatMessage,
isAllowedAfterStreamTerminal,
} from './useChat';
import { hydrateShippingOrderExtractionState } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
describe('useChat user attachment snapshots', () => {
it('copies sent attachments onto the user message without inheriting them for text-only messages', () => {
const attachments = [{
id: 'attachment-1',
name: 'purchase-order.pdf',
size: 144_456,
extension: 'pdf',
type: 'document' as const,
source: 'local' as const,
}];
const message = createUserChatMessage('总结附件', attachments);
attachments[0]!.name = 'changed.pdf';
expect(message).toMatchObject({
role: 'user',
content: '总结附件',
attachments: [{ name: 'purchase-order.pdf', size: 144_456 }],
});
expect(message.attachments).not.toBe(attachments);
expect(createUserChatMessage('仅重发文字')).toEqual({ role: 'user', content: '仅重发文字' });
});
});
const buildBatchUiStateEvent = (
taskNo: string,
batchNo: string,
@@ -97,3 +127,93 @@ describe('useChat shipping_ui_state SSE', () => {
.toBe('SN-FOCUS-B');
});
});
describe('useChat shipping_order_extraction_state SSE', () => {
it('replaces extracting with persisted facts without overwriting Dify content', () => {
const message: ChatMessage = {
role: 'assistant',
content: 'Dify 最终正文保持不变',
payload: { existing_key: 'kept' },
};
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'extracting',
phase: 'llm_extraction',
message: '正在识别邮件及附件中的订单',
created_count: -1,
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('extracting');
expect(message.shipping_order_extraction_state?.created_count).toBe(0);
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'completed',
phase: 'result_persisted',
message: '已创建 1 个发货任务',
created_count: 1,
opened_existing_count: 2,
pending_count: 0,
non_shipping_count: 3,
created_with_missing_fields_count: 1,
batch_no: 'SB-STATE-001',
terminal: true,
});
expect(message.content).toBe('Dify 最终正文保持不变');
expect(message.shipping_order_extraction_state).toMatchObject({
status: 'completed',
created_count: 1,
opened_existing_count: 2,
non_shipping_count: 3,
batch_no: 'SB-STATE-001',
terminal: true,
});
expect((message.payload as Record<string, unknown>).existing_key).toBe('kept');
expect((message.payload as { shipping_order_extraction_state?: { created_count?: number } })
.shipping_order_extraction_state?.created_count).toBe(1);
// 关键断言:网络重排导致的迟到进行态不能覆盖已经展示的终态。
applyShippingOrderExtractionStateToMessage(message, {
status: 'extracting',
phase: 'llm_extraction',
message: '迟到事件',
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('completed');
});
it('allows HXOPS domain states after the upstream terminal event', () => {
expect(isAllowedAfterStreamTerminal('shipping_order_extraction_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('shipping_ui_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('agent_message')).toBe(false);
});
it('hydrates persisted terminal state from ChatLog payload', () => {
const message: ChatMessage = {
role: 'assistant',
content: '订单识别完成',
payload: {
shipping_order_extraction_state: {
status: 'partially_completed',
phase: 'result_persisted',
message: '仍有 1 个订单需要补充信息',
created_count: 1,
opened_existing_count: 0,
pending_count: 1,
non_shipping_count: 0,
created_with_missing_fields_count: 0,
batch_no: 'SB-HISTORY-001',
terminal: true,
},
},
};
hydrateShippingOrderExtractionState(message);
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
expect(message.shipping_order_extraction_state?.pending_count).toBe(1);
expect(message.shipping_order_extraction_state?.batch_no).toBe('SB-HISTORY-001');
});
});
@@ -1,19 +1,49 @@
/**
* features/chat/composables/useChat.ts
* SSE 流式对话核心:消息列表、runs、发送与接收。
* 用途:维护聊天消息、并行 run 与 legacy SSE 流式收发,并投影货代领域状态。
* 依赖:Vue、vue-i18n、useChatTurn、streamErrorMessage、chat/shipping 类型。
* 逻辑:页面调用 useChat 发起消息;Dify/HXOPS SSE 被归并到当前助手消息,领域终态可继续在上游终止事件后写入。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
import type {
ChatMessage,
ChatMessageAttachment,
ChatRun,
RetrieverResource,
ShippingOrderExtractionState,
ShippingOrderExtractionStatus,
} from '../types/chat.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
import { createStartChatTurn } from './useChatTurn';
export interface SendMessageLifecycleHooks {
/** 当前轮用户消息的已发送附件快照;仅用于界面展示与后续持久化。 */
userAttachments?: ChatMessageAttachment[];
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
}
/**
* 创建当前轮乐观用户消息,并复制附件快照避免调用方后续修改污染消息历史。
* @param content - 用户可见问题文本
* @param attachments - 已上传并固化的附件快照
* @returns 可直接推入消息列表的用户消息
*/
export function createUserChatMessage(
content: string,
attachments?: ChatMessageAttachment[],
): ChatMessage {
return {
role: 'user',
content,
...(attachments?.length
? { attachments: attachments.map((attachment) => ({ ...attachment })) }
: {}),
};
}
const normalizeResources = (resources: unknown) => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
@@ -136,6 +166,74 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
};
};
const SHIPPING_ORDER_EXTRACTION_STATUSES = new Set<ShippingOrderExtractionStatus>([
'extracting',
'completed',
'partially_completed',
'failed',
]);
/**
* 将未知 SSE payload 规范为订单识别状态。
* 核心逻辑:只接受固定状态枚举;计数字段统一约束为非负整数,避免异常上游值破坏卡片布局。
* @param data - shipping_order_extraction_state 事件对象。
* @returns 合法状态;协议不匹配时返回 undefined。
*/
const resolveShippingOrderExtractionState = (
data: Record<string, unknown>,
): ShippingOrderExtractionState | undefined => {
const status = String(data.status || '') as ShippingOrderExtractionStatus;
if (!SHIPPING_ORDER_EXTRACTION_STATUSES.has(status)) return undefined;
const phase = String(data.phase || '');
if (!['llm_extraction', 'result_persisted', 'failed'].includes(phase)) return undefined;
const count = (value: unknown) => {
const parsed = Number(value);
return Number.isFinite(parsed) ? Math.max(Math.trunc(parsed), 0) : 0;
};
return {
status,
phase: phase as ShippingOrderExtractionState['phase'],
message: String(data.message || '').trim(),
created_count: count(data.created_count),
opened_existing_count: count(data.opened_existing_count),
pending_count: count(data.pending_count),
non_shipping_count: count(data.non_shipping_count),
created_with_missing_fields_count: count(data.created_with_missing_fields_count),
batch_no: typeof data.batch_no === 'string' && data.batch_no.trim() ? data.batch_no.trim() : null,
terminal: data.terminal === true || status !== 'extracting',
};
};
/**
* 将订单识别领域事件同步到当前助手消息及可持久化 payload。
* 核心逻辑:终态不得被迟到的 extracting 覆盖;正文由 Dify 独立维护,本函数只更新结构化状态。
* @param msg - 当前助手消息。
* @param data - shipping_order_extraction_state SSE 事件。
*/
export const applyShippingOrderExtractionStateToMessage = (
msg: ChatMessage,
data: Record<string, unknown>,
): void => {
const state = resolveShippingOrderExtractionState(data);
if (!state) return;
if (msg.shipping_order_extraction_state?.terminal && !state.terminal) return;
msg.shipping_order_extraction_state = state;
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_order_extraction_state: state,
};
};
/**
* 判断上游终态之后仍允许写入当前消息的领域事件。
* 核心逻辑:普通 Dify 文本在 terminal 后丢弃,但 HXOPS 的抽取终态和任务 UI State 由 Handler 在 terminal 后生成。
* @param eventName - SSE event 字段。
* @returns 是否允许继续消费。
*/
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
);
/**
* 把 SSE 事件附带的元数据同步到当前消息对象。
*
@@ -436,7 +534,11 @@ export function useChat() {
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => {
const displayQuery = String(context?.display_query || query || '').trim();
const displayQuery = String(
context && Object.prototype.hasOwnProperty.call(context, 'display_query')
? context.display_query ?? ''
: query || '',
).trim();
clearLikelyCompletedStreamTimer();
const shouldDetachPreviousStream = Boolean(activeStreamController.value) && hasVisibleCompletedAssistantReply(messages.value);
if (shouldDetachPreviousStream) {
@@ -463,7 +565,7 @@ export function useChat() {
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
runMessages.push({ role: 'user', content: displayQuery });
runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments));
let botMsgIndex: number | null = null;
let hasAssistantContent = false;
let hasTerminalEvent = false;
@@ -496,7 +598,10 @@ export function useChat() {
task_id: context?.task_id || undefined,
batch_no: context?.batch_no || undefined,
shipping_intake_nos: context?.shipping_intake_nos?.length ? context.shipping_intake_nos : undefined,
display_query: context?.display_query || undefined,
display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query')
? context.display_query
: undefined,
user_attachments: hooks?.userAttachments?.length ? hooks.userAttachments : undefined,
}),
});
@@ -550,13 +655,17 @@ export function useChat() {
}
const eventName = String(data.event || '');
if (ignoreFurtherStreamEvents && eventName !== 'shipping_ui_state') {
if (ignoreFurtherStreamEvents && !isAllowedAfterStreamTerminal(eventName)) {
continue;
}
if (eventName === 'shipping_ui_state') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingUiStateToMessage(botMsg, data);
} else if (eventName === 'shipping_order_extraction_state') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingOrderExtractionStateToMessage(botMsg, data);
} else if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
@@ -686,6 +795,7 @@ export function useChat() {
}
}
}
return run.status === 'done';
};
return {
@@ -0,0 +1,132 @@
/**
* features/chat/composables/useChatAttachments.spec.ts
* 用途:验证普通聊天附件的逐文件上传状态、成功缓存、失败重试与删除保护。
* 依赖:Vitest、Vue 响应式 API、mock 后的 chat.api。
* 逻辑:直接调用 useChatAttachments,断言附件状态与生成的 Dify 文件参数保持一致。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { uploadChatFile } from '../api/chat.api';
import { useChatAttachments } from './useChatAttachments';
import type { ChatDeps } from './chat.deps';
vi.mock('../api/chat.api', () => ({
uploadChatFile: vi.fn(),
}));
const uploadChatFileMock = vi.mocked(uploadChatFile);
/** 创建满足 composable 依赖的最小测试上下文。 */
function createAttachments() {
return useChatAttachments({
deps: {
msg: { warning: vi.fn() },
} as unknown as ChatDeps,
currentAgentId: computed(() => 7),
currentAgent: ref({
capabilities: { file_upload: true },
dify_parameters: {
file_upload: {
document: { enabled: true, transfer_methods: ['local_file'] },
},
},
}),
});
}
/** 向附件状态中加入一个普通本地文件。 */
function selectLocalFile(api: ReturnType<typeof createAttachments>, name = 'order.pdf') {
const file = new File(['content'], name, { type: 'application/pdf' });
api.handleLocalFilesSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
return api.attachments.value[0];
}
describe('useChatAttachments upload states', () => {
beforeEach(() => {
uploadChatFileMock.mockReset();
});
it('marks a successful local upload ready and reuses its upload id', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
uploadChatFileMock.mockResolvedValue({ id: 'upload-1' });
const firstSpecs = await api.buildFileSpecsForSend();
const secondSpecs = await api.buildFileSpecsForSend();
expect(attachment).toMatchObject({
kind: 'local',
uploadStatus: 'uploaded',
uploadProgress: 100,
uploadFileId: 'upload-1',
});
expect(firstSpecs).toEqual([{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }]);
expect(secondSpecs).toEqual(firstSpecs);
expect(uploadChatFileMock).toHaveBeenCalledTimes(1);
});
it('keeps a failed attachment and retries it on the next send', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
uploadChatFileMock
.mockRejectedValueOnce(new Error('network unavailable'))
.mockResolvedValueOnce({ id: 'upload-retry' });
await expect(api.buildFileSpecsForSend()).rejects.toThrow('network unavailable');
expect(attachment).toMatchObject({
uploadStatus: 'failed',
uploadProgress: 0,
errorMessage: 'network unavailable',
});
await expect(api.buildFileSpecsForSend()).resolves.toEqual([
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-retry' },
]);
expect(attachment).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-retry' });
expect(attachment && 'errorMessage' in attachment ? attachment.errorMessage : undefined).toBeUndefined();
});
it('reuses earlier successful files when a later file failed', async () => {
const api = createAttachments();
selectLocalFile(api, 'first.pdf');
selectLocalFile(api, 'second.pdf');
uploadChatFileMock
.mockResolvedValueOnce({ id: 'upload-first' })
.mockRejectedValueOnce(new Error('second failed'))
.mockResolvedValueOnce({ id: 'upload-second' });
await expect(api.buildFileSpecsForSend()).rejects.toThrow('second failed');
expect(api.attachments.value[0]).toMatchObject({
uploadStatus: 'uploaded',
uploadFileId: 'upload-first',
});
expect(api.attachments.value[1]).toMatchObject({ uploadStatus: 'failed' });
await expect(api.buildFileSpecsForSend()).resolves.toEqual([
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-first' },
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-second' },
]);
expect(uploadChatFileMock).toHaveBeenCalledTimes(3);
});
it('does not remove a local attachment while its request is uploading', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
let resolveUpload: ((value: { id: string }) => void) | undefined;
uploadChatFileMock.mockImplementation(() => new Promise((resolve) => {
resolveUpload = resolve;
}));
const buildPromise = api.buildFileSpecsForSend();
await Promise.resolve();
expect(attachment && 'uploadStatus' in attachment ? attachment.uploadStatus : undefined).toBe('uploading');
api.removeAttachment(attachment?.id || '');
expect(api.attachments.value).toHaveLength(1);
resolveUpload?.({ id: 'upload-finished' });
await buildPromise;
api.removeAttachment(attachment?.id || '');
expect(api.attachments.value).toHaveLength(0);
});
});
@@ -1,9 +1,12 @@
/**
* features/chat/composables/useChatAttachments.ts
* Dify 附件策略解析、本地/URL 附件管理与发送前上传。
* 用途:解析 Dify 附件策略,管理本地/URL 附件,并在发送前逐文件上传。
* 依赖:chat.api 的附件上传接口、chat.deps 的消息提示能力。
* 逻辑:Chat 页面通过本 composable 维护附件状态;发送流程调用 buildFileSpecsForSend 生成 Dify 文件参数。
*/
import { computed, ref, type ComputedRef, type Ref } from 'vue';
import { uploadChatFile } from '../api/chat.api';
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import type { PendingAttachment } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
@@ -245,7 +248,13 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
return resolveDifyType(ext, file.type || '');
};
/**
* 删除未在上传中的附件,避免界面移除后网络请求仍继续造成状态失配。
* @param id - 待删除附件的本地唯一标识
*/
const removeAttachment = (id: string) => {
const target = attachments.value.find((attachment) => attachment.id === id);
if (target?.kind === 'local' && target.uploadStatus === 'uploading') return;
attachments.value = attachments.value.filter((a) => a.id !== id);
};
@@ -288,7 +297,14 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
continue;
}
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type });
attachments.value.push({
id: `${Date.now()}_${Math.random()}`,
kind: 'local',
file: f,
type,
uploadStatus: 'waiting',
uploadProgress: 0,
});
}
if (inputEl) inputEl.value = '';
};
@@ -336,6 +352,12 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
};
/**
* 将待发送附件转换为 Dify 文件参数,并逐个更新本地文件的真实上传状态。
* 核心逻辑:复用已成功上传的 uploadFileId;失败附件保留并在下次发送时重试。
* @returns 可直接传给聊天接口的文件参数列表
* @throws 任一本地附件上传失败时抛出原始错误,中止本次消息发送
*/
const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
if (!attachmentPolicy.value.anyEnabled) return [];
if (attachments.value.length === 0) return [];
@@ -348,11 +370,30 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
isUploadingAttachments.value = true;
try {
for (const item of locals) {
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) {
throw new Error('Missing upload id');
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId });
continue;
}
item.uploadStatus = 'uploading';
item.uploadProgress = 0;
item.errorMessage = undefined;
try {
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) {
throw new Error('Missing upload id');
}
item.uploadStatus = 'uploaded';
item.uploadProgress = 100;
item.uploadFileId = uploaded.id;
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
} catch (error: unknown) {
item.uploadStatus = 'failed';
item.uploadProgress = 0;
item.uploadFileId = undefined;
item.errorMessage = error instanceof Error ? error.message : 'File upload failed';
throw error;
}
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
}
} finally {
isUploadingAttachments.value = false;
@@ -370,6 +411,14 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
attachments.value = [];
};
/**
* 固化当前待发送附件,供发送成功后的用户消息展示。
* @returns 与当前附件顺序一致、可 JSON 序列化的安全快照
*/
const createMessageAttachmentSnapshots = () => (
createChatMessageAttachmentSnapshots(attachments.value)
);
return {
attachments,
isUploadingAttachments,
@@ -378,6 +427,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
handleLocalFilesSelected,
addRemoteUrlAttachment,
buildFileSpecsForSend,
createMessageAttachmentSnapshots,
clearAttachments,
};
}
@@ -415,6 +415,7 @@ export function useChatPage() {
attachments: attachmentApi.attachments,
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
createMessageAttachmentSnapshots: attachmentApi.createMessageAttachmentSnapshots,
clearAttachments: attachmentApi.clearAttachments,
sendMessage,
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
@@ -561,6 +562,12 @@ export function useChatPage() {
resolveShippingDuplicateDialog: shipping.resolveShippingDuplicateDialog,
removeShippingDuplicateDialogAttachment: shipping.removeShippingDuplicateDialogAttachment,
closeShippingDuplicateDialog: shipping.closeShippingDuplicateDialog,
showShippingCustomerDialog: shipping.showShippingCustomerDialog,
shippingCustomerOptions: shipping.shippingCustomerOptions,
shippingCustomerLoading: shipping.shippingCustomerLoading,
searchShippingCustomers: shipping.searchShippingCustomers,
confirmShippingCustomer: shipping.confirmShippingCustomer,
closeShippingCustomerDialog: shipping.closeShippingCustomerDialog,
filePreviewVisible,
previewFile,
previewFiles,
@@ -5,7 +5,12 @@
* 逻辑:覆盖 current focus、process summary 回退、首票回退与无任务时清空焦点原因四种路径。
*/
import { describe, expect, it } from 'vitest';
import { resolveShippingBatchFocusState } from './useChatShipping';
import {
resolveLatestShippingMessageRecoveryPayload,
resolveLatestShippingBatchSnapshot,
resolveShippingBatchFocusState,
selectShippingConversationBatch,
} from './useChatShipping';
describe('useChatShipping batch focus sync', () => {
it('prefers batch current focus task and keeps default reason', () => {
@@ -62,3 +67,84 @@ describe('useChatShipping batch focus sync', () => {
});
});
});
describe('useChatShipping conversation workspace selection', () => {
const batches = [
{ batch_no: 'SB-OLD', focus_task: { task_no: 'SN-OLD' } },
{ batch_no: 'SB-NEW', focus_task: { task_no: 'SN-NEW' } },
];
it('keeps the active batch during a normal refresh', () => {
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', false)?.batch_no).toBe('SB-OLD');
});
it('selects the latest batch after an order extraction turn', () => {
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', true)?.batch_no).toBe('SB-NEW');
});
});
describe('useChatShipping persisted batch snapshot', () => {
it('restores the latest valid batch snapshot from assistant message payloads', () => {
const snapshot = resolveLatestShippingBatchSnapshot([
{
role: 'assistant',
content: '旧结果',
payload: { shipping_batch_ui_state: { batch_no: 'SB-OLD', tasks: [] } },
},
{
role: 'assistant',
content: '无效结果',
payload: { shipping_batch_ui_state: { batch_no: 'SB-INVALID' } },
},
{
role: 'assistant',
content: '已打开已有任务',
payload: {
shipping_batch_ui_state: {
batch_no: 'SB-EXISTING',
current_focus_task_no: 'SN-EXISTING',
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', process_status: 'pending_review' }],
},
},
},
]);
expect(snapshot?.batch_no).toBe('SB-EXISTING');
expect(snapshot?.current_focus_task_no).toBe('SN-EXISTING');
});
it('ignores malformed snapshots', () => {
expect(resolveLatestShippingBatchSnapshot([
{ role: 'assistant', content: '', payload: { shipping_batch_ui_state: { batch_no: 'SB-NO-TASKS' } } },
{ role: 'user', content: '继续' },
])).toBeNull();
});
});
describe('useChatShipping message recovery payload', () => {
it('falls back to task anchor when batch snapshot is absent', () => {
const payload = resolveLatestShippingMessageRecoveryPayload([
{
role: 'assistant',
content: '已打开已有任务',
payload: {
task_no: 'SN-OPEN-EXISTING',
batch_no: 'SB-OPEN-EXISTING',
shipping_ui_state: {
task_no: 'SN-OPEN-EXISTING',
batch_no: 'SB-OPEN-EXISTING',
process_status: 'waiting_inventory',
steps: [],
summary: {},
action_buttons: [],
},
},
},
]);
expect(payload?.task_no).toBe('SN-OPEN-EXISTING');
expect(payload?.batch_no).toBe('SB-OPEN-EXISTING');
expect(payload?.shipping_ui_state?.task_no).toBe('SN-OPEN-EXISTING');
expect(payload?.shipping_batch_ui_state).toBeUndefined();
});
});
@@ -30,7 +30,6 @@ import {
createShippingSendHandlers,
createShippingUploadHandlers,
onNoticeBatchConversationChanging,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
getShippingMatchResultPayload,
@@ -48,6 +47,8 @@ import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
listWorkspaceShippingCustomerOptions,
confirmWorkspaceShippingCustomer,
switchWorkspaceShippingBatchFocusTask,
type ShippingBatchUiState,
type ShippingBatchSummary,
@@ -55,13 +56,15 @@ import {
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import type { ShippingCustomerOption } from '../types/shipping.api.types';
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
import {
hasShortageLines,
isShippingShortageQueryIntent,
} from '../shipping/shippingShortageDetails';
import type { ChatMessage, ChatRun, ChatSessionItem } from '../types/chat.types';
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
import type { SendMessageLifecycleHooks } from './useChat';
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
import { listChatMessages } from '../api/chat.api';
@@ -94,8 +97,8 @@ export interface UseChatShippingOptions {
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>;
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
@@ -130,6 +133,104 @@ export const resolveShippingBatchFocusState = (
};
};
/**
* 从会话工作台选择本轮应展示的批次。
* 核心逻辑:订单抽取完成后选服务端按创建时间升序返回的最后一个批次;普通续办优先保留当前批次。
*/
export const selectShippingConversationBatch = <T extends { batch_no: string; focus_task?: unknown }>(
batches: T[],
currentBatchNo: string,
queryBatchNo: string,
preferLatest = false,
): T | undefined => (
(preferLatest ? batches[batches.length - 1] : undefined)
|| batches.find((item) => item.batch_no === currentBatchNo)
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : undefined)
|| batches.find((item) => Boolean(item.focus_task))
|| batches[0]
);
/**
* 从消息列表解析最近一次权威批次快照。
* 核心逻辑:只接受包含批次号和任务数组的 `shipping_batch_ui_state`,供实时终态与历史会话共用。
* @param sourceMessages - 当前会话消息
* @returns 最近的合法批次快照;不存在时返回 null
*/
export const resolveLatestShippingBatchSnapshot = (
sourceMessages: ChatMessage[],
): ShippingBatchUiState | null => {
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
const message = sourceMessages[index];
const payload = message?.payload && typeof message.payload === 'object'
? message.payload as Record<string, unknown>
: null;
const rawSnapshot = payload?.shipping_batch_ui_state;
if (!rawSnapshot || typeof rawSnapshot !== 'object') continue;
const snapshot = rawSnapshot as ShippingBatchUiState;
if (String(snapshot.batch_no || '').trim() && Array.isArray(snapshot.tasks)) {
return snapshot;
}
}
return null;
};
/**
* 从单条助手消息中提取工作台恢复锚点。
* 核心逻辑:优先识别合法 `shipping_batch_ui_state`,其次回退到 `task_no / batch_no / shipping_ui_state`;
* 供实时终态、历史回放与刷新恢复共用。
*/
export const resolveShippingMessageRecoveryPayload = (
message: ChatMessage | null | undefined,
): ShippingMessageRecoveryPayload | null => {
const payload = message?.payload && typeof message.payload === 'object'
? message.payload as ShippingMessageRecoveryPayload
: null;
if (!payload) return null;
const batchSnapshot = payload.shipping_batch_ui_state;
const hasBatchSnapshot = Boolean(
batchSnapshot
&& String(batchSnapshot.batch_no || '').trim()
&& Array.isArray(batchSnapshot.tasks),
);
const taskNo = String(
payload.task_no
|| payload.shipping_ui_state?.task_no
|| batchSnapshot?.current_focus_task_no
|| batchSnapshot?.focus_task?.task_no
|| batchSnapshot?.tasks?.[0]?.task_no
|| '',
).trim();
const batchNo = String(
payload.batch_no
|| payload.shipping_ui_state?.batch_no
|| batchSnapshot?.batch_no
|| '',
).trim();
const hasTaskUiState = Boolean(payload.shipping_ui_state && typeof payload.shipping_ui_state === 'object');
if (!hasBatchSnapshot && !taskNo && !batchNo && !hasTaskUiState) {
return null;
}
return {
...payload,
...(taskNo ? { task_no: taskNo } : {}),
...(batchNo ? { batch_no: batchNo } : {}),
};
};
/**
* 从消息列表中选择最近一条可恢复工作台的消息载荷。
* 核心逻辑:从后往前找最近的权威恢复锚点,允许 `open_existing` 只靠 `task_no/ui_state` 恢复。
*/
export const resolveLatestShippingMessageRecoveryPayload = (
sourceMessages: ChatMessage[],
): ShippingMessageRecoveryPayload | null => {
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
const payload = resolveShippingMessageRecoveryPayload(sourceMessages[index]);
if (payload) return payload;
}
return null;
};
/**
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
*
@@ -163,7 +264,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
sendMessage,
startChatTurn,
buildFileSpecsForSend,
loadConversation,
createNewChatView,
} = options;
@@ -280,34 +380,152 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
};
const applyConversationWorkspaceFocus = (workspace: ShippingConversationWorkspace) => {
const applyConversationWorkspaceFocus = (
workspace: ShippingConversationWorkspace,
options?: { preferLatest?: boolean },
) => {
const batches = Array.isArray(workspace.batches) ? workspace.batches : [];
if (!batches.length) return;
const queryBatchNo = String(shippingBatchNoFromQuery.value || '').trim();
const currentBatchNo = String(activeShippingBatchNo.value || resolvedShippingBatchNo.value || queryBatchNo || '').trim();
const selectedBatch = batches.find((item) => item.batch_no === currentBatchNo)
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : null)
|| batches.find((item) => item.focus_task?.task_no)
|| batches[0];
const selectedBatch = selectShippingConversationBatch(
batches,
currentBatchNo,
queryBatchNo,
Boolean(options?.preferLatest),
);
if (!selectedBatch) return;
if (options?.preferLatest) {
activeShippingBatchNo.value = selectedBatch.batch_no;
}
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
};
const syncShippingConversationWorkspace = async () => {
const syncShippingConversationWorkspace = async (
options?: { preferLatest?: boolean },
): Promise<boolean> => {
const localConversationId = String(conversationId.value || '').trim();
if (!localConversationId || !isShippingNoticeAgent.value) {
shippingConversationWorkspace.value = null;
return;
return false;
}
try {
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
shippingConversationWorkspace.value = workspace;
applyConversationWorkspaceFocus(workspace);
applyConversationWorkspaceFocus(workspace, options);
return true;
} catch {
shippingConversationWorkspace.value = null;
return false;
}
};
/**
* 从本轮 SSE 助手消息恢复权威批次快照。
*
* 核心逻辑:订单识别可能打开属于旧会话的已有任务,此时按当前会话补拉工作台会返回空批次;
* 优先应用 `shipping_ui_state` 事件随消息持久化的 `shipping_batch_ui_state`,再由接口刷新后续状态。
* @param message - 当前流式回答完成后的助手消息
* @returns 是否找到并应用了合法批次快照
*/
const applyResolvedShippingBatchSnapshot = (snapshot: ShippingBatchUiState | null): boolean => {
if (!snapshot) return false;
const batchNo = String(snapshot.batch_no || '').trim();
applyShippingBatchDetail(snapshot, batchNo);
return true;
};
const applyShippingBatchSnapshot = (message: ChatMessage): boolean => (
applyResolvedShippingBatchSnapshot(resolveLatestShippingBatchSnapshot([message]))
);
/**
* 按“批次快照 -> 任务/批次锚点 -> 会话工作台”顺序恢复聊天工作台。
*
* 核心逻辑:`open_existing` 可能只携带 `task_no / shipping_ui_state`;此时先恢复任务锚点并补拉任务详情,
* 再尝试按任务所属批次加载批次详情,最后才回退到当前会话工作台。
* @param payload - 从消息中解析出的恢复载荷
* @returns 是否至少恢复出一层任务或批次上下文
*/
const applyResolvedShippingMessageRecovery = async (
payload: ShippingMessageRecoveryPayload | null,
): Promise<boolean> => {
if (!payload) return false;
let recovered = false;
const snapshot = payload.shipping_batch_ui_state ?? null;
if (applyResolvedShippingBatchSnapshot(snapshot)) {
recovered = true;
}
const taskNo = String(
payload.task_no
|| payload.shipping_ui_state?.task_no
|| '',
).trim().toUpperCase();
let batchNo = String(
payload.batch_no
|| payload.shipping_ui_state?.batch_no
|| snapshot?.batch_no
|| '',
).trim();
if (batchNo) {
resolvedShippingBatchNo.value = batchNo;
activeShippingBatchNo.value = batchNo;
}
if (taskNo) {
resolvedShippingTaskId.value = taskNo;
focusedShippingTaskNo.value = taskNo;
if (!shippingFocusReason.value) {
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
}
}
if (payload.shipping_ui_state && taskNo) {
activeShippingTaskDetail.value = {
...(activeShippingTaskDetail.value || {}),
task_no: taskNo,
batch_no: batchNo || payload.shipping_ui_state.batch_no || null,
lines: activeShippingTaskDetail.value?.lines || [],
events: activeShippingTaskDetail.value?.events || [],
ui_state: payload.shipping_ui_state,
} as ShippingTaskDetail;
recovered = true;
}
if (!snapshot && batchNo) {
try {
const detail = await getWorkspaceShippingBatch(batchNo);
applyShippingBatchDetail(detail, batchNo);
recovered = true;
} catch {
// ignore and continue with task-first recovery
}
}
if (taskNo) {
await syncActiveShippingTaskDetail(taskNo);
const detailBatchNo = String(activeShippingTaskDetail.value?.batch_no || '').trim();
if (detailBatchNo) {
batchNo = detailBatchNo;
resolvedShippingBatchNo.value = detailBatchNo;
activeShippingBatchNo.value = detailBatchNo;
}
if (!snapshot && batchNo && String(shippingBatchSummary.value?.batch_no || '').trim() !== batchNo) {
try {
const detail = await getWorkspaceShippingBatch(batchNo);
applyShippingBatchDetail(detail, batchNo);
recovered = true;
} catch {
// ignore and keep task-only recovery
}
}
recovered = recovered || Boolean(activeShippingTaskDetail.value);
}
return recovered || Boolean(batchNo);
};
const applyShippingMessageRecovery = async (message: ChatMessage): Promise<boolean> => (
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
);
const switchShippingFocusTask = async (taskNo: string) => {
const batchNo = getActiveShippingBatchNo();
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
@@ -529,7 +747,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
messages,
conversationId,
isThinking,
history,
resolvedShippingTaskId,
shippingTaskIdFromQuery,
getActiveBatchTaskId,
@@ -563,6 +780,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
const finalizeShippingAssistantMessage = async () => {
if (!isShippingNoticeAgent.value) return;
await shippingIntakes.refreshStatuses();
if (!(await syncShippingConversationWorkspace())) {
await new Promise((resolve) => setTimeout(resolve, 300));
await syncShippingConversationWorkspace();
}
shippingIntakes.clearConsumedAttachments();
await refreshShippingActions();
};
@@ -672,6 +893,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
});
const showShippingDuplicateDialog = ref(false);
const showShippingCustomerDialog = ref(false);
const shippingCustomerDialogTaskId = ref('');
const shippingCustomerOptions = ref<ShippingCustomerOption[]>([]);
const shippingCustomerLoading = ref(false);
const shippingDuplicateAttachmentId = ref<string | null>(null);
const shippingDuplicateAttachment = computed(() => {
const id = shippingDuplicateAttachmentId.value;
@@ -733,6 +958,50 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingDuplicateAttachmentId.value = null;
};
/** 打开客户确认对话框并加载启用标准客户。 */
const openShippingCustomerDialog = async (taskId: string): Promise<void> => {
shippingCustomerDialogTaskId.value = String(taskId || '').trim().toUpperCase();
showShippingCustomerDialog.value = true;
shippingCustomerLoading.value = true;
try {
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions();
} catch (error: unknown) {
shippingCustomerOptions.value = [];
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
shippingCustomerLoading.value = false;
}
};
/** 按关键词刷新客户选项。 */
const searchShippingCustomers = async (query: string): Promise<void> => {
shippingCustomerLoading.value = true;
try {
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions(query);
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
shippingCustomerLoading.value = false;
}
};
/** 确认客户后刷新任务详情与动作菜单;业务号仍由后续阶段生成。 */
const confirmShippingCustomer = async (customerId: number): Promise<void> => {
const taskId = shippingCustomerDialogTaskId.value;
if (!taskId) return;
shippingCustomerLoading.value = true;
try {
await confirmWorkspaceShippingCustomer(taskId, customerId);
showShippingCustomerDialog.value = false;
await Promise.all([syncActiveShippingTaskDetail(taskId), refreshShippingActions()]);
msg.success(t('chat.shippingCustomer.confirmed'));
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.confirmFailed'));
} finally {
shippingCustomerLoading.value = false;
}
};
/** 更新 Candidate 选择状态,并将 API 失败统一反馈给用户。 */
const setShippingCandidateSelected = async (candidateNo: string, selected: boolean) => {
try {
@@ -825,6 +1094,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
openShippingNoticePicker,
openShippingCustomerDialog,
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
@@ -870,8 +1140,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
hasSelectedNoticeCandidates: () => shippingIntakes.getSelectedCandidateNos().length > 0,
openShippingDuplicateDialog,
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
markOrderExtractionStarted: shippingIntakes.markOrderExtractionStarted,
rollbackOrderExtractionStarted: shippingIntakes.rollbackOrderExtractionStarted,
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
applyShippingMessageRecovery,
applyShippingBatchSnapshot,
syncShippingConversationWorkspace,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
@@ -881,6 +1156,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
});
// ── 路由 / 会话生命周期 ───────────────────────────────────
/**
* 根据路由中的 `task_id/batch_no` 恢复发货任务上下文。
* 核心逻辑:优先同步显式传入的批次摘要;若仍缺少会话,则直接基于 `task_id` 发起一次继续任务请求,
* 禁止再按历史标题模糊猜测旧会话,避免多批次/多票场景跳进错误会话。
* @returns Promise<void>
*/
const resumeShippingTaskFromQuery = async () => {
const batchNo = shippingBatchNoFromQuery.value;
if (batchNo && isShippingNoticeAgent.value) {
@@ -894,11 +1175,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
if (route.query.conversation_id) return;
if (presetQuestion.value) return;
if (autoResumedShippingTasks.value[taskId]) return;
const existing = findHistorySessionForShippingTask(history.value, taskId);
if (existing) {
await loadConversation(existing.conversation_id, { force: true });
return;
}
autoResumedShippingTasks.value[taskId] = true;
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId });
await sendMessage(
@@ -1010,6 +1286,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
kind: 'local',
file,
type: kind === 'inventory' ? 'document' : 'document',
uploadStatus: 'waiting',
uploadProgress: 0,
},
];
}
@@ -1089,6 +1367,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
String(last?.content || '').slice(-120),
].join('|');
});
const shippingRecoveryWatchKey = computed(() => {
const recovery = resolveLatestShippingMessageRecoveryPayload(messages.value);
const snapshot = recovery?.shipping_batch_ui_state;
const uiState = recovery?.shipping_ui_state;
return [
String(conversationId.value || ''),
String(recovery?.batch_no || snapshot?.batch_no || uiState?.batch_no || ''),
String(recovery?.task_no || snapshot?.current_focus_task_no || uiState?.task_no || ''),
String(snapshot?.updated_at || ''),
String(uiState?.updated_at || ''),
String(snapshot?.tasks.length || 0),
].join('|');
});
watch([shippingRecoveryWatchKey, isShippingNoticeAgent], () => {
if (!isShippingNoticeAgent.value) return;
void applyResolvedShippingMessageRecovery(resolveLatestShippingMessageRecoveryPayload(messages.value));
}, { immediate: true });
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions().then(async () => {
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
@@ -1188,6 +1483,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
updateShippingCandidateSummary,
resolveShippingCandidateDuplicate,
showShippingDuplicateDialog,
showShippingCustomerDialog,
shippingCustomerOptions,
shippingCustomerLoading,
searchShippingCustomers,
confirmShippingCustomer,
closeShippingCustomerDialog: () => {
showShippingCustomerDialog.value = false;
},
shippingDuplicateAttachment,
canForceCreateShippingDuplicate,
openShippingDuplicateDialog,
@@ -9,7 +9,10 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatRun } from '../types/chat.types';
import { applyShippingUiStateToMessage } from './useChat';
import {
applyShippingOrderExtractionStateToMessage,
applyShippingUiStateToMessage,
} from './useChat';
export interface CreateStartChatTurnOptions {
messages: Ref<ChatMessage[]>;
@@ -169,6 +172,9 @@ export function createStartChatTurn(options: CreateStartChatTurnOptions) {
if (eventName === 'shipping_ui_state' || eventName === 'ui_state.updated') {
const botMsg = ensureBotMessage();
if (botMsg) applyShippingUiStateToMessage(botMsg, data);
} else if (eventName === 'shipping_order_extraction_state') {
const botMsg = ensureBotMessage();
if (botMsg) applyShippingOrderExtractionStateToMessage(botMsg, data);
} else if (
eventName === 'message'
|| eventName === 'agent_message'