feat(shipping_notice): 新增货代订单全流程业务模块及配套基建

本次提交新增货代订单处理全流程的完整业务能力、数据库迁移与测试用例:
1.  统一追加式审计事件体系,支持全链路不可篡改的业务追溯
2.  货代任务撤销、版本替代管控逻辑,规范已上传订单的合规版本更替
3.  订单抽取路由审计、模板自动冻结资格、路由计数等核心业务基建
4.  EML订单补充表解析契约与合并逻辑,完善订单补全能力
5.  Chatflow只读能力令牌校验机制,保障工具调用安全
6.  人工复核证据校验服务,规范人工审核的证据留存
所有变更均配套完整的单元测试与迁移契约测试,支持受控回退
This commit is contained in:
hugo committed 2026-07-28 08:56:58 +08:00
1 parent 90f77634d6
commit 1f3ecb87b7
128 files changed
+3635 -2074

No files matched your search

+1 -1
View File
@@ -77,7 +77,7 @@ export type ShippingOrderExtractionDiagnosticRun = {
export type ShippingOrderExtractionDiagnosticDetail = {
run: ShippingOrderExtractionDiagnosticRun;
job_attempts: Array<{ job_id: number; status: string; attempts: number; max_attempts: number; created_at?: string | null; started_at?: string | null; finished_at?: string | null; duration_ms?: number | null }>;
units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null }>;
units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null; route_decisions: Array<{ attempt_no: number; execution_mode: 'deterministic' | 'dify' | 'blocked'; match_status: string; selected_profile_code?: string | null; selected_profile_version?: number | null; auto_create_approved?: boolean | null; candidate_count: number; table_count: number; approved_table_count: number; candidates: Array<{ profile_code: string; version: number; score: number; hard_match: boolean; reason_codes: string[]; missing_required_anchor_ids?: string[] }>; fallback_reason_codes: string[] }> }>;
progress_events: Array<{ event_type: string; node_type?: string | null; stage_code?: string | null; status?: string | null; workflow_run_id?: string | null; node_execution_id?: string | null; occurred_at?: string | null }>;
};
export const listShippingOrderExtractionDiagnosticRuns = (page = 1, pageSize = 25, status = '') => {
@@ -76,16 +76,6 @@ const dialogTitle = computed(() => {
const dialogSubtitle = computed(() => (
isInternalExecutor.value ? t('admin.agent.executor.formSubtitle') : t('admin.agent.subtitle')
));
const orderExtractionCapability = computed(() => (
currentCatalogEntry.value?.required_runtime_capabilities?.['shipping.order_extraction']
));
const orderExtractionProviderOptions = computed(() => props.agentOptions.filter((agent) => (
agent.id !== props.form.id
&& agent.is_active
&& agent.runtime_provider === 'dify'
&& agent.dify_app_type === 'workflow'
&& agent.exposure_mode === 'internal'
)));
const showToolRunProgress = computed(() => (
showDifyFields.value
&& props.form.dify_app_type !== 'workflow'
@@ -366,28 +356,6 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</div>
</template>
<div v-if="orderExtractionCapability" class="col-span-1 md:col-span-2 rounded-xl border border-default bg-surface-soft p-4">
<div class="mb-4">
<h4 class="text-sm font-semibold text-primary">{{ t('admin.agent.runtimeBinding.title') }}</h4>
<p class="mt-1 text-xs text-muted">{{ t('admin.agent.runtimeBinding.subtitle') }}</p>
</div>
<div class="overflow-x-auto rounded-lg border border-default">
<table class="min-w-full text-sm">
<thead class="bg-surface-soft text-left text-xs font-bold uppercase tracking-wider text-muted">
<tr><th class="px-3 py-2">{{ t('admin.agent.runtimeBinding.capability') }}</th><th class="px-3 py-2">{{ t('admin.agent.runtimeBinding.provider') }}</th><th class="px-3 py-2">{{ t('admin.agent.runtimeBinding.timeout') }}</th><th class="px-3 py-2">{{ t('admin.agent.runtimeBinding.maxAttempts') }}</th></tr>
</thead>
<tbody><tr class="border-t border-default">
<td class="px-3 py-3 font-medium text-primary">{{ t('admin.agent.runtimeBinding.orderExtraction') }}</td>
<td class="px-3 py-3"><select v-model="form.order_extraction_provider_agent_id" class="w-full input-field text-sm"><option :value="null">{{ t('admin.agent.runtimeBinding.selectProvider') }}</option><option v-for="agent in orderExtractionProviderOptions" :key="agent.id" :value="agent.id">{{ agent.name }} (Workflow #{{ agent.id }})</option></select></td>
<td class="px-3 py-3"><input v-model.number="form.order_extraction_timeout_seconds" type="number" min="30" max="3600" class="w-28 input-field text-sm" /></td>
<td class="px-3 py-3"><input v-model.number="form.order_extraction_max_attempts" type="number" min="1" max="10" class="w-20 input-field text-sm" /></td>
</tr></tbody>
</table>
</div>
<p v-if="!orderExtractionProviderOptions.length" class="mt-3 text-xs text-amber-700">
{{ t('admin.agent.runtimeBinding.noProvider') }}
</p>
</div>
<div v-if="isInternalExecutor" class="col-span-1 md:col-span-2 rounded-xl border border-default bg-surface-soft p-4">
<div class="mb-4"><h4 class="text-sm font-semibold text-primary">{{ t('admin.agent.runtimeBinding.executorGovernance') }}</h4></div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
@@ -17,7 +17,6 @@ import {
listAdminContentProfiles,
listAdminIntentRoutes,
listAdminAgents,
listAdminAgentRuntimeBindings,
listAdminUsers,
saveAdminAgentPermissions,
testAdminAgent,
@@ -404,18 +403,6 @@ export function useAgentsAdmin() {
}
isEditing.value = true;
void loadTrainingExamPdfGuides(agent.id);
if (catalogEntry?.required_runtime_capabilities?.['shipping.order_extraction']) {
void listAdminAgentRuntimeBindings(agent.id).then((bindings) => {
if (selectedAgentId.value !== agent.id) return;
const binding = bindings.find((item) => item.capability_code === 'shipping.order_extraction');
form.value.order_extraction_binding_enabled = binding?.enabled !== false;
form.value.order_extraction_provider_agent_id = binding?.provider_agent_id ?? null;
form.value.order_extraction_timeout_seconds = Number(binding?.config?.timeout_seconds || 900);
form.value.order_extraction_max_attempts = Number(binding?.config?.max_attempts || 3);
}).catch((error) => {
console.error('Error loading Agent runtime bindings:', error);
});
}
const governance = asRecord(extra.order_extraction_governance);
form.value.executor_provider_max_concurrency = Number(governance.provider_max_concurrency || 4);
form.value.executor_circuit_failure_threshold = Number(governance.circuit_failure_threshold || 5);
@@ -521,22 +508,6 @@ export function useAgentsAdmin() {
typeCatalog: typeCatalog.value,
});
registryPayload.exposure_mode = form.value.exposure_mode;
if (catalogEntry?.required_runtime_capabilities?.['shipping.order_extraction']) {
if (!form.value.order_extraction_provider_agent_id) {
msg.warning(t('admin.agent.runtimeBinding.providerRequired'));
isSaving.value = false;
return false;
}
registryPayload.order_extraction_runtime_binding = {
provider_agent_id: form.value.order_extraction_provider_agent_id,
// 新 UI 不再暴露启用勾选;绑定存在即启用,旧 API 仍兼容显式 enabled=false。
enabled: true,
config: {
timeout_seconds: form.value.order_extraction_timeout_seconds,
max_attempts: form.value.order_extraction_max_attempts,
},
};
}
if (form.value.exposure_mode === 'internal') {
extra_config.order_extraction_governance = {
provider_max_concurrency: form.value.executor_provider_max_concurrency,
@@ -16,7 +16,7 @@ defineEmits<{ close: []; edit: [profile: ShippingOrderDocumentProfile]; publish:
<aside v-if="open" class="drawer" :aria-label="t('admin.shippingOrderProfiles.versions')">
<header><strong>{{ t('admin.shippingOrderProfiles.versions') }}</strong><button type="button" @click="$emit('close')">{{ t('common.close') }}</button></header>
<article v-for="profile in profiles" :key="profile.id">
<div><b>{{ profile.display_name }} · v{{ profile.version }}</b><small>{{ profile.profile_code }} · {{ profile.status }}</small><small v-if="profile.migration_status === 'needs_revalidation'" class="migration-status">{{ t('admin.shippingOrderProfiles.migrationNeedsReview') }}</small></div>
<div><b>{{ profile.display_name }} · v{{ profile.version }}</b><small>{{ profile.profile_code }} · {{ profile.status }}</small><small v-if="profile.auto_freeze_qualification">{{ t(`admin.shippingOrderProfiles.autoFreezeQualification.${profile.auto_freeze_qualification.status}`) }}</small><small v-if="profile.migration_status === 'needs_revalidation'" class="migration-status">{{ t('admin.shippingOrderProfiles.migrationNeedsReview') }}</small></div>
<div class="actions">
<button v-if="profile.status === 'draft'" type="button" @click="$emit('edit', profile)">{{ t('common.edit') }}</button>
<button v-if="profile.status === 'draft'" type="button" @click="$emit('test', profile)">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</button>
@@ -110,7 +110,9 @@ onMounted(() => { void load(); });
<p v-if="detailLoading" class="mt-6 text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</p>
<template v-else-if="detail"><dl class="mt-5 grid grid-cols-2 gap-3 text-sm"><dt>{{ t('admin.shippingOrderExtractionRuns.runNo') }}</dt><dd class="font-mono text-xs">{{ detail.run.run_no }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.workflowRunId') }}</dt><dd class="font-mono text-xs">{{ detail.run.workflow_run_id || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.errorCode') }}</dt><dd>{{ detail.run.error_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</dt><dd>{{ formatDuration(detail.run.durations_ms.total) }}</dd></dl>
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.jobAttempts') }}</h3><div class="mt-2 space-y-2"><div v-for="job in detail.job_attempts" :key="job.job_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ job.job_id }}</b> · {{ job.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ job.attempts }}/{{ job.max_attempts }} · {{ formatDuration(job.duration_ms) }}</div><p v-if="!detail.job_attempts.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.units') }}</h3><div class="mt-2 space-y-2"><div v-for="unit in detail.units" :key="unit.unit_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ unit.position + 1 }} {{ unit.unit_type }}</b> · {{ unit.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ unit.attempt_count }} · {{ formatDuration(unit.duration_ms) }}<span v-if="unit.error_code" class="ml-2 font-mono text-xs text-danger">{{ unit.error_code }}</span></div><p v-if="!detail.units.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.units') }}</h3><div class="mt-2 space-y-2"><div v-for="unit in detail.units" :key="unit.unit_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ unit.position + 1 }} {{ unit.unit_type }}</b> · {{ unit.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ unit.attempt_count }} · {{ formatDuration(unit.duration_ms) }}<span v-if="unit.error_code" class="ml-2 font-mono text-xs text-danger">{{ unit.error_code }}</span>
<section v-for="route in unit.route_decisions" :key="`${unit.unit_id}:${route.attempt_no}`" class="mt-3 rounded border border-default bg-slate-50 p-3 text-xs dark:bg-slate-900/40"><h4 class="font-semibold text-primary">{{ t('admin.shippingOrderExtractionRuns.routeDecision') }} #{{ route.attempt_no }}</h4><dl class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1"><dt>{{ t('admin.shippingOrderExtractionRuns.executionMode') }}</dt><dd>{{ t(`admin.shippingOrderExtractionRuns.executionModes.${route.execution_mode}`) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.matchStatus') }}</dt><dd>{{ t(`admin.shippingOrderExtractionRuns.matchStatuses.${route.match_status}`) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.selectedProfile') }}</dt><dd>{{ route.selected_profile_code ? `${route.selected_profile_code} V${route.selected_profile_version}` : '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.autoCreateApproved') }}</dt><dd>{{ route.auto_create_approved == null ? '-' : t(route.auto_create_approved ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.fallbackReasons') }}</dt><dd>{{ route.fallback_reason_codes.length ? route.fallback_reason_codes.map(code => t(`admin.shippingOrderExtractionRuns.reasonCodes.${code}`)).join(';') : '-' }}</dd></dl><div v-if="route.candidates.length" class="mt-3"><p class="font-medium">{{ t('admin.shippingOrderExtractionRuns.candidates') }}</p><div v-for="candidate in route.candidates" :key="`${candidate.profile_code}:${candidate.version}`" class="mt-1 flex flex-wrap gap-x-2 text-muted"><span>{{ candidate.profile_code }} V{{ candidate.version }}</span><span>{{ candidate.score.toFixed(2) }}</span><span>{{ candidate.hard_match ? t('admin.shippingOrderExtractionRuns.hardMatch') : t('admin.shippingOrderExtractionRuns.hardMismatch') }}</span><span v-if="candidate.missing_required_anchor_ids?.length">{{ t('admin.shippingOrderExtractionRuns.missingAnchors', { ids: candidate.missing_required_anchor_ids.join(', ') }) }}</span></div></div></section>
</div><p v-if="!detail.units.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.lifecycle') }}</h3><div class="mt-2 space-y-2"><div v-for="event in detail.progress_events" :key="`${event.node_execution_id}:${event.event_type}:${event.occurred_at}`" class="rounded-lg border border-default p-3 text-sm"><b>{{ event.stage_code || event.event_type }}</b><span class="ml-2 text-secondary">{{ event.status || '-' }}</span><span class="ml-2 font-mono text-xs text-muted">{{ event.node_type || '-' }}</span><time class="ml-2 text-xs text-muted">{{ formatTime(event.occurred_at) }}</time></div><p v-if="!detail.progress_events.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
</template>
</aside>
@@ -132,10 +132,6 @@ export interface AgentFormState {
training_hr_chat_questions_text: string;
training_question_bank: AgentTrainingQuestionFormItem[];
directory_member_ids: number[];
order_extraction_binding_enabled: boolean;
order_extraction_provider_agent_id: number | null;
order_extraction_timeout_seconds: number;
order_extraction_max_attempts: number;
executor_provider_max_concurrency: number;
executor_circuit_failure_threshold: number;
executor_circuit_cooldown_seconds: number;
@@ -198,10 +194,6 @@ export const createEmptyAgentForm = (
training_hr_chat_questions_text: '',
training_question_bank: [],
directory_member_ids: [],
order_extraction_binding_enabled: true,
order_extraction_provider_agent_id: null,
order_extraction_timeout_seconds: 900,
order_extraction_max_attempts: 3,
executor_provider_max_concurrency: 4,
executor_circuit_failure_threshold: 5,
executor_circuit_cooldown_seconds: 60,
@@ -59,6 +59,13 @@ export interface ShippingOrderDocumentProfile {
review_changes?: Array<{ field_id: string; reason: string; before?: unknown; after?: unknown }>;
} | null;
migration_status?: 'normal' | 'needs_revalidation' | 'blocked';
auto_freeze_qualification?: {
status: 'manual_confirmation' | 'auto_freeze_approved' | 'auto_freeze_suspended';
auto_freeze_enabled: boolean;
qualification_id: number | null;
parser_version?: string;
quality_suite_id?: number | null;
};
}
/** 受控预览授权只对单页生效,令牌不得持久化或复用。 */
@@ -1,87 +0,0 @@
/**
* features/chat/api/chat.api.spec.ts
* 用途:验证聊天历史接口适配层不会在 hydrate 过程中丢失用户附件快照。
* 依赖:Vitest、mock 后的 shared/api/client 与 auth、chat.api。
* 逻辑:覆盖历史消息过滤 shipping-parse-review、恢复订单识别状态时仍保留 attachments。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { listChatMessages } from './chat.api';
vi.mock('@/shared/utils/auth', () => ({
getAuthHeaders: vi.fn(() => ({ Authorization: 'Bearer test-token' })),
}));
vi.mock('@/shared/api/client', () => ({
requestJson: vi.fn(),
}));
import { requestJson } from '@/shared/api/client';
const requestJsonMock = vi.mocked(requestJson);
describe('chat.api history hydration', () => {
beforeEach(() => {
requestJsonMock.mockReset();
});
it('keeps user attachment snapshots while hydrating persisted assistant payload', async () => {
requestJsonMock.mockResolvedValue([
{
role: 'user',
content: '',
attachments: [{
id: 'attachment-only-1',
name: 'notice.eml',
type: 'document',
source: 'shipping_notice',
}],
},
{
role: 'assistant',
content: '中间态消息',
type: 'shipping-parse-review',
},
{
role: 'assistant',
content: '订单识别完成',
payload: {
shipping_order_extraction_state: {
status: 'completed',
phase: 'result_persisted',
message: '已创建 1 个任务',
created_count: 1,
opened_existing_count: 0,
pending_count: 0,
non_shipping_count: 0,
created_with_missing_fields_count: 0,
batch_no: 'SB-HISTORY-001',
terminal: true,
},
},
},
]);
const messages = await listChatMessages('conv-history-1', 24);
expect(requestJsonMock).toHaveBeenCalledWith(
'/api/chat/messages?conversation_id=conv-history-1&agent_id=24',
{ headers: { Authorization: 'Bearer test-token' } },
);
expect(messages).toHaveLength(2);
expect(messages[0]).toEqual({
role: 'user',
content: '',
attachments: [{
id: 'attachment-only-1',
name: 'notice.eml',
type: 'document',
source: 'shipping_notice',
}],
});
expect(messages[1]?.shipping_order_extraction_state).toMatchObject({
status: 'completed',
batch_no: 'SB-HISTORY-001',
terminal: true,
});
});
});
+25 -16
View File
@@ -422,6 +422,11 @@ export async function submitWorkspaceShippingDecision(taskNo: string, decision:
return assertShippingOk(body);
}
/** 人工复核证据只允许已绑定文档单元格或具名人工输入。 */
export type ShippingReviewEvidence =
| { evidence_type: 'document_cell'; document_id: number; observation_id: number; page_no: number; table_id: string; cell_id: string }
| { evidence_type: 'manual_input'; reason: string };
/**
* 更新发货通知单头字段。
* @param taskNo - 发货任务编号
@@ -432,18 +437,18 @@ export async function submitWorkspaceShippingDecision(taskNo: string, decision:
export async function updateWorkspaceShippingNoticeFields(
taskNo: string,
fields: Partial<ShippingNoticeHeader>,
comment?: string,
options?: { expectedOrderDataVersion?: number; idempotencyKey?: string },
comment: string | undefined,
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-fields`,
jsonPost({
fields,
...(comment ? { comment } : {}),
...(options?.expectedOrderDataVersion != null
? { expected_order_data_version: options.expectedOrderDataVersion }
: {}),
...(options?.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
expected_order_data_version: options.expectedOrderDataVersion,
evidence: options.evidence,
reason: options.reason,
...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
}),
);
return assertShippingOk(body);
@@ -479,8 +484,8 @@ export async function updateWorkspaceShippingNoticeLine(
taskNo: string,
lineIndex: number,
patch: Partial<ShippingNoticeLine> & { quantity?: number },
comment?: string,
options?: { expectedOrderDataVersion?: number; idempotencyKey?: string },
comment: string | undefined,
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-line`,
@@ -488,10 +493,10 @@ export async function updateWorkspaceShippingNoticeLine(
line_index: lineIndex,
patch,
...(comment ? { comment } : {}),
...(options?.expectedOrderDataVersion != null
? { expected_order_data_version: options.expectedOrderDataVersion }
: {}),
...(options?.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
expected_order_data_version: options.expectedOrderDataVersion,
evidence: options.evidence,
reason: options.reason,
...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
}),
);
return assertShippingOk(body);
@@ -522,6 +527,7 @@ export async function resolveWorkspaceShippingFieldConflict(
expectedConflictVersion?: number;
expectedOrderDataVersion?: number;
reason?: string;
evidence: ShippingReviewEvidence;
idempotencyKey?: string;
},
) {
@@ -542,6 +548,7 @@ export async function resolveWorkspaceShippingFieldConflict(
? { expected_order_data_version: payload.expectedOrderDataVersion }
: {}),
...(payload.reason ? { reason: payload.reason } : {}),
evidence: payload.evidence,
...(payload.idempotencyKey ? { idempotency_key: payload.idempotencyKey } : {}),
}),
);
@@ -557,11 +564,12 @@ export async function resolveWorkspaceShippingFieldConflict(
export async function addWorkspaceShippingNoticeLine(
taskNo: string,
line: Partial<ShippingNoticeLine> & { quantity?: number },
comment?: string,
comment: string | undefined,
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/add-notice-line`,
jsonPost({ line, ...(comment ? { comment } : {}) }),
jsonPost({ line, ...(comment ? { comment } : {}), expected_order_data_version: options.expectedOrderDataVersion, evidence: options.evidence, reason: options.reason, ...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}) }),
);
return assertShippingOk(body);
}
@@ -576,11 +584,12 @@ export async function addWorkspaceShippingNoticeLine(
export async function removeWorkspaceShippingNoticeLine(
taskNo: string,
lineIndex: number,
comment?: string,
comment: string | undefined,
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/remove-notice-line`,
jsonPost({ line_index: lineIndex, ...(comment ? { comment } : {}) }),
jsonPost({ line_index: lineIndex, ...(comment ? { comment } : {}), expected_order_data_version: options.expectedOrderDataVersion, evidence: options.evidence, reason: options.reason, ...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}) }),
);
return assertShippingOk(body);
}
@@ -132,6 +132,9 @@ function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachmen
failed: issues,
});
}
if (attachment.layoutStatus === 'processing') {
return t('chat.shippingNoticeAttachmentHintLayoutProcessing', { ok, total: effectiveTotal });
}
if (duplicates > 0) {
return t('chat.shippingNoticeAttachmentHintWithDup', { ok, total: effectiveTotal, duplicates });
}
@@ -40,6 +40,11 @@ const items = computed(() =>
<div v-if="item.document_id != null">
{{ t('chat.shippingParsedResult.documentId', { id: item.document_id }) }}
</div>
<div v-if="item.page_no != null">
{{ t('chat.shippingParsedResult.pageNumber', { page: item.page_no }) }}
<span v-if="item.table_id" class="ml-1 font-mono">{{ item.table_id }}</span>
<span v-if="item.cell_id" class="ml-1 font-mono">{{ item.cell_id }}</span>
</div>
<blockquote
v-if="item.quote"
class="rounded border border-slate-200 bg-slate-50 px-2 py-1.5 font-mono text-[11px] leading-5 text-slate-700"
@@ -37,13 +37,15 @@ async function resolveConflict(
conflict: ShippingFieldConflict,
resolution: 'keep_existing' | 'take_incoming',
) {
if (!props.taskNo || resolvingId.value != null) return;
if (!props.taskNo || resolvingId.value != null || props.orderDataVersion == null) return;
resolvingId.value = conflict.id;
try {
await resolveWorkspaceShippingFieldConflict(props.taskNo, conflict.id, {
resolution,
expectedConflictVersion: conflict.conflict_version,
expectedOrderDataVersion: props.orderDataVersion ?? undefined,
expectedOrderDataVersion: props.orderDataVersion,
evidence: { evidence_type: 'manual_input', reason: '工作台人工解决字段冲突' },
reason: '工作台人工解决字段冲突',
idempotencyKey: `conflict-${conflict.id}-${resolution}-${conflict.conflict_version}`,
});
msg.success(t('chat.shippingFieldConflict.resolveSuccess'));
@@ -1,8 +1,8 @@
/**
* features/chat/components/messages/ChatMessageAttachmentList.vue
* 用途:在用户消息气泡内部展示已发送附件快照。
* 用途:在用户消息中展示已发送附件快照。
* 依赖:lucide 文件图标、attachmentCard.utils 的大小格式化、chat.types 的消息附件契约。
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;卡片继承品牌气泡语境,只读展示且不提供删除或重试。
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;本组件只读展示,不提供删除、重试或上传状态操作。
*/
<script setup lang="ts">
import { FileAudio, FileImage, FileText, FileVideo, Link2 } from 'lucide-vue-next';
@@ -35,16 +35,16 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
<div
v-if="attachments.length > 0"
data-testid="chat-message-attachment-list"
class="flex w-full flex-wrap justify-end gap-2"
class="mb-2 flex w-full flex-wrap justify-end gap-2"
>
<article
v-for="(attachment, attachmentIndex) in attachments"
:key="attachment.id || `${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex min-w-0 basis-full items-center gap-2.5 rounded-xl border border-white/20 bg-white/10 px-3 py-2.5 shadow-sm backdrop-blur-sm sm:basis-[calc(50%-0.25rem)] sm:min-w-[220px] sm:max-w-[290px]"
:key="`${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex min-w-0 basis-full items-center gap-2.5 rounded-xl border border-default bg-surface px-3 py-2.5 shadow-sm dark:bg-slate-900 sm:basis-[calc(50%-0.25rem)] sm:min-w-[220px] sm:max-w-[290px]"
:title="attachment.name"
>
<div
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-white/15 text-white"
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
aria-hidden="true"
>
<component :is="attachmentIcon(attachment)" class="h-4 w-4" />
@@ -53,8 +53,8 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
</span>
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-semibold text-white">{{ attachment.name }}</div>
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-white/70">
<div class="truncate text-sm font-semibold text-primary">{{ attachment.name }}</div>
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-muted">
{{ formatAttachmentSize(attachment.size) }}
</div>
</div>
@@ -1,21 +1,22 @@
/**
* 用途:验证聊天流的附件快照、货代 UI State 与终态事件过滤。
* features/chat/composables/useChat.spec.ts
* 用途:验证聊天流对发货通知 UI State 与订单识别生命周期 SSE 的消息级回写行为。
* 逻辑:覆盖任务状态投影、terminal 后 UI State 放行及用户附件快照。
* 依赖:vitest、useChat/chat.api 导出的纯函数、chat.types。
* 逻辑:覆盖任务状态投影、订单识别终态保护、terminal 后事件放行及历史 payload 恢复。
*/
import { describe, expect, it } from 'vitest';
import {
applyShippingOrderExtractionStateToMessage,
applyShippingUiStateToMessage,
createUserChatMessage,
isAllowedAfterStreamTerminal,
} from './useChat';
import { hydrateShippingOrderExtractionState } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
describe('useChat user attachment snapshots', () => {
it('copies sent attachments onto the user message without inheriting them for text-only messages', () => {
const attachments = [{
id: 'attachment-1',
name: 'purchase-order.pdf',
size: 144_456,
extension: 'pdf',
@@ -126,11 +127,92 @@ describe('useChat shipping_ui_state SSE', () => {
});
});
describe('useChat shipping_order_extraction_state SSE', () => {
it('replaces extracting with persisted facts without overwriting Dify content', () => {
const message: ChatMessage = {
role: 'assistant',
content: 'Dify 最终正文保持不变',
payload: { existing_key: 'kept' },
};
describe('useChat terminal event filtering', () => {
it('allows only shipping UI state after the upstream terminal event', () => {
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'extracting',
phase: 'llm_extraction',
message: '正在识别邮件及附件中的订单',
created_count: -1,
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('extracting');
expect(message.shipping_order_extraction_state?.created_count).toBe(0);
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'completed',
phase: 'result_persisted',
message: '已创建 1 个发货任务',
created_count: 1,
opened_existing_count: 2,
pending_count: 0,
non_shipping_count: 3,
created_with_missing_fields_count: 1,
batch_no: 'SB-STATE-001',
terminal: true,
});
expect(message.content).toBe('Dify 最终正文保持不变');
expect(message.shipping_order_extraction_state).toMatchObject({
status: 'completed',
created_count: 1,
opened_existing_count: 2,
non_shipping_count: 3,
batch_no: 'SB-STATE-001',
terminal: true,
});
expect((message.payload as Record<string, unknown>).existing_key).toBe('kept');
expect((message.payload as { shipping_order_extraction_state?: { created_count?: number } })
.shipping_order_extraction_state?.created_count).toBe(1);
// 关键断言:网络重排导致的迟到进行态不能覆盖已经展示的终态。
applyShippingOrderExtractionStateToMessage(message, {
status: 'extracting',
phase: 'llm_extraction',
message: '迟到事件',
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('completed');
});
it('allows HXOPS domain states after the upstream terminal event', () => {
expect(isAllowedAfterStreamTerminal('shipping_order_extraction_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('shipping_ui_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('shipping_order_extraction_state')).toBe(false);
expect(isAllowedAfterStreamTerminal('agent_message')).toBe(false);
});
it('hydrates persisted terminal state from ChatLog payload', () => {
const message: ChatMessage = {
role: 'assistant',
content: '订单识别完成',
payload: {
shipping_order_extraction_state: {
status: 'partially_completed',
phase: 'result_persisted',
message: '仍有 1 个订单需要补充信息',
created_count: 1,
opened_existing_count: 0,
pending_count: 1,
non_shipping_count: 0,
created_with_missing_fields_count: 0,
batch_no: 'SB-HISTORY-001',
terminal: true,
},
},
};
hydrateShippingOrderExtractionState(message);
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
expect(message.shipping_order_extraction_state?.pending_count).toBe(1);
expect(message.shipping_order_extraction_state?.batch_no).toBe('SB-HISTORY-001');
});
});
@@ -36,7 +36,6 @@ 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 = [];
@@ -45,7 +44,6 @@ const createConversationContext = () => {
return {
conversationId,
messages,
loadConversationState,
createNewChatView,
api: createChatPageConversationApi({
deps: { t: (key: string) => key, msg: { warning: vi.fn() } },
@@ -56,7 +54,7 @@ const createConversationContext = () => {
activeRunId: ref(null),
messages,
isThinking: ref(false),
loadConversationState,
loadConversationState: vi.fn(),
createNewChatView,
clearPendingNoticeBatchRetry,
onConversationIdChanging: vi.fn(),
@@ -99,6 +97,7 @@ const createUploadContext = (
shippingBatchTasks: ref([]),
shippingInventorySelectionActive: ref(false),
shippingInventorySelectionTaskId: ref(''),
shippingInventorySchemaPreviewCache: ref({}),
getActiveShippingTaskId: () => '',
startChatTurn,
refreshShippingActions: vi.fn(async () => undefined),
@@ -164,32 +163,4 @@ 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',
}],
}]);
});
});
@@ -10,7 +10,6 @@ import { createChatPageSendApi, type ChatPageSendContext } from './useChatPageSe
import type { ChatMessageAttachment } from '../types/chat.types';
const attachmentSnapshots: ChatMessageAttachment[] = [{
id: 'attachment-1',
name: 'purchase-order.pdf',
size: 3,
extension: 'pdf',
@@ -35,7 +34,7 @@ function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSe
]),
createMessageAttachmentSnapshots: vi.fn(() => attachmentSnapshots.map((item) => ({ ...item }))),
clearAttachments: vi.fn(),
sendMessage: vi.fn(async () => ({ accepted: true, completed: true })),
sendMessage: vi.fn(async () => true),
refreshHistoryAfterSend: vi.fn(async () => undefined),
refreshConversationAfterSend: vi.fn(async () => undefined),
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
@@ -62,26 +61,25 @@ describe('createChatPageSendApi attachment lifecycle', () => {
expect(ctx.sendMessage).not.toHaveBeenCalled();
});
it('keeps uploaded attachments and restores input when the request is not accepted', async () => {
it('keeps uploaded attachments when message sending fails', async () => {
const ctx = createContext({
sendMessage: vi.fn(async () => ({ accepted: false, completed: false })),
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.input.value).toBe('请分析附件');
});
it('clears attachments when the request is accepted even if the assistant stream fails', async () => {
const ctx = createContext({
sendMessage: vi.fn(async () => ({ accepted: true, completed: false, chatLogId: 42 })),
});
await createChatPageSendApi(ctx).handleSend();
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
expect(ctx.refreshHistoryAfterSend).toHaveBeenCalledOnce();
expect(ctx.refreshHistoryAfterSend).not.toHaveBeenCalled();
});
it('clears attachments only after message sending succeeds', async () => {
@@ -12,6 +12,7 @@ import {
updateWorkspaceShippingNoticeLine,
type ShippingNoticeHeader,
type ShippingNoticeLine,
type ShippingReviewEvidence,
} from '@/features/chat/api/shipping.api';
import { getShippingParseReviewPayload } from './shippingParseReview';
import type { ChatMessage } from '../types/chat.types';
@@ -34,6 +35,7 @@ export interface ShippingParseReviewContext {
* @returns 复核卡片同步与编辑处理函数集合
*/
export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContext) {
const manualEvidence = (reason: string): ShippingReviewEvidence => ({ evidence_type: 'manual_input', reason });
/**
* 读取任务当前 order_data_version,供改单乐观锁使用。
* @param taskId - 任务编号
@@ -75,8 +77,10 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
const expectedOrderDataVersion = await resolveOrderDataVersion(taskId);
if (expectedOrderDataVersion == null) throw new Error('订单版本不可用,请刷新后重试');
await updateWorkspaceShippingNoticeFields(taskId, fields, '聊天区订单表修订', {
expectedOrderDataVersion,
evidence: manualEvidence('聊天区人工复核'), reason: '聊天区人工复核',
idempotencyKey: `parse-review-header-${taskId}-${expectedOrderDataVersion ?? 'na'}-${Date.now()}`,
});
await syncShippingParseReviewCard(taskId);
@@ -102,8 +106,10 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
const expectedOrderDataVersion = await resolveOrderDataVersion(taskId);
if (expectedOrderDataVersion == null) throw new Error('订单版本不可用,请刷新后重试');
await updateWorkspaceShippingNoticeLine(taskId, lineIndex, patch, '聊天区订单表修订', {
expectedOrderDataVersion,
evidence: manualEvidence('聊天区人工复核'), reason: '聊天区人工复核',
idempotencyKey: `parse-review-line-${taskId}-${lineIndex}-${expectedOrderDataVersion ?? 'na'}`,
});
await syncShippingParseReviewCard(taskId);
@@ -127,7 +133,11 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
payload.saving = true;
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
await addWorkspaceShippingNoticeLine(taskId, line, '聊天区订单表新增行');
const expectedOrderDataVersion = await resolveOrderDataVersion(taskId);
if (expectedOrderDataVersion == null) throw new Error('订单版本不可用,请刷新后重试');
await addWorkspaceShippingNoticeLine(taskId, line, '聊天区订单表新增行', {
expectedOrderDataVersion, evidence: manualEvidence('聊天区人工新增行'), reason: '聊天区人工新增行',
});
await syncShippingParseReviewCard(taskId);
await ctx.refreshShippingActions();
return true;
@@ -149,7 +159,11 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
payload.saving = true;
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
await removeWorkspaceShippingNoticeLine(taskId, lineIndex, '聊天区订单表删除行');
const expectedOrderDataVersion = await resolveOrderDataVersion(taskId);
if (expectedOrderDataVersion == null) throw new Error('订单版本不可用,请刷新后重试');
await removeWorkspaceShippingNoticeLine(taskId, lineIndex, '聊天区订单表删除行', {
expectedOrderDataVersion, evidence: manualEvidence('聊天区人工删除行'), reason: '聊天区人工删除行',
});
await syncShippingParseReviewCard(taskId);
await ctx.refreshShippingActions();
return true;
@@ -39,7 +39,7 @@ const createContext = (
getActiveShippingTaskId: () => '',
lastAssistantMessageContent: () => '',
lastAssistantShippingActions: () => [],
sendMessage: vi.fn(async () => ({ accepted: true, completed: true })),
sendMessage: vi.fn(async () => true),
buildFileSpecsForSend: vi.fn(async () => []),
loadHistory: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
@@ -51,7 +51,8 @@ const createContext = (
handleShippingAutoUploadFile: vi.fn(async () => undefined),
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
startOrderExtractionRun: vi.fn(async () => true),
markOrderExtractionStarted: vi.fn(),
rollbackOrderExtractionStarted: vi.fn(),
syncShippingConversationWorkspace: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
shippingSuggestedPrompt: computed(() => ''),
@@ -81,41 +82,8 @@ describe('useChatShippingSendHandler', () => {
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
});
it('keeps a spreadsheet pending until the user explicitly declares it as inventory', async () => {
const attachment = {
id: 'spreadsheet', kind: 'local' as const,
file: new File(['sheet'], 'unknown.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
type: 'document' as const, uploadStatus: 'waiting' as const, uploadProgress: 0,
};
const ctx = createContext({ attachments: ref([attachment]) });
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadFile).not.toHaveBeenCalled();
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeSpreadsheetIntentRequired');
expect(ctx.attachments.value).toHaveLength(1);
});
it('routes a declared xls spreadsheet to the isolated temporary inventory path', async () => {
const attachment = {
id: 'legacy-spreadsheet', kind: 'local' as const,
file: new File(['sheet'], 'inventory.xls', { type: 'application/vnd.ms-excel' }),
type: 'document' as const, uploadStatus: 'waiting' as const, uploadProgress: 0,
};
const ctx = createContext({ attachments: ref([attachment]), shippingAutoFlowRequested: ref(false) });
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow('这是库存文件,请分析', '这是库存文件,请分析', '这是库存文件,请分析');
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadFile).toHaveBeenCalledWith(attachment.file);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
});
it('creates a background Run for parsed intakes without calling the Chatflow', async () => {
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
const completionOrder: string[] = [];
const attachment = {
id: 'notice-1',
kind: 'shipping_notice' as const,
@@ -132,6 +100,11 @@ describe('useChatShippingSendHandler', () => {
hasCandidateReviewIssues: () => true,
hasSelectedNoticeCandidates: () => true,
getParsedIntakeNos: () => ['SNI-1'],
applyShippingBatchSnapshot: vi.fn(() => { completionOrder.push('snapshot'); return true; }),
refreshNoticeIntakeStatuses: vi.fn(async () => { completionOrder.push('intakes'); }),
syncShippingConversationWorkspace: vi.fn(async () => { completionOrder.push('workspace'); return true; }),
clearConsumedNoticeAttachments: vi.fn(() => { completionOrder.push('clear'); }),
refreshShippingActions: vi.fn(async () => { completionOrder.push('actions'); }),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
@@ -139,20 +112,34 @@ describe('useChatShippingSendHandler', () => {
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.startOrderExtractionRun).toHaveBeenCalledWith(
expect(ctx.sendMessage).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultPrompt',
['SNI-1'],
[{
id: 'notice-1',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
},
expect.objectContaining({
userAttachments: [{
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
}],
onAssistantMessageFinished: expect.any(Function),
}),
);
expect(ctx.sendMessage).not.toHaveBeenCalled();
expect(ctx.attachments.value).toEqual([]);
expect(ctx.markOrderExtractionStarted).toHaveBeenCalledWith(['SNI-1']);
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
const assistantMessage = { role: 'assistant', content: '已打开已有任务' } as const;
await hooks?.onAssistantMessageFinished?.(assistantMessage, []);
expect(ctx.applyShippingBatchSnapshot).toHaveBeenCalledWith(assistantMessage);
expect(completionOrder).toEqual(['snapshot', 'intakes', 'workspace', 'clear', 'actions']);
expect(ctx.syncShippingConversationWorkspace).toHaveBeenCalledWith({ preferLatest: true });
});
it('uses the user query for full extraction even when no candidate exists before send', async () => {
@@ -179,21 +166,32 @@ describe('useChatShippingSendHandler', () => {
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.startOrderExtractionRun).toHaveBeenCalledWith(
expect(ctx.sendMessage).toHaveBeenCalledWith(
'请解析这些附件',
['SNI-1'],
[{
id: 'notice-1',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: '请解析这些附件',
},
expect.objectContaining({
userAttachments: [{
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
}],
onAssistantMessageFinished: expect.any(Function),
}),
);
});
it('keeps attachments when Run creation reports not started', async () => {
it('retries the conversation workspace once when the first refresh fails', async () => {
const syncWorkspace = vi.fn()
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true);
const ctx = createContext({
attachments: ref([{
id: 'notice-retry',
@@ -207,15 +205,22 @@ describe('useChatShippingSendHandler', () => {
intakeNo: 'SNI-RETRY',
}]),
getParsedIntakeNos: () => ['SNI-RETRY'],
startOrderExtractionRun: vi.fn(async () => false),
syncShippingConversationWorkspace: syncWorkspace,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(ctx.attachments.value).toHaveLength(1);
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
await hooks?.onAssistantMessageFinished?.({} as never, []);
expect(syncWorkspace).toHaveBeenCalledTimes(2);
expect(syncWorkspace).toHaveBeenNthCalledWith(1, { preferLatest: true });
expect(syncWorkspace).toHaveBeenNthCalledWith(2, { preferLatest: true });
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('keeps attachments and reports the error when Run creation fails', async () => {
it('rolls back the local extracting state when the chat request fails', async () => {
const rollback = vi.fn();
const ctx = createContext({
attachments: ref([{
id: 'notice-failed-send',
@@ -229,18 +234,20 @@ describe('useChatShippingSendHandler', () => {
intakeNo: 'SNI-FAILED-SEND',
}]),
getParsedIntakeNos: () => ['SNI-FAILED-SEND'],
startOrderExtractionRun: vi.fn(async () => { throw new Error('network failed'); }),
sendMessage: vi.fn(async () => { throw new Error('network failed'); }),
rollbackOrderExtractionStarted: rollback,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(rollback).toHaveBeenCalledWith(['SNI-FAILED-SEND']);
expect(ctx.msg.warning).toHaveBeenCalledWith('network failed');
expect(ctx.attachments.value).toHaveLength(1);
});
it('does not call the Chatflow when Run creation is handled as unavailable', async () => {
it('rolls back extraction state when sendMessage reports a handled stream failure', async () => {
const rollback = vi.fn();
const ctx = createContext({
attachments: ref([{
id: 'notice-handled-failure',
@@ -254,46 +261,15 @@ describe('useChatShippingSendHandler', () => {
intakeNo: 'SNI-HANDLED-FAILURE',
}]),
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
startOrderExtractionRun: vi.fn(async () => false),
sendMessage: vi.fn(async () => false),
rollbackOrderExtractionStarted: rollback,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.sendMessage).not.toHaveBeenCalled();
expect(ctx.attachments.value).toHaveLength(1);
});
it('removes only the Intake set accepted by the background Run', async () => {
const submitted = {
id: 'notice-accepted-error',
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-ACCEPTED-ERROR',
};
const retained = {
...submitted,
id: 'notice-retained',
originalFilename: 'other.eml',
intakeNo: 'SNI-RETAINED',
};
const ctx = createContext({
attachments: ref([submitted, retained]),
getParsedIntakeNos: () => ['SNI-ACCEPTED-ERROR'],
startOrderExtractionRun: vi.fn(async () => true),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.attachments.value).toEqual([retained]);
expect(ctx.sendMessage).not.toHaveBeenCalled();
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
expect(ctx.loadHistory).not.toHaveBeenCalled();
});
});
@@ -31,6 +31,8 @@ describe('shipping notice order extraction state', () => {
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'partially_completed' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'completed' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'failed' })).toBe(true);
expect(isOrderExtractionEligibleIntake({ ...base, layoutStatus: 'processing' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, layoutStatus: 'completed' })).toBe(true);
});
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
@@ -46,6 +48,11 @@ describe('shipping notice order extraction state', () => {
parseStatus: 'parsed',
orderExtractionStatus: 'failed',
})).toBe(false);
expect(shouldPollShippingNoticeIntake({
parseStatus: 'parsed',
orderExtractionStatus: 'not_started',
layoutStatus: 'processing',
})).toBe(true);
});
it('preserves the immediate extracting state until the backend leaves not_started', () => {
@@ -61,6 +68,7 @@ describe('shipping notice order extraction state', () => {
expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'failed', 0)).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 2)).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, 'processing')).toBe(true);
// 已完成且没有待审核 Candidate 的文件仅保留在用户消息气泡中。
expect(shouldRestoreShippingNoticeIntake('parsed')).toBe(false);
@@ -1,7 +1,7 @@
/**
* features/chat/shipping/useShippingNoticeIntakes.ts
* 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。
* 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity。
* 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity、后端布局状态汇总。
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件;
* 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐);会话刷新仅恢复未提交的处理中或解析失败附件。
*/
@@ -51,34 +51,55 @@ export function shouldRestoreShippingNoticeIntake(
parseStatus: string | null | undefined,
orderExtractionStatus?: string | null,
candidateCount = 0,
layoutStatus?: ShippingNoticePendingAttachment['layoutStatus'],
): boolean {
const status = String(parseStatus || '').trim().toLowerCase();
const extractionStatus = String(orderExtractionStatus || '').trim().toLowerCase();
return ACTIVE_PARSE.has(status)
|| status === 'parse_failed'
|| layoutStatus === 'processing'
|| extractionStatus === 'failed'
|| (extractionStatus === 'partially_completed' && candidateCount > 0);
}
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
export function shouldPollShippingNoticeIntake(
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus'>,
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus' | 'layoutStatus'>,
): boolean {
return !TERMINAL_PARSE.has(item.parseStatus)
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase())
|| item.layoutStatus === 'processing';
}
/** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */
export function isOrderExtractionEligibleIntake(
item: Pick<ShippingNoticePendingAttachment, 'intakeNo' | 'parseStatus' | 'parseSummary' | 'orderExtractionStatus'>,
item: Pick<ShippingNoticePendingAttachment, 'intakeNo' | 'parseStatus' | 'parseSummary' | 'orderExtractionStatus' | 'layoutStatus'>,
): boolean {
const extractionStatus = String(item.orderExtractionStatus || 'not_started').trim().toLowerCase();
return item.parseStatus === 'parsed'
&& Boolean(item.intakeNo)
&& (extractionStatus === 'not_started' || extractionStatus === 'failed')
&& item.layoutStatus !== 'processing'
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary);
}
/** 把后端布局汇总投影为附件卡片使用的最小状态,旧响应缺字段时保持兼容。 */
function mapServerLayout(remote: ShippingNoticeIntakeResponse): Pick<ShippingNoticePendingAttachment, 'layoutStatus' | 'layoutSummary'> {
const summary = remote.layout_summary;
return {
layoutStatus: remote.layout_status || summary?.status,
layoutSummary: summary ? {
total: Number(summary.total || 0),
queued: Number(summary.queued || 0),
running: Number(summary.running || 0),
ready: Number(summary.ready || 0),
needs_review: Number(summary.needs_review || 0),
failed: Number(summary.failed || 0),
unsupported: Number(summary.unsupported || 0),
} : undefined,
};
}
/** 保留刚点击发送的本地 extracting,直到服务端进入真实抽取状态或返回终态。 */
export function resolveShippingOrderExtractionStatus(localStatus?: string, remoteStatus?: string | null): string | undefined {
const local = String(localStatus || '').trim().toLowerCase();
@@ -239,6 +260,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|| ACTIVE_PARSE.has(item.parseStatus)
|| item.parseStatus === 'queued'
|| item.parseStatus === 'parsing'
|| item.layoutStatus === 'processing'
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()),
),
);
@@ -339,6 +361,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
remote.order_extraction_status,
),
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
...mapServerLayout(remote),
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,
@@ -369,6 +392,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
parseStatus: mapServerParseStatus(intake.parse_status),
orderExtractionStatus: intake.order_extraction_status || undefined,
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
...mapServerLayout(intake),
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,
@@ -421,6 +445,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
patchAttachment(id, {
parseStatus: mapServerParseStatus(intake.parse_status),
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
...mapServerLayout(intake),
errorCode: intake.error_code || undefined,
errorMessage: intake.error_message || undefined,
});
@@ -472,6 +497,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
item.parse_status,
item.order_extraction_status,
item.candidates?.length || 0,
item.layout_status,
))
.map((item) => ({
id: `restored_${item.intake_no}`,
@@ -486,6 +512,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
originalFilename: item.original_filename || item.intake_no,
fileSize: Number(item.file_size || 0),
parseSummary: (item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
...mapServerLayout(item),
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,
@@ -515,6 +542,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
);
patchAttachment(target.id, {
parseStatus: mapServerParseStatus(intake.parse_status),
...mapServerLayout(intake),
...mapServerDuplicate(intake),
});
};
+9 -18
View File
@@ -32,31 +32,28 @@ export interface ShippingOrderExtractionState {
created_with_missing_fields_count: number;
batch_no?: string | null;
terminal: boolean;
/** 当前服务端阶段,仅用于状态卡展示。 */
current_stage_code?: string | null;
health?: string;
/** 服务端健康提示,不包含诊断详情。 */
health?: 'normal' | 'slow' | 'idle' | string;
last_activity_at?: string | null;
started_at?: string | null;
}
/** 订单抽取 Run 持久化的业务审核快照,不保存原始文档或服务商诊断信息。 */
/** 订单识别终态卡保存的候选审核快照,仅含用户可见业务字段。 */
export interface ShippingOrderExtractionReviewAttachment {
intakeNo: string;
originalFilename: string;
candidates: ShippingNoticeCandidate[];
}
/**
* 货代消息在实时 SSE 与历史回放之间共享的最小恢复载荷。
* 核心逻辑:`open_existing` 终态至少要保留 `task_no`;若已知所属批次或已拿到工作台快照,
* 则继续补齐 `batch_no`、`shipping_ui_state`、`shipping_batch_ui_state`,供聊天页恢复右侧工作台。
*/
export interface ShippingMessageRecoveryPayload extends Record<string, unknown> {
/** 历史消息中用于恢复发货工作台焦点的最小持久化载荷。 */
export interface ShippingMessageRecoveryPayload {
task_no?: string;
batch_no?: string | null;
batch_no?: string;
shipping_ui_state?: ShippingTaskUiState;
shipping_batch_ui_state?: ShippingBatchUiState;
shipping_order_extraction_state?: ShippingOrderExtractionState;
shipping_order_extraction_review?: ShippingOrderExtractionReviewAttachment[];
[key: string]: unknown;
}
export type ChatMessageAttachmentType = 'image' | 'document' | 'audio' | 'video' | 'custom';
@@ -65,10 +62,8 @@ export type ChatMessageAttachmentSource = 'local' | 'remote' | 'shipping_notice'
/**
* 已发送消息中的附件快照。
* 约束:只保留可展示、可 JSON 序列化的信息,不得包含 File、完整 URL、上传凭据或内部资产编号。
readonly id: string;
*/
export interface ChatMessageAttachment {
readonly id: string;
readonly name: string;
readonly size?: number;
readonly extension?: string;
@@ -81,16 +76,12 @@ export interface ChatMessage {
content: string;
/** 用户提交时固化的附件展示快照;助手消息不使用此字段。 */
attachments?: ChatMessageAttachment[];
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
/** 文件检核等异步任务批次 ID(按轮问答绑定) */
run_id?: number;
/**
* 结构化回放载荷。
* 约束:货代消息需兼容 `ShippingMessageRecoveryPayload`,保证历史刷新后仍可恢复任务锚点与批次工作台。
*/
payload?: unknown;
local_id?: string;
local_only?: boolean;
@@ -206,6 +206,10 @@ export interface ShippingFieldEvidenceItem {
reservation_id?: string | null;
quote?: string | null;
document_id?: number | null;
page_no?: number | null;
table_id?: string | null;
cell_id?: string | null;
observation_id?: number | null;
[key: string]: unknown;
}
@@ -554,6 +558,21 @@ export interface ShippingNoticeIntakeResponse {
candidates?: ShippingNoticeCandidateResponse[];
document_count?: number;
candidate_count?: number;
layout_status?: ShippingNoticeLayoutStatus;
layout_summary?: ShippingNoticeLayoutSummary;
}
export type ShippingNoticeLayoutStatus = 'processing' | 'completed' | 'not_required';
export interface ShippingNoticeLayoutSummary {
status: ShippingNoticeLayoutStatus;
total: number;
queued: number;
running: number;
ready: number;
needs_review: number;
failed: number;
unsupported: number;
}
export interface ShippingInventoryVerificationLine {
@@ -158,6 +158,17 @@ export type ShippingNoticePendingAttachment = {
duplicate?: ShippingDuplicateResult;
duplicateResolution?: ShippingDuplicateResolution;
candidates?: ShippingNoticeCandidate[];
/** 文档版面任务汇总;processing 时不得创建订单识别 Run。 */
layoutStatus?: 'processing' | 'completed' | 'not_required';
layoutSummary?: {
total: number;
queued: number;
running: number;
ready: number;
needs_review: number;
failed: number;
unsupported: number;
};
};
/** 普通本地附件:选择后等待发送,实际上传由发送流程触发。 */
@@ -70,8 +70,9 @@ describe('attachment card utils', () => {
});
it('preserves shipping parsing, failure and duplicate attention states', () => {
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'parsing' }))).toEqual({
state: 'processing', labelKey: 'chat.attachment.parsing',
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'parsing' })).state).toBe('processing');
expect(getAttachmentCardStatus(shippingAttachment({ layoutStatus: 'processing' }))).toEqual({
state: 'processing', labelKey: 'chat.attachment.layoutProcessing',
});
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'failed' }))).toEqual({
state: 'failed', labelKey: 'chat.attachment.parseFailed',
@@ -85,9 +86,7 @@ describe('attachment card utils', () => {
allowedActions: [],
},
})).state).toBe('attention');
expect(getAttachmentCardStatus(shippingAttachment())).toEqual({
state: 'ready', labelKey: 'chat.attachment.parseSucceeded',
});
expect(getAttachmentCardStatus(shippingAttachment()).state).toBe('ready');
});
it('shows the order extraction lifecycle separately from attachment parsing', () => {
@@ -128,7 +127,6 @@ describe('attachment card utils', () => {
expect(snapshots).toEqual([
{
id: 'local-1',
name: 'purchase-order.pdf',
size: 3,
extension: 'pdf',
@@ -136,14 +134,12 @@ describe('attachment card utils', () => {
source: 'local',
},
{
id: 'remote-secret',
name: 'report.xlsx',
extension: 'xlsx',
type: 'document',
source: 'remote',
},
{
id: 'shipping-1',
name: 'notice.EML',
size: 229_877,
extension: 'eml',
@@ -172,7 +168,6 @@ describe('attachment card utils', () => {
}]);
expect(snapshots).toEqual([{
id: 'remote-root',
name: 'remote-file',
type: 'custom',
source: 'remote',
@@ -184,9 +179,6 @@ describe('attachment card utils', () => {
shippingAttachment({ originalFilename: 'C:\\mail\\notice\u0000.eml' }),
]);
expect(snapshots[0]).toMatchObject({
id: 'shipping-1',
name: 'notice.eml',
});
expect(snapshots[0]?.name).toBe('notice.eml');
});
});
@@ -67,9 +67,12 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme
if (attachment.uploadStatus === 'uploading') return { state: 'uploading', labelKey: 'chat.attachment.uploading' };
if (attachment.uploadStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.uploadFailed' };
if (attachment.parseStatus === 'queued' || attachment.parseStatus === 'parsing') {
return { state: 'processing', labelKey: 'chat.attachment.parsing' };
return { state: 'processing', labelKey: 'chat.attachment.processing' };
}
if (attachment.parseStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.parseFailed' };
if (attachment.layoutStatus === 'processing') {
return { state: 'processing', labelKey: 'chat.attachment.layoutProcessing' };
}
const extractionStatus = String(attachment.orderExtractionStatus || '').trim().toLowerCase();
if (extractionStatus === 'extracting') {
return { state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing' };
@@ -92,7 +95,7 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme
}
}
if (attachment.parseStatus === 'parsed' || attachment.parseStatus === 'consumed') {
return { state: 'ready', labelKey: 'chat.attachment.parseSucceeded' };
return { state: 'ready', labelKey: 'chat.attachment.ready' };
}
return { state: 'pending', labelKey: 'chat.attachment.pending' };
}
@@ -129,15 +132,6 @@ function getSnapshotAttachmentName(attachment: PendingAttachment): string {
return basename.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 255) || 'attachment';
}
/** 生成可持久化的附件快照 ID,避免引入 File 或内部资产指针。 */
function getSnapshotAttachmentId(attachment: PendingAttachment, index: number): string {
const candidate = String(attachment.id || '')
.replace(/[\u0000-\u001f\u007f]/g, '')
.trim()
.slice(0, 128);
return candidate || `attachment-${index + 1}`;
}
/** 从安全文件名提取小写扩展名;无明确扩展名时不制造类型后缀。 */
function getSnapshotAttachmentExtension(name: string): string | undefined {
const dotIndex = name.lastIndexOf('.');
@@ -155,7 +149,7 @@ function getSnapshotAttachmentExtension(name: string): string | undefined {
export function createChatMessageAttachmentSnapshots(
attachments: readonly PendingAttachment[],
): ChatMessageAttachment[] {
return attachments.map((attachment, index) => {
return attachments.map((attachment) => {
const name = getSnapshotAttachmentName(attachment);
const size = attachment.kind === 'local'
? attachment.file.size
@@ -164,7 +158,6 @@ export function createChatMessageAttachmentSnapshots(
: undefined;
const extension = getSnapshotAttachmentExtension(name);
return {
id: getSnapshotAttachmentId(attachment, index),
name,
type: attachment.type,
source: attachment.kind,