feat(shipping-notice): 新增发货通知重复检测与处理接口,支持重复决策保存与重新执行检测

This commit is contained in:
hugo committed 2026-07-14 21:12:36 +08:00
1 parent 729546a7b7
commit ceb49461e8
72 files changed
+14270 -460

No files matched your search

@@ -0,0 +1,56 @@
/**
* features/chat/shipping/shippingNoticeAttachmentIntegrity.spec.ts
* 用途:附件完整性门禁单测;阻断码与截断路径须能阻止建单判定。
*/
import { describe, expect, it } from 'vitest';
import {
BLOCKING_WARNING_PREFIXES,
isShippingNoticeAttachmentParseIncomplete,
} from './shippingNoticeAttachmentIntegrity';
describe('shippingNoticeAttachmentIntegrity', () => {
it('treats each blocking warning prefix as incomplete', () => {
for (const prefix of BLOCKING_WARNING_PREFIXES) {
expect(
isShippingNoticeAttachmentParseIncomplete({
warnings: [`${prefix}demo`],
attachments: [],
}),
).toBe(true);
}
});
it('treats per-attachment text truncation as incomplete', () => {
expect(
isShippingNoticeAttachmentParseIncomplete({
attachment_count: 1,
attachments: [
{
parse_status: 'parsed',
warnings: ['eml_attachment_text_truncated:10'],
},
],
warnings: [],
}),
).toBe(true);
});
it('treats notice_text_truncated as incomplete', () => {
expect(
isShippingNoticeAttachmentParseIncomplete({
warnings: ['notice_text_truncated:200000'],
attachments: [],
}),
).toBe(true);
});
it('allows clean parsed summary', () => {
expect(
isShippingNoticeAttachmentParseIncomplete({
attachment_count: 1,
attachments: [{ parse_status: 'parsed', warnings: [] }],
warnings: [],
}),
).toBe(false);
});
});
@@ -0,0 +1,54 @@
/**
* features/chat/shipping/shippingNoticeAttachmentIntegrity.ts
* 用途:发货通知附件完整性门禁契约(阻断 warning 前缀与 incomplete 判定)。
* 依赖:shipping.types(ParseSummary 形状)。
* 逻辑:与后端 attachment_integrity.BLOCKING_WARNING_PREFIXES /
* is_attachment_parse_incomplete 保持一致;契约测试校验两端前缀集合。
*/
import type { ShippingNoticeParseSummary } from '../types/shipping.types';
/** 阻断 warning 前缀;须与 backend BLOCKING_WARNING_PREFIXES 完全一致(顺序可不同)。 */
export const BLOCKING_WARNING_PREFIXES = [
'eml_nesting_depth_exceeded:',
'eml_attachment_limit_exceeded:',
'eml_total_attachment_size_exceeded:',
'eml_nested_message_unreadable',
'eml_attachment_text_budget_exhausted:',
'eml_attachment_text_truncated:',
'notice_text_truncated:',
] as const;
const INCOMPLETE_ATTACHMENT_STATUSES = new Set(['failed', 'empty', 'skipped']);
/**
* 判定单条 warning 是否为完整性阻断项。
*/
export function isBlockingWarning(text: string): boolean {
const normalized = String(text || '');
return BLOCKING_WARNING_PREFIXES.some((prefix) => normalized.startsWith(prefix));
}
/**
* 判定 EML 等 intake 是否存在未完整解析的附件(含超深/超限/截断警告)。
* 核心逻辑:阻断警告、登记数少于发现数、或 failed/empty/skipped 均视为不完整;
* duplicate 仅为去重,不阻断建单。
*/
export function isShippingNoticeAttachmentParseIncomplete(
summary?: ShippingNoticeParseSummary | null,
): boolean {
if (!summary) return false;
const warnings = summary.warnings || [];
if (warnings.some((item) => isBlockingWarning(String(item || '')))) {
return true;
}
const rows = summary.attachments || [];
const total = Number(summary.attachment_count || 0);
if (total > rows.length) return true;
return rows.some((item) => {
if (INCOMPLETE_ATTACHMENT_STATUSES.has(String(item.parse_status || ''))) {
return true;
}
return (item.warnings || []).some((w) => isBlockingWarning(String(w || '')));
});
}
@@ -64,6 +64,8 @@ export interface ShippingSendHandlerContext {
isShippingNoticeBatchSubmitting?: () => boolean;
hasBlockingNoticeIntake?: () => boolean;
hasNoticeIntakeFailures?: () => boolean;
hasBlockingNoticeDuplicates?: () => boolean;
openShippingDuplicateDialog?: (attachmentId?: string) => void;
getParsedIntakeNos?: () => string[];
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
@@ -201,6 +203,11 @@ 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)) {
ctx.shippingAutoFlowRequested.value = false;
@@ -1,23 +1,31 @@
/**
* features/chat/shipping/useShippingNoticeIntakes.ts
* 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。
* 依赖:file-assets.api、shipping.api、shipping.types。
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件。
* 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity。
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件;
* 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐)。
*/
import { computed, onBeforeUnmount, ref, type Ref } from 'vue';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import type {
PendingAttachment,
ShippingDuplicateAction,
ShippingDuplicateResult,
ShippingNoticeParseSummary,
ShippingNoticePendingAttachment,
} from '../types/shipping.types';
import type { ShippingNoticeIntakeResponse } from '../types/shipping.api.types';
import {
cancelShippingNoticeIntake,
createShippingNoticeIntake,
getShippingNoticeIntakeStatuses,
listActiveShippingNoticeIntakes,
resolveShippingNoticeDuplicate,
retryShippingNoticeIntake,
} from '@/features/chat/api/shipping.api';
import type {
PendingAttachment,
ShippingNoticeParseSummary,
ShippingNoticePendingAttachment,
} from '../types/shipping.types';
import { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity';
export { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity';
const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', 'cancelled', 'expired']);
const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']);
@@ -34,6 +42,46 @@ function mapServerParseStatus(status: string): ShippingNoticePendingAttachment['
return 'waiting';
}
/**
* 将服务端 duplicate 结果映射为前端附件状态。
*/
function mapServerDuplicate(remote: ShippingNoticeIntakeResponse): {
duplicate?: ShippingDuplicateResult;
duplicateResolution?: ShippingNoticePendingAttachment['duplicateResolution'];
} {
const dup = remote.duplicate;
if (!dup) return {};
const duplicate: ShippingDuplicateResult = {
status: dup.status,
blocking: Boolean(dup.blocking),
fingerprintStrength: dup.fingerprint_strength,
matches: (dup.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: (dup.allowed_actions || []) as ShippingDuplicateAction[],
};
const resolution = remote.duplicate_resolution;
return {
duplicate,
duplicateResolution: resolution
? {
action: resolution.action,
targetTaskNo: resolution.target_task_no || undefined,
reason: resolution.reason || undefined,
}
: undefined,
};
}
function listSafe(value: unknown): string[] {
return Array.isArray(value) ? value.map((item) => String(item)) : [];
}
function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
return {
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
@@ -76,12 +124,30 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
);
const hasParseFailures = computed(() =>
noticeAttachments.value.some((item) => item.parseStatus === 'failed'),
noticeAttachments.value.some(
(item) =>
item.parseStatus === 'failed'
|| isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
),
);
const allParsedReady = computed(() =>
noticeAttachments.value.length > 0
&& noticeAttachments.value.every((item) => item.parseStatus === 'parsed'),
&& noticeAttachments.value.every(
(item) =>
item.parseStatus === 'parsed'
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
),
);
const hasBlockingDuplicates = computed(() =>
noticeAttachments.value.some(
(item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
),
);
const allReadyForConfirmation = computed(() =>
allParsedReady.value && !hasBlockingDuplicates.value && !hasParseFailures.value,
);
const stopPolling = () => {
@@ -137,6 +203,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
errorMessage: remote.error_message || undefined,
expiresAt: remote.expires_at || undefined,
assetNo: remote.asset_no || local.assetNo,
...mapServerDuplicate(remote),
});
}
};
@@ -218,7 +285,12 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
const getParsedIntakeNos = () =>
noticeAttachments.value
.filter((item) => item.parseStatus === 'parsed' && item.intakeNo)
.filter(
(item) =>
item.parseStatus === 'parsed'
&& item.intakeNo
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
)
.map((item) => String(item.intakeNo));
const clearConsumedAttachments = () => {
@@ -233,11 +305,11 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
.filter((item) => item.parse_status !== 'consumed')
.map((item) => ({
id: `restored_${item.intake_no}`,
kind: 'shipping_notice',
type: 'document',
kind: 'shipping_notice' as const,
type: 'document' as const,
assetNo: item.asset_no || undefined,
intakeNo: item.intake_no,
uploadStatus: 'uploaded',
uploadStatus: 'uploaded' as const,
parseStatus: mapServerParseStatus(item.parse_status),
uploadProgress: 100,
originalFilename: item.original_filename || item.intake_no,
@@ -246,6 +318,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
errorCode: item.error_code || undefined,
errorMessage: item.error_message || undefined,
expiresAt: item.expires_at || undefined,
...mapServerDuplicate(item),
}));
const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
options.attachments.value = [...nonNotice, ...restored];
@@ -254,6 +327,26 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
}
};
const resolveDuplicateAttachment = async (
id: string,
action: ShippingDuplicateAction,
targetTaskNo?: string,
reason?: string,
) => {
const target = noticeAttachments.value.find((item) => item.id === id);
if (!target?.intakeNo) return;
const intake = await resolveShippingNoticeDuplicate(
target.intakeNo,
action,
targetTaskNo,
reason,
);
patchAttachment(target.id, {
parseStatus: mapServerParseStatus(intake.parse_status),
...mapServerDuplicate(intake),
});
};
onBeforeUnmount(() => {
stopPolling();
});
@@ -263,9 +356,12 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
hasBlockingUploadOrParse,
hasParseFailures,
allParsedReady,
hasBlockingDuplicates,
allReadyForConfirmation,
enqueueNoticeFiles,
removeNoticeAttachment,
retryNoticeAttachment,
resolveDuplicateAttachment,
getParsedIntakeNos,
clearConsumedAttachments,
restoreForConversation,