feat(shipping-notice): 增加发货通知建单幂等性支持及内容哈希校验

This commit is contained in:
hugo committed 2026-07-14 00:28:52 +08:00
1 parent 0a9bd6415d
commit 143e054d86
39 files changed
+1750 -80

No files matched your search

+17 -2
View File
@@ -222,15 +222,30 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F
* @param conversationId - 可选会话 ID
* @returns 批次与任务创建结果
*/
export async function createWorkspaceShippingBatchFromNotices(files: File[], conversationId?: string) {
export async function createWorkspaceShippingBatchFromNotices(
files: File[],
conversationId?: string,
idempotencyKey?: string,
) {
const form = new FormData();
files.forEach((file) => form.append('files', file));
if (conversationId) form.append('conversation_id', conversationId);
if (idempotencyKey) form.append('idempotency_key', idempotencyKey);
const headers: Record<string, string> = {};
if (idempotencyKey) {
headers['Idempotency-Key'] = idempotencyKey;
}
const body = await requestJson<ShippingNoticeUploadResponse & ShippingApiStatusPayload & {
error?: string;
batch_no?: string;
idempotent_replay?: boolean;
file_summary?: unknown;
data?: unknown;
}>('/api/workspace/shipping-batches/create-from-notices', { method: 'POST', body: form });
}>('/api/workspace/shipping-batches/create-from-notices', {
method: 'POST',
body: form,
headers,
});
return assertShippingOk(body);
}
@@ -31,6 +31,7 @@ import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace } from './useTrainingWorkspace';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import { clearPendingNoticeBatchRetry } from '../shipping/useChatShippingUploadHandler';
import {
createChatPageConversationApi,
createChatPageLocalMessageApi,
@@ -337,6 +338,7 @@ export function useChatPage() {
isThinking,
loadConversationState,
createNewChatView,
clearPendingNoticeBatchRetry,
onConversationIdChanging: shipping.onConversationIdChanging,
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
onConversationLoadFailed: shipping.onConversationLoadFailed,
@@ -27,6 +27,7 @@ import {
createShippingParseReviewHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
onNoticeBatchConversationChanging,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
@@ -666,6 +667,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
isShippingNoticeBatchSubmitting,
} = createShippingUploadHandlers({
conversationId,
currentAgentId,
@@ -738,6 +740,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
handleShippingMenuAction,
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
isShippingNoticeBatchSubmitting,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
@@ -778,6 +781,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
onNoticeBatchConversationChanging(nextId, prevId);
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
if (!shippingBatchNoFromQuery.value) {
@@ -0,0 +1,166 @@
/**
* features/chat/page/useChatPageConversation.spec.ts
* 用途:验证新建聊天与 Agent 切换时清理发货通知待重试建批幂等状态。
* 依赖:vitest、vue refs/computed、useChatPageConversation、useChatShippingUploadHandler。
* 逻辑:覆盖 createNewChatView 不经 onConversationIdChanging 时仍生成新幂等键的回归场景。
*/
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(),
}));
const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
}),
}));
vi.mock('../api/chat.api', () => ({
listChatMessages,
}));
vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({
computeNoticeFilesContentFingerprint,
}));
const createConversationContext = () => {
const conversationId = ref<string | null>('conv-a');
const messages = ref([]);
const createNewChatView = vi.fn(() => {
conversationId.value = null;
messages.value = [];
});
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: vi.fn(),
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: vi.fn(),
filePreviewVisible: ref(false),
previewFile: ref(null),
previewFiles: ref([]),
currentPreviewIndex: ref(0),
}),
};
};
const createUploadContext = (
conversationId: ReturnType<typeof ref<string | null>>,
startChatTurn: 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(''),
shippingInventorySchemaPreviewCache: ref({}),
getActiveShippingTaskId: () => '',
startChatTurn,
refreshShippingActions: vi.fn(async () => undefined),
msg: { warning: vi.fn() },
t: (key: string) => key,
});
describe('useChatPageConversation', () => {
beforeEach(() => {
listChatMessages.mockReset();
computeNoticeFilesContentFingerprint.mockReset();
computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
});
resetShippingNoticeBatchSubmitStateForTests();
});
it('startNewChat clears pending notice batch retry and next upload uses a new idempotency key', async () => {
const startChatTurn = vi.fn(async () => false);
const { conversationId, createNewChatView, api } = createConversationContext();
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
createUploadContext(conversationId, startChatTurn),
);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
api.startNewChat();
expect(createNewChatView).toHaveBeenCalledTimes(1);
expect(conversationId.value).toBeNull();
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('resetChatStateForAgentChange clears pending notice batch retry and next upload uses a new idempotency key', async () => {
const startChatTurn = vi.fn(async () => false);
const { conversationId, createNewChatView, api } = createConversationContext();
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
createUploadContext(conversationId, startChatTurn),
);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
api.resetChatStateForAgentChange();
expect(createNewChatView).toHaveBeenCalledTimes(1);
expect(conversationId.value).toBeNull();
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
});
@@ -17,6 +17,7 @@ export interface ChatPageConversationContext {
isThinking: Ref<boolean>;
loadConversationState: (id: string, loaded: ChatMessage[]) => void;
createNewChatView: () => void;
clearPendingNoticeBatchRetry: () => void;
onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void;
onConversationLoadedEmpty: () => Promise<void>;
onConversationLoadFailed: () => Promise<void>;
@@ -71,6 +72,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
};
const startNewChat = () => {
ctx.clearPendingNoticeBatchRetry();
ctx.createNewChatView();
ctx.clearAttachments();
ctx.input.value = '';
@@ -84,6 +86,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
};
const resetChatStateForAgentChange = () => {
ctx.clearPendingNoticeBatchRetry();
ctx.createNewChatView();
ctx.clearHistory();
ctx.clearAttachments();
@@ -0,0 +1,23 @@
/**
* features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts
* 用途:验证前端文件集合指纹与后端 compute_notice_items_content_fingerprint 对齐。
*/
import { describe, expect, it } from 'vitest';
import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency';
describe('shippingNoticeBatchIdempotency', () => {
it('treats duplicate files as one content set', async () => {
const content = 'same-notice-content';
const single = new File([content], 'a.txt', { type: 'text/plain' });
const duplicatePair = [
new File([content], 'a.txt', { type: 'text/plain' }),
new File([content], 'b.txt', { type: 'text/plain' }),
];
const singleFp = await computeNoticeFilesContentFingerprint([single]);
const duplicateFp = await computeNoticeFilesContentFingerprint(duplicatePair);
expect(singleFp).toBeTruthy();
expect(duplicateFp).toBe(singleFp);
});
});
@@ -0,0 +1,31 @@
/**
* features/chat/shipping/shippingNoticeBatchIdempotency.ts
* 用途:发货通知建批幂等键与文件集合指纹计算。
* 依赖:浏览器 Web Crypto API。
* 逻辑:useChatShippingUploadHandler 在重试时绑定「幂等键 + 文件指纹」,文件变化时生成新键。
*/
/**
* 将 File 列表转为与后端 notice_items 对齐的内容指纹(排序哈希后二次 SHA-256)。
*/
export async function computeNoticeFilesContentFingerprint(files: File[]): Promise<string> {
const hashes: string[] = [];
for (const file of files) {
if (!file) continue;
const buffer = await file.arrayBuffer();
const digest = await crypto.subtle.digest('SHA-256', buffer);
const hex = Array.from(new Uint8Array(digest))
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('');
hashes.push(hex.toLowerCase());
}
const uniqueHashes = [...new Set(hashes)].sort();
if (!uniqueHashes.length) return '';
const joined = uniqueHashes.join('|');
const encoded = new TextEncoder().encode(joined);
const fingerprintDigest = await crypto.subtle.digest('SHA-256', encoded);
return Array.from(new Uint8Array(fingerprintDigest))
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('')
.toLowerCase();
}
@@ -0,0 +1,22 @@
/**
* features/chat/shipping/shippingTurnActions.spec.ts
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingCreateBatchTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
const files = [
new File(['notice-a'], 'notice-a.txt', { type: 'text/plain' }),
new File(['notice-b'], 'notice-b.txt', { type: 'text/plain' }),
];
const turn = buildShippingCreateBatchTurn(files, 'conv-001', 'idem-key-001');
expect(turn.actionType).toBe('shipping.create_batch_from_notices');
expect(turn.payload.conversation_id).toBe('conv-001');
expect(turn.payload.file_count).toBe(2);
expect(turn.payload.idempotency_key).toBe('idem-key-001');
expect(turn.files).toEqual(files);
});
});
@@ -78,6 +78,7 @@ export function buildShippingSubmitDecisionTurn(
export function buildShippingCreateBatchTurn(
files: File[],
conversationId?: string | null,
idempotencyKey?: string,
): { actionType: string; displayText: string; payload: Record<string, unknown>; files: File[] } {
const count = files.length;
const displayText = count === 1
@@ -89,6 +90,7 @@ export function buildShippingCreateBatchTurn(
payload: {
conversation_id: conversationId || undefined,
file_count: count,
idempotency_key: idempotencyKey,
},
files,
};
@@ -0,0 +1,74 @@
/**
* features/chat/shipping/useChatShippingSendHandler.spec.ts
* 用途:验证建批提交中发送拦截不会回退到普通聊天发送。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createShippingSendHandlers, type ShippingSendHandlerContext } from './useChatShippingSendHandler';
const isShippingNoticeBatchSubmitting = vi.hoisted(() => vi.fn(() => false));
vi.mock('./useChatShippingUploadHandler', () => ({
isShippingNoticeBatchSubmitting,
}));
const createContext = (
overrides: Partial<ShippingSendHandlerContext> = {},
): ShippingSendHandlerContext => ({
isShippingNoticeAgent: computed(() => true),
isThinking: ref(false),
isUploadingAttachments: ref(false),
messages: ref([]),
conversationId: ref('conv-send'),
history: ref([]),
input: ref(''),
attachments: ref([{ kind: 'local', file: new File(['notice'], 'notice.txt', { type: 'text/plain' }) }]),
shippingAutoFlowRequested: ref(true),
resolvedShippingTaskId: ref(''),
getActiveShippingBatchNo: () => '',
currentAgentId: computed(() => 1),
selectedKb: ref(''),
attachmentPolicy: computed(() => ({ anyEnabled: true })),
getActiveShippingTaskId: () => '',
lastAssistantMessageContent: () => '',
lastAssistantShippingActions: () => [],
sendMessage: vi.fn(async () => undefined),
buildFileSpecsForSend: vi.fn(async () => []),
loadHistory: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
startChatTurn: vi.fn(async () => true),
openShippingInventoryPicker: vi.fn(() => true),
executeShippingDecision: vi.fn(async () => true),
executeShippingManualUpload: vi.fn(async () => true),
handleShippingMenuAction: vi.fn(async () => undefined),
handleShippingAutoUploadFile: vi.fn(async () => undefined),
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
refreshShippingActions: vi.fn(async () => undefined),
shippingSuggestedPrompt: computed(() => ''),
isShippingShortageQueryIntent: () => false,
queryShippingShortageDetails: vi.fn(async () => true),
msg: { warning: vi.fn(), info: vi.fn() },
t: (key: string) => key,
...overrides,
});
describe('useChatShippingSendHandler', () => {
beforeEach(() => {
isShippingNoticeBatchSubmitting.mockReset();
isShippingNoticeBatchSubmitting.mockReturnValue(false);
});
it('consumes send while notice batch is submitting and does not call sendMessage', async () => {
isShippingNoticeBatchSubmitting.mockReturnValue(true);
const ctx = createContext();
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.sendMessage).not.toHaveBeenCalled();
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
});
});
@@ -61,6 +61,7 @@ export interface ShippingSendHandlerContext {
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise<void>;
handleShippingAutoUploadFile: (file: File) => Promise<void>;
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
isShippingNoticeBatchSubmitting?: () => boolean;
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
isShippingShortageQueryIntent: (text: string) => boolean;
@@ -189,6 +190,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
if (ctx.isShippingNoticeBatchSubmitting?.()) {
ctx.msg.info(ctx.t('chat.shippingNoticeBatchSubmitting'));
return true;
}
const requestedAutoFlow = ctx.shippingAutoFlowRequested.value;
ctx.shippingAutoFlowRequested.value = false;
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
@@ -7,7 +7,10 @@
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
clearPendingNoticeBatchRetry,
createShippingUploadHandlers,
onNoticeBatchConversationChanging,
resetShippingNoticeBatchSubmitStateForTests,
type ShippingUploadHandlerContext,
} from './useChatShippingUploadHandler';
@@ -15,10 +18,21 @@ const { createWorkspaceShippingTask } = vi.hoisted(() => ({
createWorkspaceShippingTask: vi.fn(),
}));
const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
}),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
createWorkspaceShippingTask,
}));
vi.mock('./shippingNoticeBatchIdempotency', () => ({
computeNoticeFilesContentFingerprint,
}));
const createContext = (
overrides: Partial<ShippingUploadHandlerContext> = {},
): ShippingUploadHandlerContext => ({
@@ -50,6 +64,12 @@ const createContext = (
describe('useChatShippingUploadHandler', () => {
beforeEach(() => {
createWorkspaceShippingTask.mockReset();
computeNoticeFilesContentFingerprint.mockReset();
computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
});
resetShippingNoticeBatchSubmitStateForTests();
});
it('opens inventory picker for explicit taskId instead of current active task', () => {
@@ -103,6 +123,186 @@ describe('useChatShippingUploadHandler', () => {
);
});
it('double click only calls startChatTurn once and keeps stable idempotency key', async () => {
const startChatTurn = vi.fn(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
return true;
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
const first = handleShippingAutoUploadNoticeBatch([file]);
const second = handleShippingAutoUploadNoticeBatch([file]);
await Promise.all([first, second]);
expect(startChatTurn).toHaveBeenCalledTimes(1);
const payload = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload;
expect(payload?.idempotency_key).toBeTruthy();
});
it('reuses idempotency key on retry and generates new key after success', async () => {
let attempt = 0;
const startChatTurn = vi.fn(async () => {
attempt += 1;
return attempt >= 2;
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const thirdKey = (startChatTurn.mock.calls[2]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBe(secondKey);
expect(thirdKey).not.toBe(secondKey);
});
it('generates new idempotency key when files change after a failed attempt', async () => {
const startChatTurn = vi.fn(async () => false);
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const firstFile = new File(['notice-a'], 'notice-a.pdf', { type: 'application/pdf' });
const secondFile = new File(['notice-b'], 'notice-b.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([firstFile]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([secondFile]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('reuses idempotency key when conversation upgrades from empty to server-assigned after network failure', async () => {
const conversationId = ref<string | null>(null);
const startChatTurn = vi.fn(async () => {
conversationId.value = 'conv-server-new';
return false;
});
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBe(firstKey);
});
it('generates new idempotency key when switching from new chat to historical session', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref<string | null>(null);
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
onNoticeBatchConversationChanging('conv-history', '');
conversationId.value = 'conv-history';
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('generates new idempotency key after explicit clearPendingNoticeBatchRetry', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref('conv-a');
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
clearPendingNoticeBatchRetry();
conversationId.value = null;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('generates new idempotency key when conversation changes after a failed attempt', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref('conv-a');
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
onNoticeBatchConversationChanging('conv-b', 'conv-a');
conversationId.value = 'conv-b';
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('releases submit lock when fingerprint computation fails', async () => {
computeNoticeFilesContentFingerprint.mockRejectedValueOnce(new Error('digest failed'));
const startChatTurn = vi.fn(async () => true);
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch, isShippingNoticeBatchSubmitting } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await expect(handleShippingAutoUploadNoticeBatch([file])).rejects.toThrow('digest failed');
expect(startChatTurn).not.toHaveBeenCalled();
expect(isShippingNoticeBatchSubmitting()).toBe(false);
computeNoticeFilesContentFingerprint.mockResolvedValueOnce('fp-notice');
await handleShippingAutoUploadNoticeBatch([file]);
expect(startChatTurn).toHaveBeenCalledTimes(1);
});
it('does not open notice picker when both explicit taskId and active task are missing', () => {
const noticeClick = vi.fn();
const warning = vi.fn();
@@ -2,7 +2,7 @@
* features/chat/shipping/useChatShippingUploadHandler.ts
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
* 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。
* 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE。
* 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE;待重试幂等键绑定 conversation_id。
*/
import { computed } from 'vue';
import {
@@ -11,12 +11,91 @@ import {
} from '@/features/chat/api/shipping.api';
import { extractExt } from '../constants/shipping';
import { buildShippingCreateBatchTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency';
import { classifyShippingUploadFile } from './shippingUploadPrompt';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
let noticeBatchSubmitting = false;
interface PendingNoticeBatchRetryState {
conversationId: string;
idempotencyKey: string;
fileFingerprint: string;
}
let pendingNoticeBatchRetry: PendingNoticeBatchRetryState | null = null;
function normalizeConversationId(conversationId: string | null | undefined): string {
return String(conversationId || '').trim();
}
function clearPendingNoticeBatchRetryState(): void {
pendingNoticeBatchRetry = null;
}
/**
* 显式清理待重试建批幂等状态(新建聊天、切换 Agent 等不经 onConversationIdChanging 的路径)。
*/
export function clearPendingNoticeBatchRetry(): void {
clearPendingNoticeBatchRetryState();
}
/**
* 判断待重试状态是否应绑定到当前会话。
* 核心逻辑:允许「尚未分配会话」升级绑定服务端新 ID;两个非空且不同、或旧非空而新为空时清理。
*/
function reconcilePendingNoticeBatchConversation(
pending: PendingNoticeBatchRetryState,
conversationKey: string,
): void {
const pendingKey = pending.conversationId;
if (pendingKey === conversationKey) {
return;
}
if (!pendingKey && conversationKey) {
pending.conversationId = conversationKey;
return;
}
if (pendingKey && !conversationKey) {
clearPendingNoticeBatchRetryState();
return;
}
if (pendingKey && conversationKey && pendingKey !== conversationKey) {
clearPendingNoticeBatchRetryState();
}
}
/**
* 用户主动切换会话时清理待重试建批状态,避免跨会话复用幂等键。
* 仅由 onConversationIdChanging 调用;SSE 自动分配 conversation_id 不经过此函数。
*/
export function onNoticeBatchConversationChanging(
nextId: string,
prevId?: string | null,
): void {
const next = normalizeConversationId(nextId);
const prev = normalizeConversationId(prevId);
if (next !== prev) {
clearPendingNoticeBatchRetryState();
}
}
/**
* 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。
*/
export function isShippingNoticeBatchSubmitting(): boolean {
return noticeBatchSubmitting;
}
/** 单测重置模块级建批提交状态。 */
export function resetShippingNoticeBatchSubmitStateForTests(): void {
noticeBatchSubmitting = false;
clearPendingNoticeBatchRetry();
}
export interface ShippingUploadHandlerContext {
conversationId: Ref<string | null>;
currentAgentId: ComputedRef<number>;
@@ -135,25 +214,58 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
};
const runNoticeBatchChatTurn = async (files: File[]) => {
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const fileFingerprint = await computeNoticeFilesContentFingerprint(files);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
}
if (
pendingNoticeBatchRetry
&& pendingNoticeBatchRetry.fileFingerprint !== fileFingerprint
) {
clearPendingNoticeBatchRetryState();
}
if (!pendingNoticeBatchRetry) {
pendingNoticeBatchRetry = {
conversationId: conversationKey,
idempotencyKey: crypto.randomUUID(),
fileFingerprint,
};
} else {
pendingNoticeBatchRetry.fileFingerprint = fileFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value, idempotencyKey);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
},
});
if (!ok) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
});
if (ok) {
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
clearPendingNoticeBatchRetryState();
}
} else {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
}
return ok;
} finally {
noticeBatchSubmitting = false;
}
return ok;
};
const syncBatchContextFromNoticeResponse = (result: Record<string, unknown> | null | undefined) => {
@@ -317,5 +429,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
isShippingNoticeBatchSubmitting,
};
}
@@ -272,12 +272,28 @@ export interface ShippingTaskCreateResponse {
data?: Record<string, unknown>;
}
export interface ShippingNoticeFileSummary {
total_files: number;
accepted_count: number;
rejected_count: number;
duplicate_count: number;
accepted_files?: Array<Record<string, unknown>>;
rejected_files?: Array<Record<string, unknown>>;
duplicate_files?: Array<{
filename: string;
duplicate_of: string;
content_hash?: string;
}>;
}
export interface ShippingNoticeUploadResponse {
status: string;
message?: string;
task_id?: string;
batch_no?: string;
checkpoint?: string;
idempotent_replay?: boolean;
file_summary?: ShippingNoticeFileSummary;
data?: Record<string, unknown> & {
batch?: ShippingBatchSummary;
focus_task?: ShippingTaskSummary | null;