Files
syops/frontend/src/features/chat/page/useChatPageConversation.spec.ts
T
hugo 5ef8329bd8 refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段
统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成
设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程
删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本
替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段
更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
2026-08-15 10:19:10 +08:00

217 lines
8.4 KiB
TypeScript

/**
* features/chat/page/useChatPageConversation.spec.ts
* 用途:验证新建聊天与 Agent 切换时清理发货通知外围状态。
* 依赖:vitest、vue refs/computed、useChatPageConversation、useChatShippingUploadHandler。
* 逻辑:覆盖 createNewChatView / Agent 切换调用 peripheral reset;建批幂等已随 co8 下线。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createChatPageConversationApi } from './useChatPageConversation';
import {
clearPendingNoticeBatchRetry,
createShippingUploadHandlers,
resetShippingNoticeBatchSubmitStateForTests,
type ShippingUploadHandlerContext,
} from '../shipping/useChatShippingUploadHandler';
const { listChatMessages } = vi.hoisted(() => ({
listChatMessages: vi.fn(),
}));
vi.mock('../api/chat.api', () => ({
listChatMessages,
}));
const createConversationContext = () => {
const conversationId = ref<string | null>('conv-a');
const messages = ref<any[]>([{ role: 'assistant', content: 'old-a' }]);
const createNewChatView = vi.fn(() => {
conversationId.value = null;
messages.value = [];
});
const resetPeripheralState = vi.fn();
return {
conversationId,
messages,
createNewChatView,
api: createChatPageConversationApi({
deps: { t: (key: string) => key, msg: { warning: vi.fn() } },
route: { path: '/chat/42', query: {} } as never,
router: { replace: vi.fn() } as never,
currentAgentId: computed(() => 42),
conversationId,
activeRunId: ref(null),
messages,
isThinking: ref(false),
loadConversationState: (id, loaded) => {
conversationId.value = id;
messages.value = loaded;
},
createNewChatView,
clearPendingNoticeBatchRetry,
onConversationIdChanging: vi.fn(),
onConversationLoadedEmpty: vi.fn(async () => undefined),
onConversationLoadFailed: vi.fn(async () => undefined),
isShippingNoticeAgent: computed(() => true),
shippingTaskIdFromQuery: computed(() => ''),
shippingBatchNoFromQuery: computed(() => ''),
clearHistory: vi.fn(),
clearAttachments: vi.fn(),
input: ref(''),
resetCurrentAgent: vi.fn(),
copiedIndex: ref(null),
resetPeripheralState,
filePreviewVisible: ref(false),
previewFile: ref(null),
previewFiles: ref([]),
currentPreviewIndex: ref(0),
}),
resetPeripheralState,
};
};
const createUploadContext = (
conversationId: ReturnType<typeof ref<string | null>>,
enqueueNoticeFiles: ReturnType<typeof vi.fn>,
): ShippingUploadHandlerContext => ({
conversationId,
currentAgentId: computed(() => 42),
attachments: ref([]),
input: ref(''),
shippingAutoFlowRequested: ref(false),
shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
pendingShippingUploadTaskId: ref(''),
pendingShippingNoticeTaskId: ref(''),
pendingShippingInventoryFile: ref(null),
resolvedShippingTaskId: ref(''),
resolvedShippingBatchNo: ref(''),
shippingBatchSummary: ref(null),
shippingBatchTasks: ref([]),
shippingInventorySelectionActive: ref(false),
shippingInventorySelectionTaskId: ref(''),
getActiveShippingTaskId: () => '',
startChatTurn: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
msg: { warning: vi.fn(), info: vi.fn() },
t: (key: string) => key,
enqueueNoticeFiles,
startOrderExtractionRun: vi.fn(async () => true),
sendTemporaryInventoryMessage: vi.fn(async () => undefined),
});
describe('useChatPageConversation', () => {
beforeEach(() => {
listChatMessages.mockReset();
resetShippingNoticeBatchSubmitStateForTests();
});
it('startNewChat clears peripheral state and subsequent notice upload still enqueues intakes', async () => {
const enqueueNoticeFiles = vi.fn(async () => undefined);
const { conversationId, createNewChatView, api } = createConversationContext();
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
createUploadContext(conversationId, enqueueNoticeFiles),
);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
api.startNewChat();
expect(createNewChatView).toHaveBeenCalledTimes(1);
expect(conversationId.value).toBeNull();
await handleShippingAutoUploadNoticeBatch([file]);
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2);
});
it('startNewChat calls peripheral reset so a shipping Run cannot remain visible in the blank view', () => {
const { api, resetPeripheralState } = createConversationContext();
api.startNewChat();
// 关键断言:Shipping 状态在 useChatShipping.resetShippingConversationState 中随该回调清理。
expect(resetPeripheralState).toHaveBeenCalledTimes(1);
});
it('resetChatStateForAgentChange clears peripheral state and subsequent notice upload still enqueues intakes', async () => {
const enqueueNoticeFiles = vi.fn(async () => undefined);
const { conversationId, createNewChatView, api } = createConversationContext();
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
createUploadContext(conversationId, enqueueNoticeFiles),
);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
api.resetChatStateForAgentChange();
expect(createNewChatView).toHaveBeenCalledTimes(1);
expect(conversationId.value).toBeNull();
await handleShippingAutoUploadNoticeBatch([file]);
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2);
});
it('clears the previous conversation messages before an uncached history request resolves', async () => {
let resolveMessages!: (value: any[]) => void;
listChatMessages.mockImplementation(() => new Promise((resolve) => { resolveMessages = resolve; }));
const { api, messages, conversationId } = createConversationContext();
const pending = api.loadConversation('conv-b', { force: true });
// 会话已切换但 B 尚无本地快照时,绝不能继续显示 A 的消息/订单卡。
expect(conversationId.value).toBe('conv-b');
expect(messages.value).toEqual([]);
resolveMessages([{ role: 'assistant', content: 'loaded-b' }]);
await pending;
expect(messages.value[0]?.content).toBe('loaded-b');
});
it('restores cached messages immediately and discards a late response from an older selection', async () => {
const pending = new Map<string, { resolve: (value: any[]) => void }>();
listChatMessages.mockImplementation((id: string) => new Promise((resolve) => {
pending.set(id, { resolve });
}));
const { api, messages, conversationId } = createConversationContext();
const firstB = api.loadConversation('conv-b', { force: true });
pending.get('conv-b')!.resolve([{ role: 'assistant', content: 'cached-b' }]);
await firstB;
const selectA = api.loadConversation('conv-a', { force: true });
const returnB = api.loadConversation('conv-b', { force: true });
expect(messages.value[0]?.content).toBe('cached-b');
pending.get('conv-a')!.resolve([{ role: 'assistant', content: 'late-a' }]);
pending.get('conv-b')!.resolve([{ role: 'assistant', content: 'cached-b' }]);
await Promise.all([selectA, returnB]);
expect(conversationId.value).toBe('conv-b');
expect(messages.value[0]?.content).toBe('cached-b');
});
it('keeps the rendered cached message array when revalidation is semantically unchanged', async () => {
const pending = new Map<string, { resolve: (value: any[]) => void }>();
listChatMessages.mockImplementation((id: string) => new Promise((resolve) => {
pending.set(id, { resolve });
}));
const { api, messages } = createConversationContext();
const initial = api.loadConversation('conv-b', { force: true });
pending.get('conv-b')!.resolve([{ chat_log_id: 91, role: 'assistant', content: 'stable-b' }]);
await initial;
const revalidate = api.loadConversation('conv-b', { force: true });
const renderedCache = messages.value;
pending.get('conv-b')!.resolve([{ chat_log_id: 91, role: 'assistant', content: 'stable-b' }]);
await revalidate;
expect(messages.value).toBe(renderedCache);
});
});