feat(shipping-notice): 增强发货通知候选管理功能,支持候选选择、重复检测与业务摘要修订

This commit is contained in:
hugo committed 2026-07-15 11:57:04 +08:00
1 parent 70f684b94a
commit b595e157e9
83 files changed
+5857 -200

No files matched your search

@@ -3,7 +3,7 @@
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingCreateBatchTurn } from './shippingTurnActions';
import { buildShippingCreateBatchFromIntakesTurn, buildShippingCreateBatchTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
@@ -19,4 +19,17 @@ describe('shippingTurnActions', () => {
expect(turn.payload.idempotency_key).toBe('idem-key-001');
expect(turn.files).toEqual(files);
});
it('buildShippingCreateBatchFromIntakesTurn includes selected candidate_nos', () => {
const turn = buildShippingCreateBatchFromIntakesTurn(
['SNI-001'],
'conv-001',
'idem-candidate-001',
['SNC-001', 'SNC-003'],
);
expect(turn.actionType).toBe('shipping.create_batch_from_intakes');
expect(turn.payload.intake_nos).toEqual(['SNI-001']);
expect(turn.payload.candidate_nos).toEqual(['SNC-001', 'SNC-003']);
});
});
@@ -103,6 +103,7 @@ export function buildShippingCreateBatchFromIntakesTurn(
intakeNos: string[],
conversationId?: string | null,
idempotencyKey?: string,
candidateNos?: string[],
): { actionType: string; displayText: string; payload: Record<string, unknown> } {
const count = intakeNos.length;
const displayText = count === 1
@@ -115,6 +116,7 @@ export function buildShippingCreateBatchFromIntakesTurn(
intake_nos: intakeNos,
conversation_id: conversationId || undefined,
idempotency_key: idempotencyKey,
candidate_nos: candidateNos,
},
};
}
@@ -1,6 +1,6 @@
/**
* features/chat/shipping/useChatShippingSendHandler.spec.ts
* 用途:验证建批提交中发送拦截不会回退到普通聊天发送。
* 用途:验证上传预处理与点击发送完整抽取链路,以及建批提交中的并发拦截。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -71,4 +71,80 @@ describe('useChatShippingSendHandler', () => {
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
});
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
const attachment = {
id: 'notice-1',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-1',
};
const ctx = createContext({
attachments: ref([attachment]),
hasCandidateReviewIssues: () => true,
hasSelectedNoticeCandidates: () => true,
getParsedIntakeNos: () => ['SNI-1'],
refreshNoticeIntakeStatuses: vi.fn(async () => undefined),
clearConsumedNoticeAttachments: vi.fn(),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultPrompt',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
},
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
);
});
it('uses the user query for full extraction even when no candidate exists before send', async () => {
const attachment = {
id: 'notice-1',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-1',
};
const ctx = createContext({
attachments: ref([attachment]),
hasCandidateReviewIssues: () => false,
hasSelectedNoticeCandidates: () => false,
getParsedIntakeNos: () => ['SNI-1'],
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '请解析这些附件', '请解析这些附件');
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'请解析这些附件',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: '请解析这些附件',
},
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
);
});
});
@@ -1,8 +1,8 @@
/**
* features/chat/shipping/useChatShippingSendHandler.ts
* 用途:在聊天发送前拦截发货通知专属意图,如切票、决策文本、列映射和附件自动流程。
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本、列映射和附件自动流程。
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。
* 逻辑:业务动作经 Chat Turn / handleShippingMenuAction;纯 UI(下载/选文件/映射卡片)保留本地或客户端行为。
* 逻辑:已预处理 Intake 通过普通聊天接口进入现有 Dify Chatflow;其他业务动作经 Chat Turn / handleShippingMenuAction。
*/
import {
getWorkspaceShippingBatch,
@@ -50,6 +50,8 @@ export interface ShippingSendHandlerContext {
agentId: number,
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>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadHistory: () => Promise<void>;
@@ -65,8 +67,12 @@ export interface ShippingSendHandlerContext {
hasBlockingNoticeIntake?: () => boolean;
hasNoticeIntakeFailures?: () => boolean;
hasBlockingNoticeDuplicates?: () => boolean;
hasCandidateReviewIssues?: () => boolean;
hasSelectedNoticeCandidates?: () => boolean;
openShippingDuplicateDialog?: (attachmentId?: string) => void;
getParsedIntakeNos?: () => string[];
refreshNoticeIntakeStatuses?: () => Promise<void>;
clearConsumedNoticeAttachments?: () => void;
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
isShippingShortageQueryIntent: (text: string) => boolean;
@@ -78,7 +84,7 @@ export interface ShippingSendHandlerContext {
/**
* 创建发货通知发送拦截器。
*
* 核心逻辑:识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图,并在命中时直接走本地前后端流程。
* 核心逻辑:已预处理邮件固定 Intake 上下文后调用普通聊天;其余识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图。
* @param ctx - 发送拦截上下文
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
*/
@@ -203,17 +209,30 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.msg.warning(ctx.t('chat.shippingNoticeParseFailedHint'));
return true;
}
if (ctx.hasBlockingNoticeDuplicates?.()) {
ctx.openShippingDuplicateDialog?.();
ctx.msg.warning(ctx.t('chat.shippingNoticeDuplicateNeedsResolution'));
return true;
}
const intakeNos = ctx.getParsedIntakeNos?.() || [];
if (intakeNos.length && (!trimmed || ctx.shippingAutoFlowRequested.value)) {
if (intakeNos.length) {
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
try {
await ctx.handleShippingAutoUploadNoticeBatch([]);
await ctx.sendMessage(
query,
ctx.currentAgentId.value,
ctx.selectedKb.value,
[],
{
shipping_intake_nos: intakeNos,
display_query: query,
},
{
onAssistantMessageFinished: async () => {
await ctx.refreshNoticeIntakeStatuses?.();
ctx.clearConsumedNoticeAttachments?.();
await ctx.refreshShippingActions();
},
},
);
await ctx.loadHistory();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
@@ -120,6 +120,7 @@ export interface ShippingUploadHandlerContext {
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
getParsedIntakeNos?: () => string[];
getSelectedCandidateNos?: () => string[];
clearConsumedNoticeAttachments?: () => void;
}
@@ -310,14 +311,14 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return ok;
};
const runNoticeBatchFromIntakes = async (intakeNos: string[]) => {
const runNoticeBatchFromIntakes = async (intakeNos: string[], candidateNos: string[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const intakeFingerprint = computeNoticeIntakeNosFingerprint(intakeNos);
const intakeFingerprint = computeNoticeIntakeNosFingerprint([...intakeNos, ...candidateNos]);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
}
@@ -337,7 +338,12 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
pendingNoticeBatchRetry.fileFingerprint = intakeFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchFromIntakesTurn(intakeNos, ctx.conversationId.value, idempotencyKey);
const turn = buildShippingCreateBatchFromIntakesTurn(
intakeNos,
ctx.conversationId.value,
idempotencyKey,
candidateNos,
);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
@@ -402,8 +408,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
const noticeFiles = files.filter(Boolean);
const intakeNos = ctx.getParsedIntakeNos?.() || [];
const candidateNos = ctx.getSelectedCandidateNos?.() || [];
if (!noticeFiles.length && intakeNos.length) {
await runNoticeBatchFromIntakes(intakeNos);
await runNoticeBatchFromIntakes(intakeNos, candidateNos);
return;
}
if (!noticeFiles.length) return;
@@ -13,15 +13,18 @@ import type {
ShippingDuplicateResult,
ShippingNoticeParseSummary,
ShippingNoticePendingAttachment,
ShippingNoticeCandidate,
} from '../types/shipping.types';
import type { ShippingNoticeIntakeResponse } from '../types/shipping.api.types';
import type { ShippingNoticeCandidateResponse, ShippingNoticeIntakeResponse } from '../types/shipping.api.types';
import {
cancelShippingNoticeIntake,
createShippingNoticeIntake,
getShippingNoticeIntakeStatuses,
listActiveShippingNoticeIntakes,
resolveShippingNoticeDuplicate,
resolveShippingNoticeCandidateDuplicate,
retryShippingNoticeIntake,
updateShippingNoticeCandidate,
} from '@/features/chat/api/shipping.api';
import { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity';
@@ -82,6 +85,44 @@ function listSafe(value: unknown): string[] {
return Array.isArray(value) ? value.map((item) => String(item)) : [];
}
/** 将 Candidate API 契约映射为输入区可审核状态。 */
function mapServerCandidate(remote: ShippingNoticeCandidateResponse): ShippingNoticeCandidate {
const duplicate = remote.duplicate
? {
status: remote.duplicate.status,
blocking: Boolean(remote.duplicate.blocking),
fingerprintStrength: remote.duplicate.fingerprint_strength,
matches: (remote.duplicate.matches || []).map((item) => ({
taskNo: item.task_no,
processStatus: item.process_status,
documentVersion: Number(item.document_version || 1),
matchType: item.match_type,
matchedFields: listSafe(item.matched_fields),
createdAt: item.created_at,
})),
allowedActions: (remote.duplicate.allowed_actions || []) as ShippingDuplicateAction[],
}
: undefined;
return {
candidateNo: remote.candidate_no,
poNumber: remote.po_number || undefined,
documentFilename: remote.primary_document_filename || undefined,
validationStatus: remote.validation_status,
selected: Boolean(remote.selected),
conflicts: remote.conflicts || [],
businessSummary: remote.business_summary || {},
duplicate,
duplicateResolution: remote.duplicate_resolution
? {
action: remote.duplicate_resolution.action,
targetTaskNo: remote.duplicate_resolution.target_task_no || undefined,
reason: remote.duplicate_resolution.reason || undefined,
}
: undefined,
consumedTaskId: remote.consumed_task_id || undefined,
};
}
function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
return {
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
@@ -142,12 +183,28 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
const hasBlockingDuplicates = computed(() =>
noticeAttachments.value.some(
(item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
(item) => (item.candidates?.length
? item.candidates.some((candidate) =>
candidate.selected && candidate.duplicate?.blocking && !candidate.duplicateResolution?.action,
)
: item.duplicate?.blocking && !item.duplicateResolution?.action),
),
);
const hasCandidateReviewIssues = computed(() =>
noticeAttachments.value.some((item) =>
(item.candidates || []).some((candidate) =>
candidate.selected && candidate.validationStatus !== 'ready',
),
),
);
const allReadyForConfirmation = computed(() =>
allParsedReady.value && !hasBlockingDuplicates.value && !hasParseFailures.value,
allParsedReady.value
&& !hasBlockingDuplicates.value
&& !hasCandidateReviewIssues.value
&& !hasParseFailures.value
&& noticeAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)),
);
const stopPolling = () => {
@@ -198,12 +255,15 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
if (!local) continue;
patchAttachment(local.id, {
parseStatus: mapServerParseStatus(remote.parse_status),
orderExtractionStatus: remote.order_extraction_status || undefined,
orderExtractionVersion: remote.order_extraction_version || undefined,
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: remote.error_code || undefined,
errorMessage: remote.error_message || undefined,
errorCode: remote.order_extraction_error_code || remote.error_code || undefined,
errorMessage: remote.order_extraction_error_message || remote.error_message || undefined,
expiresAt: remote.expires_at || undefined,
assetNo: remote.asset_no || local.assetNo,
...mapServerDuplicate(remote),
candidates: (remote.candidates || []).map(mapServerCandidate),
});
}
};
@@ -226,10 +286,14 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
patchAttachment(attachment.id, {
intakeNo: intake.intake_no,
parseStatus: mapServerParseStatus(intake.parse_status),
orderExtractionStatus: intake.order_extraction_status || undefined,
orderExtractionVersion: intake.order_extraction_version || undefined,
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: intake.error_code || undefined,
errorMessage: intake.error_message || undefined,
errorCode: intake.order_extraction_error_code || intake.error_code || undefined,
errorMessage: intake.order_extraction_error_message || intake.error_message || undefined,
expiresAt: intake.expires_at || undefined,
...mapServerDuplicate(intake),
candidates: (intake.candidates || []).map(mapServerCandidate),
});
schedulePoll();
} catch (error) {
@@ -294,8 +358,10 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
.map((item) => String(item.intakeNo));
const clearConsumedAttachments = () => {
options.attachments.value = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
stopPolling();
options.attachments.value = options.attachments.value.filter(
(item) => item.kind !== 'shipping_notice' || item.parseStatus !== 'consumed',
);
if (!noticeAttachments.value.length) stopPolling();
};
const restoreForConversation = async (conversationId?: string | null) => {
@@ -311,14 +377,17 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
intakeNo: item.intake_no,
uploadStatus: 'uploaded' as const,
parseStatus: mapServerParseStatus(item.parse_status),
orderExtractionStatus: item.order_extraction_status || undefined,
orderExtractionVersion: item.order_extraction_version || undefined,
uploadProgress: 100,
originalFilename: item.original_filename || item.intake_no,
fileSize: Number(item.file_size || 0),
parseSummary: (item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: item.error_code || undefined,
errorMessage: item.error_message || undefined,
errorCode: item.order_extraction_error_code || item.error_code || undefined,
errorMessage: item.order_extraction_error_message || item.error_message || undefined,
expiresAt: item.expires_at || undefined,
...mapServerDuplicate(item),
...mapServerDuplicate(item),
candidates: (item.candidates || []).map(mapServerCandidate),
}));
const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
options.attachments.value = [...nonNotice, ...restored];
@@ -347,6 +416,56 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
});
};
/** 切换 Candidate 是否参与本次建批。 */
const setCandidateSelected = async (candidateNo: string, selected: boolean) => {
const remote = await updateShippingNoticeCandidate(candidateNo, { selected });
for (const attachment of noticeAttachments.value) {
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
patchAttachment(attachment.id, {
candidates: (attachment.candidates || []).map((item) =>
item.candidateNo === candidateNo ? mapServerCandidate(remote) : item,
),
});
}
};
/** 保存 Candidate 人工修订后的订单摘要。 */
const updateCandidateSummary = async (candidateNo: string, businessSummary: Record<string, unknown>) => {
const remote = await updateShippingNoticeCandidate(candidateNo, { business_summary: businessSummary });
for (const attachment of noticeAttachments.value) {
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
patchAttachment(attachment.id, {
candidates: (attachment.candidates || []).map((item) =>
item.candidateNo === candidateNo ? mapServerCandidate(remote) : item,
),
});
}
};
/** 保存单个 Candidate 的重复处理决策。 */
const resolveCandidateDuplicate = async (
candidateNo: string,
action: ShippingDuplicateAction,
targetTaskNo?: string,
reason?: string,
) => {
const remote = await resolveShippingNoticeCandidateDuplicate(candidateNo, action, targetTaskNo, reason);
for (const attachment of noticeAttachments.value) {
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
patchAttachment(attachment.id, {
candidates: (attachment.candidates || []).map((item) =>
item.candidateNo === candidateNo ? mapServerCandidate(remote) : item,
),
});
}
};
const getSelectedCandidateNos = () => noticeAttachments.value.flatMap((item) =>
(item.candidates || [])
.filter((candidate) => candidate.selected)
.map((candidate) => candidate.candidateNo),
);
onBeforeUnmount(() => {
stopPolling();
});
@@ -357,12 +476,18 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
hasParseFailures,
allParsedReady,
hasBlockingDuplicates,
hasCandidateReviewIssues,
allReadyForConfirmation,
enqueueNoticeFiles,
removeNoticeAttachment,
retryNoticeAttachment,
resolveDuplicateAttachment,
resolveCandidateDuplicate,
setCandidateSelected,
updateCandidateSummary,
getParsedIntakeNos,
getSelectedCandidateNos,
refreshStatuses,
clearConsumedAttachments,
restoreForConversation,
stopPolling,