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

@@ -36,6 +36,7 @@ vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({
const createConversationContext = () => {
const conversationId = ref<string | null>('conv-a');
const messages = ref([]);
const loadConversationState = vi.fn();
const createNewChatView = vi.fn(() => {
conversationId.value = null;
messages.value = [];
@@ -44,6 +45,7 @@ const createConversationContext = () => {
return {
conversationId,
messages,
loadConversationState,
createNewChatView,
api: createChatPageConversationApi({
deps: { t: (key: string) => key, msg: { warning: vi.fn() } },
@@ -54,7 +56,7 @@ const createConversationContext = () => {
activeRunId: ref(null),
messages,
isThinking: ref(false),
loadConversationState: vi.fn(),
loadConversationState,
createNewChatView,
clearPendingNoticeBatchRetry,
onConversationIdChanging: vi.fn(),
@@ -163,4 +165,32 @@ describe('useChatPageConversation', () => {
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('loadConversation keeps attachment-only history snapshots intact', async () => {
const { api, loadConversationState } = createConversationContext();
listChatMessages.mockResolvedValue([{
role: 'user',
content: '',
attachments: [{
id: 'attachment-only-1',
name: 'notice.eml',
type: 'document',
source: 'shipping_notice',
}],
}]);
await api.loadConversation('conv-attachment-only', { force: true });
expect(listChatMessages).toHaveBeenCalledWith('conv-attachment-only', 42);
expect(loadConversationState).toHaveBeenCalledWith('conv-attachment-only', [{
role: 'user',
content: '',
attachments: [{
id: 'attachment-only-1',
name: 'notice.eml',
type: 'document',
source: 'shipping_notice',
}],
}]);
});
});
@@ -0,0 +1,87 @@
/**
* features/chat/page/useChatPageMarkdown.spec.ts
* 用途:验证聊天消息可见性与思考提示在订单识别生命周期中的切换行为。
* 依赖:Vitest、Vue 响应式 API、useChatPageMarkdown。
* 逻辑:构造最小 Markdown 上下文,确保空正文的订单识别状态可见且替代通用思考提示。
*/
import { ref } from 'vue';
import { describe, expect, it } from 'vitest';
import type { ChatMessage } from '../types/chat.types';
import {
createChatPageMarkdownApi,
type ChatPageMarkdownContext,
} from './useChatPageMarkdown';
/**
* 创建消息可见性测试所需的最小 Markdown 上下文。
* 核心逻辑:所有外部解析器返回空结果,让断言只受消息正文和订单识别状态影响。
* @param messages - 当前聊天消息列表。
* @param isThinking - 是否仍在等待助手回复。
* @returns 可直接传给 createChatPageMarkdownApi 的上下文。
*/
function createContext(
messages: ChatMessage[],
isThinking = true,
): ChatPageMarkdownContext {
return {
messages: ref(messages),
isThinking: ref(isThinking),
prepareMarkdownDisplayText: (text) => text,
handleLeaveMarkdownClick: () => undefined,
parsePlmPreviewLink: () => null,
openPreview: async () => undefined,
openAssetHistory: () => undefined,
openAssetImage: () => undefined,
getMessageLinks: () => [],
getDisplayRetrieverResources: () => [],
getSourceLinks: () => [],
shouldExpandSourceDetails: () => false,
getSourceTitle: () => '',
getSourceMeta: () => '',
getSourceBrief: () => '',
getShippingInventoryMappingPayload: () => null,
getShippingMatchResultPayload: () => null,
canOpenQueryPreview: () => false,
getQueryPreviewSummary: () => '',
openQueryPreviewDialog: () => undefined,
shippingActionButtonClass: () => '',
onShippingActionClick: () => undefined,
};
}
const extractionMessage: ChatMessage = {
role: 'assistant',
content: '',
shipping_order_extraction_state: {
status: 'extracting',
phase: 'llm_extraction',
message: '正在识别邮件及附件中的订单',
created_count: 0,
opened_existing_count: 0,
pending_count: 0,
non_shipping_count: 0,
created_with_missing_fields_count: 0,
batch_no: null,
terminal: false,
},
};
describe('useChatPageMarkdown order extraction visibility', () => {
it('renders an extraction-state message before Dify content arrives', () => {
const api = createChatPageMarkdownApi(createContext([]));
// 关键断言:结构化进度不能因为 assistant 正文为空而被消息过滤器隐藏。
expect(api.shouldRenderMessage(extractionMessage)).toBe(true);
expect(api.shouldRenderMessage({ role: 'assistant', content: '' })).toBe(false);
});
it('hides the generic thinking bubble when extraction progress is visible', () => {
const api = createChatPageMarkdownApi(createContext([
{ role: 'user', content: '请解析当前邮件中的发货订单' },
extractionMessage,
]));
// 关键断言:领域进度已出现时不再叠加通用“思考中”,避免重复反馈。
expect(api.shouldShowThinkingBubble.value).toBe(false);
});
});
@@ -338,10 +338,18 @@ function enhanceAssetHistoryTableLinks(html: string): string {
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const message = useMessage();
/**
* 判断消息是否具备可展示内容。
* 核心逻辑:订单识别状态本身就是用户可见反馈,即使 Dify 正文尚未到达也必须渲染;
* 其余消息继续沿用正文、链接、引用源和结构化消息的既有判断。
* @param msgItem - 当前聊天消息。
* @returns 消息是否应进入聊天列表渲染。
*/
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
if (msgItem?.type === 'shipping-parse-review') return false;
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
if (msgItem?.shipping_order_extraction_state) return true;
const content = (msgItem?.content || '').trim();
if (content) return true;
if (ctx.getMessageLinks(msgItem as unknown as Record<string, unknown>).length > 0) return true;
@@ -356,6 +364,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
*/
const hasMeaningfulAssistantReply = (msgItem: ChatMessage): boolean => {
if (msgItem?.role !== 'assistant') return false;
if (msgItem?.shipping_order_extraction_state) return true;
if (msgItem?.type === 'leave-form'
|| msgItem?.type === 'leave-confirmation'
|| msgItem?.type === 'leave-result'
@@ -0,0 +1,121 @@
/**
* features/chat/page/useChatPageSend.spec.ts
* 用途:验证普通聊天发送时附件失败保留、消息成功后清空的恢复语义。
* 依赖:Vitest、Vue 响应式 API、useChatPageSend。
* 逻辑:构造最小发送上下文,分别模拟上传失败、SSE 发送失败与发送成功。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
import { createChatPageSendApi, type ChatPageSendContext } from './useChatPageSend';
import type { ChatMessageAttachment } from '../types/chat.types';
const attachmentSnapshots: ChatMessageAttachment[] = [{
id: 'attachment-1',
name: 'purchase-order.pdf',
size: 3,
extension: 'pdf',
type: 'document',
source: 'local',
}];
/** 创建普通聊天发送测试上下文。 */
function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSendContext {
return {
input: ref('请分析附件'),
messages: ref([]),
isThinking: ref(false),
currentAgentId: computed(() => 1),
selectedKb: ref(''),
isUploadingAttachments: ref(false),
attachmentPolicy: computed(() => ({ anyEnabled: true })),
attachments: ref([{ id: 'attachment-1' }]),
allowsSendWithAttachmentsOnly: computed(() => true),
buildFileSpecsForSend: vi.fn(async () => [
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' },
]),
createMessageAttachmentSnapshots: vi.fn(() => attachmentSnapshots.map((item) => ({ ...item }))),
clearAttachments: vi.fn(),
sendMessage: vi.fn(async () => true),
refreshHistoryAfterSend: vi.fn(async () => undefined),
refreshConversationAfterSend: vi.fn(async () => undefined),
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
tryHandleLeaveSend: vi.fn(() => false),
tryHandleShippingSend: vi.fn(async () => false),
refreshToolRunProgressAfterSend: vi.fn(async () => undefined),
prepareToolRunProgressBeforeSend: vi.fn(async () => undefined),
msg: { warning: vi.fn(), info: vi.fn() },
t: (key: string) => key,
copiedIndex: ref(null),
...overrides,
};
}
describe('createChatPageSendApi attachment lifecycle', () => {
it('keeps attachments when file upload fails', async () => {
const ctx = createContext({
buildFileSpecsForSend: vi.fn(async () => { throw new Error('upload failed'); }),
});
await createChatPageSendApi(ctx).handleSend();
expect(ctx.clearAttachments).not.toHaveBeenCalled();
expect(ctx.sendMessage).not.toHaveBeenCalled();
});
it('keeps uploaded attachments when message sending fails', async () => {
const ctx = createContext({
sendMessage: vi.fn(async () => { throw new Error('stream failed'); }),
});
await expect(createChatPageSendApi(ctx).handleSend()).rejects.toThrow('stream failed');
expect(ctx.clearAttachments).not.toHaveBeenCalled();
});
it('keeps uploaded attachments when the real send result reports failure', async () => {
const ctx = createContext({
sendMessage: vi.fn(async () => false),
});
await createChatPageSendApi(ctx).handleSend();
expect(ctx.clearAttachments).not.toHaveBeenCalled();
expect(ctx.refreshHistoryAfterSend).not.toHaveBeenCalled();
});
it('clears attachments only after message sending succeeds', async () => {
const ctx = createContext();
await createChatPageSendApi(ctx).handleSend();
expect(ctx.sendMessage).toHaveBeenCalledOnce();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'请分析附件',
1,
'',
[{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }],
undefined,
expect.objectContaining({ userAttachments: attachmentSnapshots }),
);
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
expect(vi.mocked(ctx.sendMessage).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(ctx.clearAttachments).mock.invocationCallOrder[0],
);
});
it('sends attachment-only messages with an internal prompt and an empty display query', async () => {
const ctx = createContext({ input: ref('') });
await createChatPageSendApi(ctx).handleSend();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'chat.attachment.defaultPrompt',
1,
'',
[{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }],
{ display_query: '' },
expect.objectContaining({ userAttachments: attachmentSnapshots }),
);
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
});
});
@@ -1,10 +1,14 @@
/**
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
* features/chat/page/useChatPageSend.ts
* 用途:编排聊天消息发送、业务前置拦截、复制与重新生成。
* 依赖:统一 BusinessError、剪贴板工具、Chat 消息与附件参数类型。
* 逻辑:附件上传成功后调用 Dify SSE;仅在消息发送成功后清空附件,失败时保留供重试。
*/
import { computed } from 'vue';
import { BusinessError } from '@/shared/api/client';
import { copyTextToClipboard } from '@/shared/utils/clipboard';
import type { ChatMessage } from '../types/chat.types';
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
import type { SendMessageLifecycleHooks } from '../composables/useChat';
import type { ChatUploadFileSpec } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
@@ -42,6 +46,7 @@ export interface ChatPageSendContext {
attachments: Ref<unknown[]>;
allowsSendWithAttachmentsOnly: ComputedRef<boolean>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
createMessageAttachmentSnapshots: () => ChatMessageAttachment[];
clearAttachments: () => void;
sendMessage: (
content: string,
@@ -49,8 +54,8 @@ export interface ChatPageSendContext {
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>;
refreshHistoryAfterSend: () => Promise<void>;
refreshConversationAfterSend?: () => Promise<void>;
tryHandleShippingAttachmentAutoFlow: (
@@ -78,6 +83,11 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
if (ctx.isUploadingAttachments.value) return false;
if (ctx.input.value.trim()) return !ctx.isThinking.value || allowSendWhileThinking;
if (
ctx.attachments.value.length > 0
&& ctx.attachmentPolicy.value.anyEnabled
&& (!ctx.isThinking.value || allowSendWhileThinking)
) return true;
if (ctx.allowsSendWithAttachmentsOnly.value) return true;
return false;
});
@@ -85,11 +95,12 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || ctx.input.value;
const trimmed = content.trim();
const hasAttachments = ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0;
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
return;
}
if (!trimmed || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
if ((!trimmed && !hasAttachments) || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
return;
}
if (ctx.tryHandleLeaveSend(content)) {
@@ -100,9 +111,11 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
}
let files: ChatUploadFileSpec[] = [];
let messageAttachments: ChatMessageAttachment[] = [];
if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) {
try {
files = await ctx.buildFileSpecsForSend();
messageAttachments = ctx.createMessageAttachmentSnapshots();
} catch (e: unknown) {
let suffix = '';
if (e instanceof BusinessError) {
@@ -121,17 +134,26 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
}
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.clearAttachments();
const requestContent = trimmed || ctx.t('chat.attachment.defaultPrompt');
const sendContext = {
...(ctx.getChatContext?.() || {}),
...(!trimmed && messageAttachments.length > 0 ? { display_query: '' } : {}),
};
await ctx.prepareToolRunProgressBeforeSend();
await ctx.sendMessage(
content,
const sent = await ctx.sendMessage(
requestContent,
ctx.currentAgentId.value,
ctx.selectedKb.value,
files,
ctx.getChatContext?.(),
{ onAssistantMessageFinished: ctx.onAssistantMessageFinished },
Object.keys(sendContext).length > 0 ? sendContext : undefined,
{
userAttachments: messageAttachments,
onAssistantMessageFinished: ctx.onAssistantMessageFinished,
},
);
if (sent === false) return;
ctx.clearAttachments();
await ctx.refreshHistoryAfterSend();
await ctx.refreshConversationAfterSend?.();
await ctx.refreshToolRunProgressAfterSend();