feat(shipping): 实现订单批处理聊天聚合展示与优化后端逻辑

This commit is contained in:
hugo committed 2026-08-13 17:40:43 +08:00
1 parent 11cef575b4
commit 523b791c92
38 files changed
+2868 -414

No files matched your search

@@ -371,9 +371,9 @@ export const reparseWorkspaceShippingOrderExtractionRun = (
);
/** 获取当前订单抽取 Run 的按 PDF 归并详情。 */
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) =>
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string, uploadBatchId?: string | null) =>
requestJson<ShippingOrderExtractionDocumentsResponse>(
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents`,
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents${uploadBatchId ? `?upload_batch_id=${encodeURIComponent(uploadBatchId)}` : ''}`,
);
/** 获取 Run 下每份 PDF 的建单前复核摘要,服务端负责 owner 隔离。 */
@@ -935,9 +935,9 @@ export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Pr
}
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string, uploadBatchId?: string | null) =>
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events`,
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events${uploadBatchId ? `?upload_batch_id=${encodeURIComponent(uploadBatchId)}` : ''}`,
);
/** 在终态状态卡已投影到当前会话后确认已查看,避免只因预加载会话列表而消除提醒。 */
@@ -77,32 +77,45 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
);
/** 同一 Run 只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
/** 同一 Run 或同一次上传批次只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
const current = items[index];
if (!current?.shipping_order_extraction_state) return false;
const payload = current.payload && typeof current.payload === 'object'
? current.payload as Record<string, unknown>
: {};
const identity = String(
const runIdentity = String(
payload.order_extraction_run_no
|| payload.formId
|| current.shipping_order_extraction_state.runNo
|| '',
).trim();
if (!identity) return false;
const batchIdentity = String(
payload.shipping_order_extraction_upload_batch_id
|| current.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
if (!runIdentity && !batchIdentity) return false;
return items.slice(index + 1).some((candidate) => {
if (!candidate?.shipping_order_extraction_state) return false;
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
? candidate.payload as Record<string, unknown>
: {};
const candidateIdentity = String(
const candidateRunIdentity = String(
candidatePayload.order_extraction_run_no
|| candidatePayload.formId
|| candidate.shipping_order_extraction_state.runNo
|| '',
).trim();
return candidateIdentity === identity;
const candidateBatchIdentity = String(
candidatePayload.shipping_order_extraction_upload_batch_id
|| candidate.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
return Boolean(
(batchIdentity && candidateBatchIdentity === batchIdentity)
|| (runIdentity && candidateRunIdentity === runIdentity),
);
});
};
@@ -125,9 +125,9 @@ describe('ShippingConversationProcessingCard', () => {
await flushPromises();
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-needs_action"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
expect(wrapper.text()).toContain('需要你处理 · 1 个任务');
expect(wrapper.text()).toContain('异常 / 失败 · 1 个任务');
expect(wrapper.text()).toContain('系统处理中 · 1 个任务');
expect(wrapper.text()).toContain('刚刚创建');
@@ -441,20 +441,36 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.findAll('[data-testid="shipping-conversation-processing-card"]')).toHaveLength(1);
});
it('renders pending order_intake work items above task groups', async () => {
it('renders an EML order_intake in the unified failed group rather than the removed intake side path', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: null,
projection: {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
needs_action: [{
user_task_no: 'SNI-1',
group: 'needs_action',
userGroup: 'failed',
status_label: 'failed',
title: 'mail.eml',
file_count: 1,
run_no: null,
can_append: false,
}],
processing: [],
completed: [],
history: [],
},
workItems: [{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
sourceType: 'eml',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'failed',
userGroup: 'failed',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-04T12:00:00Z',
@@ -484,16 +500,10 @@ describe('ShippingConversationProcessingCard', () => {
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-intake-SNI-1"]').exists()).toBe(true);
expect(wrapper.text()).toContain('po.pdf');
expect(wrapper.find('[data-testid="shipping-processing-intake-recovery"]').exists()).toBe(true);
expect(wrapper.text()).toContain('SHIPPING_NOTICE.INTAKE_PARSE_FAILED');
await wrapper.find('[data-testid="shipping-processing-intake-action-retry_parse"]').trigger('click');
expect(wrapper.emitted('intakeAction')?.[0]?.[0]).toMatchObject({
action: 'retry_parse',
item: { workItemNo: 'SNI-1' },
});
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-SNI-1"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(false);
expect(wrapper.text()).toContain('重试解析');
});
it('keeps a human Gate action visible before and after selecting its task', async () => {
@@ -31,7 +31,6 @@ import {
import {
resolveShippingProcessingMessage,
resolveShippingProcessingStatusLabel,
shippingProcessingSourceTypeKey,
shippingProcessingStageKey,
} from '@/features/chat/shipping/shippingProcessingLabels';
import { resolveConversationTaskActionPresentation } from '@/features/shipping-progress/actionPresentation';
@@ -71,22 +70,21 @@ const activeProjection = computed((): ConversationProcessingProjection | null =>
props.projection || null
));
/** 尚未建 OT、仍应展示在「待处理材料」的 Intake 工作项。 */
const pendingIntakeItems = computed((): ShippingProcessingProjection[] => {
const items = Array.isArray(props.workItems) ? props.workItems : [];
return items.filter((item) => {
if (item.workItemType !== 'order_intake') return false;
return !['completed', 'cancelled'].includes(String(item.status || ''));
});
});
const hasContent = computed(() => Boolean(
activeProjection.value
|| pendingIntakeItems.value.length,
activeProjection.value,
));
const completedTasks = computed(() => activeProjection.value?.completed || []);
const historyTasks = computed(() => activeProjection.value?.history || []);
const statusGroups = computed(() => activeProjection.value?.status_groups || null);
const completedTasks = computed(() => statusGroups.value?.completed || activeProjection.value?.completed || []);
const historyTasks = computed(() => statusGroups.value
? [...statusGroups.value.cancelled, ...statusGroups.value.archived]
: (activeProjection.value?.history || []));
/** EML 卡必须由后端 userGroup 分入独立用户区;旧任务保留 needs_action 兼容归属。 */
const failedTasks = computed(() => statusGroups.value?.failed
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'failed' || !task.userGroup));
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'waiting_human'));
const processingTasks = computed(() => statusGroups.value?.processing || activeProjection.value?.processing || []);
/** history 中非取消 →「历史版本」。 */
const historyVersionTasks = computed(() => historyTasks.value.filter(
@@ -123,7 +121,7 @@ function projectionForTask(task: ConversationProcessingUserTask): ShippingProces
if (!taskNo) return null;
const items = Array.isArray(props.workItems) ? props.workItems : [];
return items.find((item) => (
item.workItemType === 'order_task'
(item.workItemType === 'order_task' || item.workItemType === 'order_intake')
&& String(item.workItemNo || '').trim() === taskNo
)) || null;
}
@@ -232,6 +230,38 @@ function statusLabel(task: ConversationProcessingUserTask): string {
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
}
/** 展示统一投影的真实履约阶段;识别候选不再冒充最终完成。 */
function stageLabel(task: ConversationProcessingUserTask): string {
const projection = projectionForTask(task);
if (!projection) return '';
return intakeStageLabel(projection);
}
/** 展示后端统一投影的阻断/失败原因,不从状态码自行猜测。 */
function taskReasonLabel(task: ConversationProcessingUserTask): string {
const code = String(task.blockingReason?.code || task.aggregateSummary?.reasonCodes[0] || '').trim();
if (!code) return '';
const messages: Record<string, string> = {
'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED': '识别结果需要人工确认,请进入订单处理继续。',
'generic_extraction_disabled': '当前文件暂不支持自动解析,请人工处理或更换文件。',
'SHIPPING_NOTICE.INTAKE_PARSE_FAILED': '邮件或附件解析失败,请检查文件后重试。',
'upload_rpa_failed': '上传货代系统失败,请稍后重试。',
};
return messages[code] || '文件处理需要人工确认,请进入订单处理查看。';
}
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
function aggregateStatusLabel(task: ConversationProcessingUserTask): string {
const summary = task.aggregateSummary;
if (!summary) return '';
const parts: string[] = [];
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
return parts.join(' · ');
}
/**
* 是否高亮 needs_action 任务。
*/
@@ -391,25 +421,6 @@ function toggleHistorySection() {
historySectionExpanded.value = !historySectionExpanded.value;
}
/**
* Intake 材料标题:文件名 / 邮件主题 / Intake 编号。
*/
function intakeTitle(item: ShippingProcessingProjection): string {
return String(
item.sourceSummary?.filename
|| item.sourceSummary?.emailSubject
|| item.workItemNo
|| '',
).trim() || item.workItemNo;
}
/**
* Intake 状态文案。
*/
function intakeStatusLabel(item: ShippingProcessingProjection): string {
return resolveShippingProcessingStatusLabel(item.status, te, t);
}
/**
* Intake 阶段文案。
*/
@@ -417,68 +428,6 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingStageKey(item.stage);
return te(key) ? t(key) : String(item.stage || '');
}
/**
* Intake 来源类型文案。
*/
function intakeSourceLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingSourceTypeKey(item.sourceType);
return te(key) ? t(key) : String(item.sourceType || '');
}
/**
* Intake / OT 门禁与失败恢复元信息(Gate / Attempt / 资产状态)。
*/
function intakeRecoveryMeta(item: ShippingProcessingProjection): string[] {
const parts: string[] = [];
const gate = item.currentGate;
const reason = String(
gate?.blockingReasonCode
|| item.sourceSummary?.failureReasonCode
|| '',
).trim();
if (reason) {
parts.push(t('chat.shippingProcessing.failureReason', { code: reason }));
}
const attempt = gate?.attemptNo ?? item.sourceSummary?.parseAttemptCount;
if (attempt != null && Number(attempt) > 0) {
parts.push(t('chat.shippingProcessing.parseAttempt', { count: Number(attempt) }));
}
const assetStatus = String(item.sourceSummary?.assetStatus || '').trim();
if (assetStatus) {
const key = `chat.shippingProcessing.assetStatus.${assetStatus}`;
parts.push(te(key) ? t(key) : t('chat.shippingProcessing.assetStatusLabel', { status: assetStatus }));
}
if (gate?.gateCode) {
parts.push(t('chat.shippingProcessing.gateCode', { code: gate.gateCode }));
}
return parts;
}
/**
* Intake 可见动作(仅展示 retry_parse)。
*/
function visibleIntakeActions(item: ShippingProcessingProjection): string[] {
const actions = Array.isArray(item.availableActions) ? item.availableActions : [];
return actions.filter((code) => code === 'retry_parse');
}
/**
* Intake 动作文案。
*/
function intakeActionLabel(action: string): string {
if (action === 'retry_parse') return t('chat.shippingProcessing.retryFromFailure');
return action;
}
/**
* 触发 Intake 级动作。
*/
function onIntakeAction(item: ShippingProcessingProjection, action: string) {
const code = String(action || '').trim();
if (!code) return;
emit('intakeAction', { item, action: code });
}
</script>
<template>
@@ -488,70 +437,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
data-testid="shipping-conversation-processing-card"
>
<section
v-if="pendingIntakeItems.length"
data-testid="shipping-processing-group-order-intake"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300">
{{ t('chat.shippingProcessing.pendingMaterials') }}
· {{ pendingIntakeItems.length }}
</div>
<div class="space-y-2">
<article
v-for="item in pendingIntakeItems"
:key="item.workItemNo"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:data-testid="`shipping-processing-intake-${item.workItemNo}`"
:data-source-type="item.sourceType"
:data-status="item.status"
>
<div class="text-sm font-semibold text-primary">
{{ intakeTitle(item) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span>{{ intakeSourceLabel(item) }}</span>
<span>{{ intakeStatusLabel(item) }}</span>
<span v-if="intakeStageLabel(item)">{{ intakeStageLabel(item) }}</span>
</div>
<div
v-if="intakeRecoveryMeta(item).length"
class="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-rose-700 dark:text-rose-300"
data-testid="shipping-processing-intake-recovery"
>
<span
v-for="(meta, idx) in intakeRecoveryMeta(item)"
:key="`${item.workItemNo}-meta-${idx}`"
>{{ meta }}</span>
</div>
<div
v-if="visibleIntakeActions(item).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-intake-actions"
>
<button
v-for="action in visibleIntakeActions(item)"
:key="`${item.workItemNo}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-intake-action-${action}`"
@click="onIntakeAction(item, action)"
>
{{ intakeActionLabel(action) }}
</button>
</div>
</article>
</div>
</section>
<section
v-if="activeProjection?.needs_action.length"
data-testid="shipping-processing-group-needs_action"
v-if="failedTasks.length"
data-testid="shipping-processing-group-failed"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: activeProjection.needs_action.length }) }}
{{ t('chat.shippingProcessing.groupFailed', { count: failedTasks.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in activeProjection.needs_action"
v-for="task in failedTasks"
:key="task.user_task_no"
class="rounded-lg border px-2.5 py-2 transition"
:class="[
@@ -574,6 +468,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
</div>
<div
v-if="primaryFileLabel(task)"
@@ -582,6 +477,12 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
>
{{ primaryFileLabel(task) }}
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
{{ taskReasonLabel(task) }}
</div>
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
{{ aggregateStatusLabel(task) }}
</div>
<div
v-if="task.recent_append_count"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
@@ -630,15 +531,52 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
</section>
<section
v-if="activeProjection?.processing.length"
data-testid="shipping-processing-group-processing"
v-if="waitingHumanTasks.length"
data-testid="shipping-processing-group-waiting_human"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: activeProjection.processing.length }) }}
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ t('chat.shippingProcessing.groupWaitingHuman', { count: waitingHumanTasks.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in activeProjection.processing"
v-for="task in waitingHumanTasks"
:key="task.user_task_no"
class="rounded-lg border border-amber-400 bg-amber-50/80 px-2.5 py-2 transition dark:border-amber-700 dark:bg-amber-950/30"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button type="button" class="w-full text-left" @click="onSelectTask(task)">
<div class="text-sm font-semibold text-primary">{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
</button>
<div v-if="currentNeedLabel(task)" class="mt-1 text-[11px] text-secondary">{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}</div>
<SidebarProgressInline
v-if="projectionForTask(task)"
class="mt-1.5 border-t border-current/10 pt-1.5"
:projection="projectionForTask(task)!"
:compact="false"
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
/>
</article>
</div>
</section>
<section
v-if="processingTasks.length"
data-testid="shipping-processing-group-processing"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: processingTasks.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in processingTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:class="focusedTaskNo === task.user_task_no
@@ -666,6 +604,9 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
>
{{ primaryFileLabel(task) }}
</div>
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
{{ aggregateStatusLabel(task) }}
</div>
<div
v-if="task.recent_append_count"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
@@ -805,6 +746,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
</div>
<div
v-if="primaryFileLabel(task)"
@@ -813,6 +755,9 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
>
{{ primaryFileLabel(task) }}
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
{{ taskReasonLabel(task) }}
</div>
<button
v-if="recordViewDetailsItem(task)"
type="button"
@@ -5,11 +5,13 @@
* 逻辑:断言不再渲染进度列表/刷新取消/完整 handling 卡片;失败重试与需处理继续处理互斥。
*/
import { mount } from '@vue/test-utils';
import { ref } from 'vue';
import { describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
import type { ShippingOrderExtractionState } from '../../types/chat.types';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
const i18n = createI18n({
legacy: false,
@@ -51,6 +53,288 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
});
describe('ShippingOrderExtractionCard', () => {
it('uses unified EML aggregation and keeps candidate creation out of completed', async () => {
const aggregate = {
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1',
shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1',
status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'forwarder.eml', documentCount: 3, parsedDocumentCount: 3, candidateCount: 2, customerName: null, poNumber: null }, childOrderTasks: [],
userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' },
aggregateSummary: { intakeNo: 'SNI-1', total: 3, completed: 1, processing: 1, needsAction: 0, failed: 1, stages: ['completed', 'candidate_creating'], reasonCodes: ['upload_rpa_failed'] },
aggregateChildren: [
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1', shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'completed', stage: 'completed', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'done.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null }, childOrderTasks: [], userStatus: 'completed', userStage: 'completed', facts: { uploadState: 'succeeded' } },
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: 'OT-1', shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'candidate.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null }, childOrderTasks: [], userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' } },
],
} as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-EML' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([aggregate]) } } },
});
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('已上传完成 1 · 处理中 1 · 异常 1');
expect(wrapper.text()).not.toContain('已生成候选 3 个文件');
await wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"] button').trigger('click');
expect(wrapper.text()).toContain('candidate.pdf');
expect(wrapper.text()).toContain('处理中 1');
});
it('keeps its matched EML card when the side-panel poll temporarily omits the intake', async () => {
const workItems = ref<any[]>([{
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-STABLE', sourceType: 'eml', rootOrderTaskNo: 'OT-STABLE',
shippingNoticeNo: null, runNo: 'SNER-STABLE', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'stable.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
childOrderTasks: [], userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' },
aggregateSummary: { intakeNo: 'SNI-STABLE', total: 2, completed: 0, processing: 2, needsAction: 0, failed: 0, stages: ['candidate_creating'], reasonCodes: [] },
aggregateChildren: [],
}]);
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-STABLE' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: workItems } } },
});
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
// 关键断言:右侧轮询暂时省略本 Intake 时,中间消息卡仍保留其自身的 EML 形态。
workItems.value = [];
await wrapper.vm.$nextTick();
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
});
it('expands an EML inside its status group and shows every child attachment state', async () => {
const child = {
workItemType: 'order_task', workItemNo: 'OT-CHILD-1', sourceType: 'eml', rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null, runNo: 'SNER-DETAIL', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-DETAIL',
status: 'failed', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'failed.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null },
childOrderTasks: [], userStatus: 'failed', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
blockingReason: { code: 'PARSE_FAILED' },
} as any;
const task = { user_task_no: 'INTAKE:SNI-DETAIL', title: 'mail.eml', file_count: 1, userGroup: 'failed', group: 'needs_action', aggregateChildren: [child], aggregateSummary: { intakeNo: 'SNI-DETAIL', total: 1, completed: 0, processing: 0, needsAction: 0, failed: 1, stages: ['document_parsing'], reasonCodes: ['PARSE_FAILED'] } } as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-DETAIL' },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({ status_groups: { failed: [task], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [] } }),
processingWorkItems: ref([]),
},
},
},
});
await wrapper.get('[data-testid="shipping-order-extraction-eml-failed-INTAKE:SNI-DETAIL"] button').trigger('click');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('failed.pdf');
expect(wrapper.text()).toContain('异常 1');
expect(wrapper.text()).toContain('文件处理需要人工确认');
expect(wrapper.text()).not.toContain('PARSE_FAILED');
});
it('falls back to the matched work item children when the status task only has a summary', async () => {
const child = {
workItemType: 'order_task', workItemNo: 'OT-FALLBACK-1', sourceType: 'eml', rootOrderTaskNo: 'OT-FALLBACK',
shippingNoticeNo: null, runNo: 'SNER-FALLBACK', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-FALLBACK',
status: 'processing', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'inside.eml.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
childOrderTasks: [], userStatus: 'running', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
} as any;
const task = { user_task_no: 'INTAKE:SNI-FALLBACK', title: 'inside.eml', file_count: 1, userGroup: 'processing', group: 'processing', aggregateChildren: [], aggregateSummary: { intakeNo: 'SNI-FALLBACK', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: ['document_parsing'], reasonCodes: [] } } as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-FALLBACK' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }),
processingWorkItems: ref([{ workItemType: 'order_intake', workItemNo: 'INTAKE:SNI-FALLBACK', sourceType: 'eml', intakeNo: 'SNI-FALLBACK', aggregateChildren: [child] } as any]),
} } },
});
await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-FALLBACK"] button').trigger('click');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('inside.eml.pdf');
});
it('counts unique EML attachment children instead of task rows', async () => {
const childA = { workItemType: 'order_task', workItemNo: 'OT-A', sourceType: 'eml', intakeNo: 'SNI-COUNT', sourceSummary: { filename: 'a.pdf', documentId: 101, documentCount: 1 }, status: 'processing', stage: 'document_parsing', userStatus: 'running', facts: { uploadState: 'not_created' } } as any;
const childB = { ...childA, workItemNo: 'OT-B', sourceSummary: { filename: 'b.pdf', documentId: 102, documentCount: 1 } } as any;
const task = { user_task_no: 'INTAKE:SNI-COUNT', title: 'count.eml', file_count: 2, userGroup: 'processing', group: 'processing', aggregateChildren: [childA, childB], aggregateSummary: { intakeNo: 'SNI-COUNT', total: 2, completed: 0, processing: 2, needsAction: 0, failed: 0, stages: [], reasonCodes: [] } } as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-COUNT' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }), processingWorkItems: ref([]) } } },
});
expect(wrapper.text()).toContain('2 个文件');
});
it('renders every projected file when the batch has two documents', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
summary: {
totalDocuments: 2,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 0,
reviewRequiredDocuments: 2,
failedDocuments: 0,
candidateCount: 0,
},
documents: [
{ unitId: 1, documentId: 11, fileName: '4518838154.pdf', status: 'review_required' },
{ unitId: 2, documentId: 12, fileName: '4518838152.pdf', status: 'review_required' },
],
availableActions: ['enter_manual_review'],
healthTips: [],
}),
runNo: 'SNER-2',
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('4518838154.pdf');
expect(wrapper.text()).toContain('4518838152.pdf');
});
it('groups completed attachments under their EML intake instead of mixing unrelated files', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
documents: [
{ unitId: 1, documentId: 11, intakeId: 7, documentType: 'email_body', fileName: 'Forwarder_A.eml', status: 'processing' },
{ unitId: 2, documentId: 12, intakeId: 7, documentType: 'attachment', fileName: 'Packing_List.pdf', status: 'candidate_ready' },
{ unitId: 3, documentId: 13, intakeId: 8, documentType: 'attachment', fileName: 'Customs_Form.pdf', status: 'processing' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
await wrapper.find('button').trigger('click');
const text = wrapper.text();
expect(text.indexOf('Forwarder_A.eml')).toBeLessThan(text.indexOf('Packing_List.pdf'));
expect(text).toContain('Customs_Form.pdf');
expect(text.match(/Packing_List\.pdf/g)?.length).toBe(1);
});
it('groups by email_body document type and renders parse failure as failed', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
status: 'failed',
summary: {
totalDocuments: 2,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 0,
reviewRequiredDocuments: 0,
failedDocuments: 1,
candidateCount: 0,
},
documents: [
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder-message', status: 'failed', reasonCode: 'intake_parse_failed' },
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'po.pdf', status: 'failed', reasonCode: 'intake_parse_failed' },
],
healthTips: [],
currentActivity: null,
}),
},
global: { plugins: [i18n] },
});
const text = wrapper.text();
expect(text).toContain('forwarder-message');
expect(text).toContain('po.pdf');
expect(text).toContain('异常');
expect(wrapper.findAll('.animate-spin').length).toBe(0);
});
it('does not render completed files again as standalone cards', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
summary: {
totalDocuments: 2,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 2,
reviewRequiredDocuments: 0,
failedDocuments: 0,
candidateCount: 2,
},
documents: [
{ unitId: 1, documentId: 11, fileName: '4518838152.pdf', status: 'candidate_ready' },
{ unitId: 2, documentId: 12, fileName: '4518838154.pdf', status: 'candidate_ready' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
const accordion = wrapper.find('button');
await accordion.trigger('click');
expect(wrapper.text().match(/4518838152\.pdf/g)?.length).toBe(1);
});
it('aggregates a fully completed EML intake only inside the completed section', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
summary: {
totalDocuments: 2,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 2,
reviewRequiredDocuments: 0,
failedDocuments: 0,
candidateCount: 2,
},
documents: [
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'candidate_ready' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).not.toContain('forwarder.eml');
expect(wrapper.text()).not.toContain('packing.pdf');
await wrapper.find('button').trigger('click');
expect(wrapper.text()).toContain('forwarder.eml');
expect(wrapper.text()).toContain('packing.pdf');
expect(wrapper.text().match(/forwarder\.eml/g)?.length).toBe(1);
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
expect(wrapper.text()).toContain('已提取');
});
it('keeps a partially completed EML intake outside the completed section', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
documents: [
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'candidate_ready' },
{ unitId: 9, documentId: 9, intakeId: 7, documentType: 'attachment', fileName: 'invoice.pdf', status: 'processing' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
await wrapper.find('button').trigger('click');
expect(wrapper.text()).toContain('forwarder.eml');
expect(wrapper.text()).toContain('invoice.pdf');
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
});
it('shows an EML as exception when a child failed even if the parent status is processing', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
documents: [
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'failed', reasonCode: 'intake_parse_failed' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('异常');
expect(wrapper.text()).not.toContain('解析附件中');
});
it('renders summary title, file count, system processing and no progress/refresh/cancel', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-1' },
@@ -5,12 +5,13 @@
* 逻辑:对话区只做任务摘要;长进度/Gate/刷新取消由右侧栏承接;详情抽屉仅由次要「查看详情」打开。
*/
<script setup lang="ts">
import { computed, ref } from 'vue';
import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
import { AlertCircle, ArrowRight, CheckCircle2, ChevronDown, CircleX, FileText, LoaderCircle, Mail, RefreshCw, TriangleAlert } from 'lucide-vue-next';
import type {
ShippingOrderExtractionHandlingItemState,
ShippingOrderExtractionFileState,
ShippingOrderExtractionState,
} from '../../types/chat.types';
import type {
@@ -18,6 +19,8 @@ import type {
ShippingOrderExtractionProgressEvent,
} from '../../types/shipping.api.types';
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
import { shippingProcessingStageKey } from '../../shipping/shippingProcessingLabels';
import {
listWorkspaceShippingOrderExtractionDocuments,
listWorkspaceShippingOrderExtractionProgressEvents,
@@ -46,6 +49,211 @@ const emit = defineEmits<{
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const shippingWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
type ConversationStatusGroups = NonNullable<import('../../types/shipping.api.types').ConversationProcessingProjection['status_groups']>;
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => ((shippingWorkflow as { processing?: { value?: { status_groups?: ConversationStatusGroups | null } | null } } | null)?.processing?.value?.status_groups || null));
const hasConversationStatusGroups = computed(() => Boolean(conversationStatusGroups.value));
const statusGroupDefs = [
{ key: 'failed', label: 'chat.shippingProcessing.groupFailed' },
{ key: 'waiting_human', label: 'chat.shippingProcessing.groupWaitingHuman' },
{ key: 'processing', label: 'chat.shippingProcessing.groupProcessing' },
{ key: 'completed', label: 'chat.shippingProcessing.groupCompleted' },
{ key: 'cancelled', label: 'chat.shippingProcessing.groupCancelled' },
{ key: 'archived', label: 'chat.shippingProcessing.groupHistoryRecords' },
] as const;
const expandedStatusGroups = ref(new Set<string>(['failed', 'waiting_human', 'processing']));
const expandedEmlTasks = ref(new Set<string>());
function statusGroupTasks(key: typeof statusGroupDefs[number]['key']) {
return conversationStatusGroups.value?.[key] || [];
}
function statusGroupLabel(key: typeof statusGroupDefs[number]['key']) {
const count = statusGroupTasks(key).length;
return t(statusGroupDefs.find((item) => item.key === key)!.label, { count });
}
function toggleStatusGroup(key: string) {
const next = new Set(expandedStatusGroups.value);
if (next.has(key)) next.delete(key); else next.add(key);
expandedStatusGroups.value = next;
}
function toggleEmlTask(taskNo: string) {
const next = new Set(expandedEmlTasks.value);
if (next.has(taskNo)) next.delete(taskNo); else next.add(taskNo);
expandedEmlTasks.value = next;
}
function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]; user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
if (task.aggregateChildren?.length) return task.aggregateChildren;
const projection = statusTaskProjection(task);
if (!projection) return [];
if (projection?.aggregateChildren?.length) return projection.aggregateChildren;
const projectionChildren = (projection?.childOrderTasks || []).map((child) => ({
...projection,
workItemNo: child.orderTaskNo,
status: child.status,
stage: child.stage,
userStatus: child.status === 'completed' ? 'completed' : child.status === 'failed' ? 'failed' : 'running',
userStage: child.stage,
sourceSummary: {
...projection.sourceSummary,
filename: child.orderTaskNo,
documentCount: 1,
},
} as ShippingProcessingProjection));
if (projectionChildren.length) return projectionChildren;
// 系统处理中 work_item 可能只有 EML 摘要;附件真实状态仍由当前 Run 文档列表承载。
const emailName = String(projection.sourceSummary?.filename || task.aggregateSummary?.intakeNo || '').trim().toLowerCase();
const emailRow = emailRows.value.find((row) => (
String(row.fileName || '').trim().toLowerCase() === emailName
|| String(row.intakeId || '').trim() === String(task.aggregateSummary?.intakeNo || '').trim()
));
if (!emailRow) return [];
return childRows(emailRow).map((row) => ({
workItemType: 'order_task',
workItemNo: `DOCUMENT:${row.documentId || row.unitId}`,
sourceType: 'eml',
rootOrderTaskNo: null,
shippingNoticeNo: null,
runNo: props.runNo || props.state.runNo || null,
caseNo: null,
conversationId: null,
submissionNo: '',
intakeNo: String(emailRow.intakeId || task.aggregateSummary?.intakeNo || ''),
status: row.status === 'failed' ? 'failed' : row.status === 'review_required' ? 'waiting_review' : row.status === 'candidate_ready' ? 'completed' : 'processing',
stage: String(row.userVisibleStage || row.status || 'processing'),
progressVersion: 0,
lastActivityAt: '',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: row.fileName,
documentId: row.documentId || null,
documentCount: 1,
parsedDocumentCount: row.status === 'failed' ? 0 : 1,
candidateCount: row.status === 'candidate_ready' ? 1 : 0,
customerName: null,
poNumber: null,
failureReasonCode: row.reasonCode || null,
},
childOrderTasks: [],
userStatus: row.status === 'failed' ? 'failed' : row.status === 'review_required' ? 'waiting_human' : row.status === 'candidate_ready' ? 'completed' : 'running',
userStage: row.userVisibleStage || row.status,
blockingReason: row.explainability?.message ? { code: row.reasonCode || 'DOCUMENT_PROCESSING_FAILED', details: { message: row.explainability.message } } : null,
retryable: false,
primaryAction: null,
facts: { uploadState: row.status === 'candidate_ready' ? 'succeeded' : 'not_created' },
userGroup: null,
} as ShippingProcessingProjection));
}
function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[]; file_count?: number | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
const children = taskChildren(task);
if (children.length) {
const ids = new Set(children.map((child) => String(child.sourceSummary?.documentId || child.workItemNo || '').trim()).filter(Boolean));
return ids.size || children.length;
}
const projection = statusTaskProjection(task);
const sourceCount = Number(projection?.sourceSummary?.documentCount || 0);
return sourceCount > 0 ? sourceCount : Math.max(0, Number(task.file_count || 0));
}
function childStatusLabel(child: ShippingProcessingProjection) {
const status = String(child.userStatus || child.status || '').toLowerCase();
if (status === 'completed' && child.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
}
function userReasonLabel(code?: string | null) {
const key = String(code || '').trim();
const messages: Record<string, string> = {
'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED': '识别结果需要人工确认,请进入订单处理继续。',
'generic_extraction_disabled': '当前文件暂不支持自动解析,请人工处理或更换文件。',
'SHIPPING_NOTICE.INTAKE_PARSE_FAILED': '邮件或附件解析失败,请检查文件后重试。',
'upload_rpa_failed': '上传货代系统失败,请稍后重试。',
};
return messages[key] || (key ? '文件处理需要人工确认,请进入订单处理查看。' : '');
}
function childStageLabel(child: ShippingProcessingProjection) {
const stage = String(child.userStage || child.stage || '').trim();
if (stage === 'review_required' || stage === 'waiting_review') return '等待人工复核';
if (stage === 'failed' || stage === 'parse_failed') return '处理失败';
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
}
function statusTaskProjection(task: { user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
const items = shippingWorkflow?.processingWorkItems.value || [];
const intakeNo = String(task.aggregateSummary?.intakeNo || '').trim();
if (intakeNo) {
const intakeMatch = items.find((item) => (
item.sourceType === 'eml'
&& String(item.intakeNo || '').trim() === intakeNo
));
if (intakeMatch) return intakeMatch;
}
return items.find((item) => (
(item.workItemType === 'order_task' || item.workItemType === 'order_intake')
&& String(item.workItemNo || '').trim() === String((task as any).user_task_no || '').trim()
)) || null;
}
function aggregateStatusLabelFromSummary(summary: NonNullable<import('../../types/shipping.api.types').ConversationProcessingUserTask['aggregateSummary']>) {
const parts: string[] = [];
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
return parts.join(' · ');
}
/**
* 当前 Run 对应的 EML Intake 聚合项。
*
* 右侧投影轮询是增量可见的:一次响应暂未带回该 Intake 不能让聊天消息卡
* 降级为旧 Run 卡。消息卡保留最后一次同 Run/用户任务命中的聚合快照,只有
* 同一绑定再次命中时才更新;右侧面板仍直接消费实时投影。
*/
const matchedEmlAggregate = computed(() => {
const runNo = String(props.runNo || props.state.runNo || '').trim();
const userTaskNo = String(props.state.userTaskNo || '').trim();
const items = shippingWorkflow?.processingWorkItems.value || [];
return items.find((item) => (
item.workItemType === 'order_task'
&& item.sourceType === 'eml'
&& Boolean(item.aggregateSummary)
&& (
String(item.runNo || '').trim() === runNo
|| (Boolean(userTaskNo) && String(item.rootOrderTaskNo || '').trim() === userTaskNo)
)
)) || null;
});
const lastMatchedEmlAggregate = ref<ShippingProcessingProjection | null>(null);
watch(matchedEmlAggregate, (item) => {
if (item) lastMatchedEmlAggregate.value = item;
}, { immediate: true });
const emlAggregate = computed(() => matchedEmlAggregate.value || lastMatchedEmlAggregate.value);
const emlAggregateChildren = computed(() => emlAggregate.value?.aggregateChildren || []);
const emlAggregateExpanded = ref(false);
function aggregateStageLabel(item: ShippingProcessingProjection): string {
const stage = String(item.userStage || item.stage || '').trim();
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
}
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
const status = String(item.userStatus || item.status || '').trim().toLowerCase();
if (status === 'completed' && item.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
}
function aggregateSummaryLabel(item: ShippingProcessingProjection): string {
const summary = item.aggregateSummary;
if (!summary) return '';
const parts: string[] = [];
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
return parts.join(' · ');
}
const detailsOpen = ref(false);
const detailsLoading = ref(false);
@@ -58,6 +266,62 @@ const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
const displaySummary = computed(() => props.state.summary);
const handlingItems = computed(() => props.state.handlingItems || []);
const fileRows = computed(() => props.state.documents || []);
const isEmailRow = (row: ShippingOrderExtractionFileState) => (
row.documentType === 'email_body' || row.fileName?.toLowerCase().endsWith('.eml')
);
const emailRows = computed(() => fileRows.value.filter(isEmailRow));
const isFailedParseRow = (row: ShippingOrderExtractionFileState) => (
row.status === 'failed'
|| row.reasonCode === 'intake_parse_failed'
|| row.userVisibleStage === 'parse_failed'
);
const childRows = (email: ShippingOrderExtractionFileState) => fileRows.value.filter((row) => (
row.unitId !== email.unitId
&& row.intakeId != null
&& row.intakeId === email.intakeId
&& !isEmailRow(row)
));
const candidateEmailGroups = computed(() => emailRows.value
.map((parent) => ({ parent, children: childRows(parent) }))
.filter((group) => group.children.length > 0 && group.children.every((child) => child.status === 'candidate_ready')));
const emailHasFailedChild = (email: ShippingOrderExtractionFileState) => childRows(email).some(isFailedParseRow);
const emailIsCompleted = (email: ShippingOrderExtractionFileState) => {
const children = childRows(email);
return children.length > 0 && children.every((child) => child.status === 'candidate_ready');
};
const candidateEmailUnitIds = computed(() => new Set(
candidateEmailGroups.value.flatMap((group) => [group.parent.unitId, ...group.children.map((child) => child.unitId)]),
));
const candidateStandaloneRows = computed(() => fileRows.value.filter((row) => (
!isEmailRow(row)
&& row.status === 'candidate_ready'
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
)));
const candidateFileCount = computed(() => (
candidateEmailGroups.value.reduce((count, group) => count + group.children.length, 0)
+ candidateStandaloneRows.value.length
));
const activeEmailRows = computed(() => emailRows.value.filter((row) => !candidateEmailUnitIds.value.has(row.unitId)));
const standaloneRows = computed(() => fileRows.value.filter((row) => (
!isEmailRow(row)
&& row.status !== 'candidate_ready'
&& !isFailedParseRow(row)
&& !candidateEmailUnitIds.value.has(row.unitId)
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
)));
const failedRows = computed(() => fileRows.value.filter((row) => (
isFailedParseRow(row)
&& !candidateEmailUnitIds.value.has(row.unitId)
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
)));
const processedCount = computed(() => emlAggregate.value?.aggregateSummary?.completed
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments));
const progressPercent = computed(() => {
const total = Math.max(0, props.state.summary.totalDocuments);
return total > 0 ? Math.min(100, Math.round((processedCount.value / total) * 100)) : 0;
});
const completedExpanded = ref(false);
/**
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
@@ -83,26 +347,20 @@ const isCandidateConfirmationNotice = computed(() => (
)
));
const toneClass = computed(() => {
if (isDuplicateOnlyNotice.value) {
return 'border-violet-200 bg-violet-50/80 text-violet-950 dark:border-violet-800 dark:bg-violet-950/35 dark:text-violet-100';
}
if (isCandidateConfirmationNotice.value) {
return 'border-teal-200 bg-teal-50/80 text-teal-950 dark:border-teal-800 dark:bg-teal-950/35 dark:text-teal-100';
}
switch (props.state.status) {
case 'completed':
return 'border-emerald-200 bg-emerald-50/80 text-emerald-950 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100';
case 'partially_completed':
case 'review_required':
return 'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100';
case 'failed':
case 'cancelled':
return 'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100';
default:
return 'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100';
}
});
function rowStatusLabel(row: ShippingOrderExtractionFileState): string {
if (row.status === 'candidate_ready') return t('chat.shippingProcessing.candidateReady');
if (isFailedParseRow(row)) return t('chat.shippingProcessing.batchException');
if (row.status === 'review_required') return t('chat.shippingProcessing.waitingReview');
const stageKey = `chat.shippingOrderExtractionUserStage.${String(row.userVisibleStage || '').trim()}`;
if (row.userVisibleStage && te(stageKey)) return t(stageKey);
return t('chat.shippingProcessing.batchProcessing');
}
function rowStatusClass(row: ShippingOrderExtractionFileState): string {
if (row.status === 'candidate_ready') return 'text-emerald-500';
if (isFailedParseRow(row)) return 'text-rose-500';
return 'text-blue-500';
}
/**
* 将处理事项类别映射为一句过程通知文案。
@@ -126,6 +384,13 @@ function handlingTitle(item: ShippingOrderExtractionHandlingItemState): string {
* 状态短句:排队/处理中仅「系统处理中」;其余用过程通知,不含文件阶段耗时。
*/
const statusNotice = computed(() => {
if (emlAggregate.value) {
const status = String(emlAggregate.value.userStatus || '').trim().toLowerCase();
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
if (status === 'failed' || status === 'retryable') return t('chat.shippingSessionSummary.processNoticeFailed');
if (status === 'waiting_human') return t('chat.shippingSessionSummary.processNoticeNeedsAction');
return t('chat.shippingProcessing.systemProcessing');
}
if (props.state.cancellation?.requested && !props.state.cancellation?.completedAt && !props.state.terminal) {
return t('chat.shippingOrderExtractionUserStage.cancellation_requested');
}
@@ -261,7 +526,7 @@ async function loadDetailsDocuments() {
detailsLoading.value = true;
detailsLoadFailed.value = false;
try {
const docsRes = await listWorkspaceShippingOrderExtractionDocuments(runNo).catch(() => null);
const docsRes = await listWorkspaceShippingOrderExtractionDocuments(runNo, props.state.uploadBatchId).catch(() => null);
if (docsRes) {
detailsDocuments.value = Array.isArray(docsRes.items) ? docsRes.items : [];
} else {
@@ -286,7 +551,7 @@ async function loadDetailsProgress() {
progressLoading.value = true;
progressLoadFailed.value = false;
try {
const eventsRes = await listWorkspaceShippingOrderExtractionProgressEvents(runNo).catch(() => null);
const eventsRes = await listWorkspaceShippingOrderExtractionProgressEvents(runNo, props.state.uploadBatchId).catch(() => null);
if (eventsRes) {
progressEvents.value = Array.isArray(eventsRes.items) ? eventsRes.items : [];
} else {
@@ -347,25 +612,126 @@ async function onPrimaryChatAction() {
<template>
<div
class="mb-3 rounded-lg border px-3.5 py-2.5"
:class="toneClass"
class="mb-3 overflow-hidden rounded-xl border border-slate-200 bg-white/90 text-slate-900 shadow-md backdrop-blur-sm dark:border-slate-700 dark:bg-slate-900/90 dark:text-slate-100"
data-testid="shipping-order-extraction-card"
>
<div class="flex items-start gap-3">
<LoaderCircle
v-if="state.status === 'queued' || state.status === 'processing'"
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
/>
<CircleCheck
v-else-if="state.status === 'completed' || isDuplicateOnlyNotice || isCandidateConfirmationNotice"
class="mt-0.5 h-4 w-4 shrink-0"
/>
<TriangleAlert
v-else-if="state.status === 'partially_completed' || state.status === 'review_required'"
class="mt-0.5 h-4 w-4 shrink-0"
/>
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
<div class="flex items-center justify-between gap-3">
<div class="flex items-center gap-2 text-lg font-semibold">
<LoaderCircle v-if="emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
<CheckCircle2 v-else-if="emlAggregate ? emlAggregate.userStatus === 'completed' && emlAggregate.facts?.uploadState === 'succeeded' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
<TriangleAlert v-else class="h-5 w-5 text-amber-500" />
<span>{{ t('chat.shippingProcessing.multiPdfTaskTitle') }}</span>
</div>
<span class="rounded-full bg-slate-200 px-3 py-1 text-xs font-medium text-slate-600 dark:bg-slate-700 dark:text-slate-200">
{{ t('chat.shippingProcessing.batchFilesTotal', { count: emlAggregate?.sourceSummary.documentCount ?? state.summary.totalDocuments }) }}
</span>
</div>
<p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.batchStatusTitle') }} · {{ statusNotice }}</p>
<div v-for="tip in healthTips" :key="tip.code" class="mt-1 text-sm font-medium text-amber-600">{{ t(`chat.shippingOrderExtractionHealthTip.${tip.code}`) }}</div>
<div v-if="handlingSummaryLine" class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ handlingSummaryLine }}</div>
<div class="mt-4 flex items-end justify-between">
<span class="text-lg font-medium text-blue-600">{{ progressPercent }}% {{ t('chat.shippingProcessing.batchComplete') }}</span>
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ emlAggregate?.sourceSummary.documentCount ?? state.summary.totalDocuments }} {{ t('chat.shippingProcessing.batchProcessed') }}</span>
</div>
<div class="mt-3 h-2 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700">
<div class="h-full rounded-full bg-blue-600 transition-all" :style="{ width: `${progressPercent}%` }" />
</div>
</div>
<div v-if="hasConversationStatusGroups" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
<template v-for="group in statusGroupDefs" :key="group.key">
<section v-if="statusGroupTasks(group.key).length" class="overflow-hidden rounded-lg border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
<button type="button" class="flex w-full items-center justify-between px-3 py-3 text-left" @click="toggleStatusGroup(group.key)">
<span class="text-sm font-semibold" :class="group.key === 'failed' ? 'text-rose-600' : group.key === 'waiting_human' ? 'text-amber-700' : group.key === 'completed' ? 'text-emerald-600' : 'text-slate-700 dark:text-slate-200'">{{ statusGroupLabel(group.key) }}</span>
<ChevronDown class="h-4 w-4 transition-transform" :class="expandedStatusGroups.has(group.key) ? 'rotate-180' : ''" />
</button>
<div v-if="expandedStatusGroups.has(group.key)" class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-700">
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="rounded-lg border border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-950/30" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
<div class="flex items-start gap-2">
<Mail class="mt-0.5 h-4 w-4 text-blue-600" />
<div class="min-w-0 flex-1">
<button type="button" class="flex w-full items-center justify-between gap-2 text-left" @click="toggleEmlTask(task.user_task_no)">
<span class="truncate text-sm font-medium">{{ statusTaskProjection(task)?.sourceSummary?.filename || task.title || task.user_task_no }}</span>
<ChevronDown class="h-4 w-4 shrink-0 transition-transform" :class="expandedEmlTasks.has(task.user_task_no) ? 'rotate-180' : ''" />
</button>
<div class="mt-1 text-xs text-slate-500">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
<div v-if="task.blockingReason?.code" class="mt-1 text-xs text-rose-600">{{ userReasonLabel(task.blockingReason.code) }}</div>
<div v-if="expandedEmlTasks.has(task.user_task_no)" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
<div v-for="child in taskChildren(task)" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
<div class="min-w-0">
<div class="truncate font-medium">{{ child.sourceSummary.filename || child.workItemNo }}</div>
<div class="text-[11px] text-slate-500">{{ childStageLabel(child) }}</div>
<div v-if="child.blockingReason?.code || child.sourceSummary?.failureReasonCode" class="text-[11px] text-rose-600">{{ userReasonLabel(child.blockingReason?.code || child.sourceSummary?.failureReasonCode) }}</div>
</div>
<span class="shrink-0" :class="child.userStatus === 'failed' || child.userStatus === 'retryable' ? 'text-rose-600' : child.userStatus === 'waiting_human' ? 'text-amber-700' : child.userStatus === 'completed' && child.facts?.uploadState === 'succeeded' ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
</div>
</div>
</div>
</div>
</article>
</div>
</section>
</template>
</div>
<div v-else-if="emlAggregate" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
<article class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
<div class="min-w-0 flex-1">
<div class="flex items-center justify-between gap-3">
<span class="truncate font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ emlAggregate.sourceSummary.filename || emlAggregate.intakeNo }}</span>
<span class="rounded border px-2 py-0.5 text-xs" :class="emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emlAggregate.userStatus === 'waiting_human' ? 'border-amber-200 bg-amber-100/70 text-amber-700' : emlAggregate.userStatus === 'completed' ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">
{{ emlAggregate.userStatus === 'completed' ? t('chat.shippingProcessing.aggregate.completed', { count: emlAggregate.aggregateSummary?.completed || 0 }) : emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? t('chat.shippingProcessing.batchException') : emlAggregate.userStatus === 'waiting_human' ? t('chat.shippingProcessing.waitingReview') : t('chat.shippingProcessing.systemProcessing') }}
</span>
</div>
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ aggregateSummaryLabel(emlAggregate) }}</div>
<div v-if="emlAggregate.blockingReason?.code" class="mt-1 text-xs text-rose-600">{{ userReasonLabel(emlAggregate.blockingReason.code) }}</div>
</div>
</div>
<button type="button" class="flex w-full items-center justify-between px-3 py-2 text-left text-sm" @click="emlAggregateExpanded = !emlAggregateExpanded">
<span>{{ t('chat.shippingProcessing.taskFiles', { count: emlAggregate.sourceSummary.documentCount || 0 }) }}</span>
<ChevronDown class="h-4 w-4 transition-transform" :class="emlAggregateExpanded ? 'rotate-180' : ''" />
</button>
<div v-if="emlAggregateExpanded" class="space-y-1 border-t border-slate-200 px-3 py-2 dark:border-slate-700">
<div v-for="child in emlAggregateChildren" :key="child.workItemNo" class="flex items-center justify-between gap-3 py-1 text-sm">
<span class="min-w-0 truncate">{{ child.sourceSummary.filename || child.workItemNo }}</span>
<span class="shrink-0 text-xs" :class="child.userStatus === 'failed' || child.userStatus === 'retryable' ? 'text-rose-600' : child.userStatus === 'waiting_human' ? 'text-amber-700' : child.userStatus === 'completed' && child.facts?.uploadState === 'succeeded' ? 'text-emerald-600' : 'text-blue-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
</div>
</div>
</article>
</div>
<div v-else class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
<button type="button" class="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-3 text-left dark:border-slate-700 dark:bg-slate-900" @click="completedExpanded = !completedExpanded">
<span class="flex items-center gap-3 text-base font-medium"><span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-100 text-blue-600"><CheckCircle2 class="h-4 w-4" /></span>{{ t('chat.shippingProcessing.candidateFiles', { count: candidateFileCount }) }}</span>
<ChevronDown class="h-5 w-5 transition-transform" :class="completedExpanded ? 'rotate-180' : ''" />
</button>
<div v-if="completedExpanded && candidateFileCount" class="space-y-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm dark:border-slate-700 dark:bg-slate-900">
<div v-for="group in candidateEmailGroups" :key="`candidate-email-${group.parent.unitId}`" class="rounded-md border border-blue-100 bg-blue-50/50 px-3 py-2 dark:border-blue-900 dark:bg-blue-950/20">
<div class="flex items-center gap-2 font-medium text-slate-700 dark:text-slate-200"><Mail class="h-4 w-4 text-blue-600" />{{ t('chat.shippingProcessing.emailPrefix') }}{{ group.parent.fileName }}<span class="ml-auto text-emerald-500">{{ t('chat.shippingProcessing.batchExtracted') }}</span></div>
<div class="mt-1 space-y-1 border-l-2 border-blue-200 pl-3 dark:border-blue-800">
<div v-for="row in group.children" :key="`candidate-child-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
</div>
</div>
<div v-for="row in candidateStandaloneRows" :key="`candidate-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
</div>
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20"><Mail class="mt-0.5 h-5 w-5 text-blue-600" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-slate-500">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-blue-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
</div>
<div v-for="row in standaloneRows" :key="row.unitId" class="flex items-center justify-between gap-3 rounded-lg border border-slate-200 bg-white p-3 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900"><span class="flex min-w-0 items-center gap-3"><FileText class="h-5 w-5 text-slate-500" /><span class="truncate">{{ row.fileName }}</span></span><span class="flex items-center gap-2" :class="rowStatusClass(row)">{{ rowStatusLabel(row) }}<RefreshCw v-if="!isFailedParseRow(row)" class="h-4 w-4 animate-spin" /></span></div>
<div v-if="!fileRows.length" class="rounded-lg border border-slate-200 bg-white p-3 text-sm text-slate-500 dark:border-slate-700 dark:bg-slate-900">{{ t('chat.shippingProcessing.batchFilesUnavailable') }}</div>
<div v-for="row in failedRows" :key="`failed-${row.unitId}`" class="rounded-lg border border-rose-200 bg-rose-50 p-3 dark:border-rose-800 dark:bg-rose-950/30"><div class="flex items-center justify-between text-rose-600"><span class="flex items-center gap-2 font-medium"><AlertCircle class="h-5 w-5" />{{ row.fileName }}</span><span class="rounded bg-rose-100 px-2 py-0.5 text-xs">{{ t('chat.shippingProcessing.batchException') }}</span></div><p class="mt-2 pl-7 text-sm">{{ row.explainability?.message || t('chat.shippingProcessing.batchManualVerify') }}</p></div>
</div>
<div class="flex justify-end border-t border-slate-200 bg-indigo-50/60 p-3 dark:border-slate-700 dark:bg-indigo-950/20">
<div class="flex items-center gap-3">
<button v-if="primaryChatAction" type="button" class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 disabled:opacity-50" data-testid="shipping-order-extraction-primary-action" :disabled="primaryChatAction.kind === 'retry' && retrying" @click="onPrimaryChatAction">{{ primaryChatAction.kind === 'retry' && retrying ? t('chat.shippingOrderExtractionRetrying') : primaryChatAction.label }}<ArrowRight class="h-4 w-4" /></button>
<button v-if="String(props.runNo || '').trim()" type="button" class="text-sm font-medium text-blue-600 underline-offset-2 hover:underline" data-testid="shipping-order-extraction-view-details" @click="openDetailsDrawer">{{ t('chat.shippingProcessing.viewTaskDetails') }}</button>
</div>
</div>
<div v-if="false" class="flex items-start gap-3">
<CircleX class="mt-0.5 h-4 w-4 shrink-0" />
<div class="min-w-0 flex-1">
<div
v-if="readonly"
@@ -394,7 +760,7 @@ async function onPrimaryChatAction() {
class="mt-1 text-[11px] opacity-80"
data-testid="shipping-order-extraction-error-request-id"
>
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability.request_id }) }}
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability?.request_id }) }}
</p>
<div
@@ -424,12 +790,12 @@ async function onPrimaryChatAction() {
type="button"
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
data-testid="shipping-order-extraction-primary-action"
:disabled="primaryChatAction.kind === 'retry' && retrying"
:disabled="primaryChatAction?.kind === 'retry' && retrying"
@click="onPrimaryChatAction"
>
{{ primaryChatAction.kind === 'retry' && retrying
{{ primaryChatAction?.kind === 'retry' && retrying
? t('chat.shippingOrderExtractionRetrying')
: primaryChatAction.label }}
: primaryChatAction?.label }}
</button>
<button
v-if="String(props.runNo || '').trim()"
@@ -7,7 +7,7 @@
* 以模态对话框语义呈现(初始焦点、Tab 陷阱、Escape/关闭后焦点恢复);
* 文档与时间线加载失败分别提供就地重试;内部错误码不向普通用户展示。
*/
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { X } from 'lucide-vue-next';
import type { ShippingOrderExtractionState } from '../../types/chat.types';
@@ -42,6 +42,19 @@ const closeButtonRef = ref<HTMLButtonElement | null>(null);
let previouslyFocused: HTMLElement | null = null;
const timelineOpen = ref(false);
const timelineGroups = computed(() => {
const groups = new Map<string, { documentId: number | null; fileName: string; events: ShippingOrderExtractionProgressEvent[] }>();
for (const event of props.progressEvents) {
const documentId = event.document_id != null ? Number(event.document_id) : null;
const document = documentId == null ? null : props.documents.find((item) => Number(item.document_id) === documentId);
const key = documentId == null ? 'run' : `document-${documentId}`;
const group = groups.get(key) || { documentId, fileName: document?.file_name || (documentId == null ? t('chat.shippingOrderExtractionTimelineRunScope') : `Document ${documentId}`), events: [] };
group.events.push(event);
groups.set(key, group);
}
return [...groups.values()];
});
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
@@ -314,28 +327,18 @@ onBeforeUnmount(() => {
>
{{ t('chat.shippingOrderExtractionTimelineEmpty') }}
</div>
<ol v-else class="mt-3 space-y-3">
<li
v-for="event in progressEvents"
:key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`"
class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200"
>
<div class="flex flex-wrap items-center gap-2">
<span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">
{{ t(eventCategoryKey(event)) }}
</span>
<div class="font-medium text-slate-900 dark:text-slate-100">
{{ eventActivityLabel(event) }}
</div>
</div>
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">
{{ eventContextLabel(event) }}
</div>
<div class="mt-1 opacity-70">
{{ eventOccurredAtLabel(event.occurred_at) }}
</div>
</li>
</ol>
<div v-else class="mt-3 space-y-3">
<section v-for="group in timelineGroups" :key="group.documentId == null ? 'run' : group.documentId" class="rounded-md border border-slate-200 px-3 py-2 dark:border-slate-700">
<h4 class="text-xs font-semibold text-slate-900 dark:text-slate-100">{{ group.fileName }}</h4>
<ol class="mt-2 space-y-3">
<li v-for="event in group.events" :key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`" class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200">
<div class="flex flex-wrap items-center gap-2"><span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">{{ t(eventCategoryKey(event)) }}</span><div class="font-medium text-slate-900 dark:text-slate-100">{{ eventActivityLabel(event) }}</div></div>
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">{{ eventContextLabel(event) }}</div>
<div class="mt-1 opacity-70">{{ eventOccurredAtLabel(event.occurred_at) }}</div>
</li>
</ol>
</section>
</div>
</details>
</div>
</aside>
@@ -330,7 +330,9 @@ async function onProcessingIntakeAction(payload: {
action: string;
}) {
const action = String(payload.action || '').trim();
const intakeNo = String(payload.item.workItemNo || payload.item.intakeNo || '').trim();
// 聚合卡的 workItemNo 可能是 INTAKE:<no>,写接口必须使用规范化 intakeNo。
const intakeNo = String(payload.item.intakeNo || '').trim()
|| String(payload.item.workItemNo || '').replace(/^INTAKE:/i, '').trim();
if (action === 'retry_parse') {
if (!intakeNo) {
msg.error(t('chat.shippingProcessing.retryTaskMissingRun'));
@@ -382,6 +384,49 @@ async function onProcessingTaskAction(payload: {
await openReviewFromTask(task);
return;
}
if (action === 'edit_draft' || action === 'create_draft' || action === 'reconcile_and_progress') {
await openReviewFromTask(task);
return;
}
if (action === 'reparse') {
if (!runNo) {
msg.warning(t('chat.shippingOrderReview.caseRequired'));
return;
}
const target = items.value.find((item) => String(item.current_run_no || '').trim() === runNo);
if (target) openReparseDialog(target);
else msg.warning(t('chat.shippingOrderReview.caseRequired'));
return;
}
if (action === 'retry_parse' || action === 'retry') {
const intakeNo = String(task.user_task_no || '').replace(/^INTAKE:/i, '').trim();
if (intakeNo.startsWith('SNI-')) {
if (actionBusyItemNo.value) return;
actionBusyItemNo.value = intakeNo;
try {
await retryShippingNoticeIntake(intakeNo);
await ctl.value.refresh();
} catch (err) {
msg.error(reparseErrorMessage(err));
} finally {
actionBusyItemNo.value = null;
}
} else if (runNo) {
if (actionBusyItemNo.value) return;
actionBusyItemNo.value = runNo;
try {
await retryWorkspaceShippingOrderExtractionRun(runNo);
await ctl.value.refresh();
} catch (err) {
msg.error(reparseErrorMessage(err));
} finally {
actionBusyItemNo.value = null;
}
} else {
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
}
return;
}
if (action === 'cancel_task' || action === 'cancel_run') {
if (!runNo) {
msg.error(t('chat.shippingProcessing.cancelTaskMissingRun'));
@@ -554,6 +599,14 @@ async function onTaskProjectionAction(payload: {
const { projection, item } = payload;
const taskNo = String(projection.workItemNo || '').trim();
const code = String(item.actionCode || '').trim();
if (code === 'reparse') {
const task = [
...(displayProcessing.value?.needs_action || []),
...(displayProcessing.value?.processing || []),
].find((row) => String(row.user_task_no || '').trim() === taskNo);
if (task) void onProcessingTaskAction({ task, action: 'reparse' });
return;
}
if (code === 'retry_parse' || item.intent === 'retry') {
void onProcessingIntakeAction({ item: projection, action: code || 'retry_parse' });
return;
@@ -569,7 +622,7 @@ async function onTaskProjectionAction(payload: {
...(displayProcessing.value?.completed || []),
].find((row) => String(row.user_task_no || '').trim() === taskNo);
if (task) {
void onProcessingTaskAction({ task, action: 'open_review' });
void onProcessingTaskAction({ task, action: code || 'open_review' });
}
return;
}
@@ -185,6 +185,7 @@ const normalizeShippingOrderExtractionState = (
: null;
return {
status: status as ShippingOrderExtractionState['status'],
uploadBatchId: String(data.uploadBatchId || '').trim() || null,
summary: {
totalDocuments: Math.max(0, Number(rawSummary.totalDocuments || 0)),
pendingDocuments: Math.max(0, Number(rawSummary.pendingDocuments || 0)),
@@ -207,6 +208,27 @@ const normalizeShippingOrderExtractionState = (
: [],
}
: null,
documents: Array.isArray(data.documents)
? data.documents.map((item) => {
const row = item && typeof item === 'object' ? item as Record<string, unknown> : {};
return {
unitId: Math.max(0, Number(row.unitId || 0)),
documentId: Math.max(0, Number(row.documentId || 0)),
intakeId: row.intakeId != null ? Math.max(0, Number(row.intakeId || 0)) || null : null,
documentType: String(row.documentType || '').trim() || null,
fileName: String(row.fileName || '').trim() || null,
status: String(row.status || '').trim(),
userVisibleStage: String(row.userVisibleStage || '').trim() || null,
reasonCode: String(row.reasonCode || '').trim() || null,
explainability: row.explainability && typeof row.explainability === 'object'
? row.explainability as { message?: string | null }
: null,
emailSupplement: row.emailSupplement && typeof row.emailSupplement === 'object'
? row.emailSupplement as { status?: string | null }
: null,
};
})
: [],
selectionPlan: rawSelectionPlan
? {
selectionVersion: String(rawSelectionPlan.selectionVersion || '').trim() || null,
@@ -613,6 +613,94 @@ describe('conversationProcessingProjection', () => {
expect(projection?.summary.total_files).toBe(1);
});
it('aggregates mixed order tasks from one EML intake into one card', () => {
const base = {
sourceType: 'eml' as const,
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-eml',
submissionNo: 'SOS-EML',
intakeNo: 'INTAKE-EML-1',
progressVersion: 1,
currentGate: null,
childOrderTasks: [],
};
const items: ShippingProcessingProjection[] = [
{
...base, workItemType: 'order_task', workItemNo: 'OT-DONE', status: 'completed', stage: 'completed',
userStatus: 'completed', userStage: 'completed', lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
sourceSummary: { emailSubject: 'Shipment', filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
{
...base, workItemType: 'order_task', workItemNo: 'OT-RUN', status: 'processing', stage: 'inventory_matching',
userStatus: 'running', userStage: 'inventory_match', lastActivityAt: '2026-08-06T00:00:01Z', availableActions: [],
sourceSummary: { emailSubject: 'Shipment', filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
{
...base, workItemType: 'order_task', workItemNo: 'OT-FAIL', status: 'failed', stage: 'freight_uploading',
userStatus: 'failed', userStage: 'freight_upload', lastActivityAt: '2026-08-06T00:00:02Z', availableActions: [],
blockingReason: { code: 'upload_rpa_failed' },
sourceSummary: { emailSubject: 'Shipment', filename: 'c.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
];
const projection = projectConversationProcessingFromWorkItems(items);
expect(projection?.needs_action).toHaveLength(1);
expect(projection?.processing).toHaveLength(0);
expect(projection?.completed).toHaveLength(0);
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
intakeNo: 'INTAKE-EML-1', total: 3, completed: 1, processing: 1, needsAction: 1, failed: 1,
}));
expect(projection?.needs_action[0]?.file_count).toBe(3);
expect(projection?.needs_action[0]?.aggregateSummary?.reasonCodes).toContain('upload_rpa_failed');
});
it('does not reuse an empty EML task when a later poll returns aggregate children', () => {
const base = {
workItemType: 'order_task' as const, sourceType: 'eml' as const, rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null, conversationId: 'conv-stable', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
progressVersion: 1, currentGate: null, availableActions: [], status: 'processing' as const,
stage: 'document_parsing' as const, userStatus: 'running' as const, userStage: 'document_parsing' as const,
lastActivityAt: '2026-08-06T00:00:00Z',
sourceSummary: { emailSubject: 'mail', filename: 'stable.eml', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
};
const first = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [] }]);
const child = { ...base, workItemNo: 'OT-CHILD', sourceSummary: { ...base.sourceSummary, filename: 'attachment.pdf' } };
const second = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [child] }], first);
expect(second?.processing[0]?.aggregateChildren?.map((item) => item.sourceSummary.filename)).toEqual(['attachment.pdf']);
expect(second?.processing[0]).not.toBe(first?.processing[0]);
});
it('puts an EML with review-required children into needs_action even when parent says processing', () => {
const parent = {
workItemType: 'order_task' as const, workItemNo: 'INTAKE:SNI-STATUS', sourceType: 'eml' as const,
rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS',
status: 'processing' as const, stage: 'document_parsing' as const, userStatus: 'running' as const, userGroup: 'processing' as const,
userStage: 'document_parsing' as const, progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'mail.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
aggregateChildren: [
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'review_required', stage: 'review_required', userStatus: 'waiting_human', userStage: 'review_required', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'processing', stage: 'document_parsing', userStatus: 'running', userStage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
],
} as any;
const projection = projectConversationProcessingFromWorkItems([parent]);
expect(projection?.needs_action).toHaveLength(1);
expect(projection?.processing).toHaveLength(0);
});
it('does not aggregate direct PDFs with matching intake numbers', () => {
const common = {
workItemType: 'order_task' as const, rootOrderTaskNo: null, shippingNoticeNo: null,
conversationId: 'conv-pdf', submissionNo: 'SOS-PDF', intakeNo: 'INTAKE-SAME', progressVersion: 1,
currentGate: null, childOrderTasks: [], status: 'processing' as const, stage: 'document_parsing' as const,
userStatus: 'running' as const, userStage: 'document_parsing' as const, lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
};
const projection = projectConversationProcessingFromWorkItems([
{ ...common, workItemNo: 'OT-1', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
{ ...common, workItemNo: 'OT-2', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
]);
expect(projection?.processing).toHaveLength(2);
});
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
const workItems: ShippingProcessingProjection[] = [
{
@@ -693,7 +781,10 @@ describe('conversationProcessingProjection', () => {
const projection = resolveConversationProcessingFromUnified(workItems, embedded);
// 关键断言:兄弟 OT 仅出现在 work_items;embedded 缺 sibling 时不得覆盖任务列表。
expect(projection?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(projection?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
expect(projection?.processing).toEqual([]);
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
intakeNo: 'SNI-1', total: 2, completed: 0, processing: 1, needsAction: 1,
}));
expect(projection?.focused_task_no).toBe('OT-ROOT');
expect(projection?.recent_task_no).toBe('OT-SIBLING');
});
@@ -1006,7 +1097,7 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
expect(result!.needs_action[0]!.title).toBe('b.pdf');
});
it('resolveConversationProcessingFromUnified: work_items 仅含 order_intake 时,仍走 embedded normalize 路径(过渡窗口不跳状态)', () => {
it('resolveConversationProcessingFromUnified: 仅含 EML order_intake 时,派生统一 processing 投影而非回退 embedded', () => {
const embedded: ConversationProcessingProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
focused_task_no: 'OT-LEG3',
@@ -1035,7 +1126,7 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
sourceType: 'eml',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
@@ -1061,13 +1152,16 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
];
const result = resolveConversationProcessingFromUnified(workItems, embedded);
expect(result).not.toBeNull();
// 过渡阶段:order_intake 不触发统一投影派生;embedded waiting_human 必须 normalize 成 waiting_review/needs_action
// EML 尚未创建 OT 时,也必须作为一张 EML 卡进入统一“系统处理中”区。
expect(result!.focused_task_no).toBe('OT-LEG3');
expect(result!.processing.length).toBe(0);
expect(result!.needs_action.length).toBe(1);
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
expect(result!.needs_action[0]!.title).toBe('c.pdf');
expect(result!.needs_action[0]!.group).toBe('needs_action');
expect(result!.needs_action).toHaveLength(0);
expect(result!.processing).toHaveLength(1);
expect(result!.processing[0]).toMatchObject({
user_task_no: 'SNI-1',
title: 'c.pdf',
group: 'processing',
status_label: 'processing',
});
});
it('resolveConversationProcessingFromUnified + IntakeOtStabilizer: 看到 order_task 后 2s 内暂缺 OT 保持 previousProjection(避免轮询抖动)', () => {
@@ -50,6 +50,15 @@ export function buildTaskSemanticKey(
): string {
if (!task) return '';
const rawStatus = (task as ConversationProcessingUserTask & { userStatus?: string | null }).userStatus ?? task.status_label;
const aggregateChildren = (task.aggregateChildren || []).map((child) => ({
workItemNo: child.workItemNo,
intakeNo: child.intakeNo,
status: child.userStatus ?? child.status,
stage: child.userStage ?? child.stage,
uploadState: child.facts?.uploadState ?? null,
filename: child.sourceSummary?.filename ?? null,
reason: child.blockingReason?.code ?? child.sourceSummary?.failureReasonCode ?? null,
}));
return JSON.stringify({
taskNo: task.user_task_no,
group: task.group,
@@ -83,6 +92,7 @@ export function buildTaskSemanticKey(
: null,
availableActions: normalizeActionCodes(task.available_actions || []),
canAppend: task.can_append ?? null,
aggregateChildren,
});
}
@@ -791,7 +801,22 @@ export function groupConversationProcessingTasks(
export function mapShippingProcessingStatusToTaskGroup(
item: ShippingProcessingProjection,
): ConversationProcessingTaskGroup {
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
const userGroup = String(item.userGroup || '').trim().toLowerCase();
const status = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim());
const childStatuses = (item.aggregateChildren || []).map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
const childHasFailure = childStatuses.some((value) => value === 'failed');
const childNeedsHuman = childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready');
const childAllUploaded = childStatuses.length > 0
&& childStatuses.every((value, index) => value === 'completed' && item.aggregateChildren?.[index]?.facts?.uploadState === 'succeeded');
if (childHasFailure) return 'needs_action';
if (childNeedsHuman) return 'needs_action';
if (childAllUploaded) return 'completed';
// 子项真实状态优先于父级 userGroup,避免 review_required/failed 被旧 processing 覆盖。
if (status === 'failed' || status === 'waiting_review' || status === 'manual_upload_pending') return 'needs_action';
if (userGroup === 'failed' || userGroup === 'waiting_human') return 'needs_action';
if (userGroup === 'completed') return 'completed';
if (userGroup === 'cancelled' || userGroup === 'archived') return 'history';
if (userGroup === 'processing') return 'processing';
const gateAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase();
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
.map((value) => String(value || '').trim().toLowerCase())
@@ -859,7 +884,10 @@ export function resolveConversationProcessingFromUnified(
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
const hasOrderTask = items.some((item) => item.workItemType === 'order_task');
const hasOrderTask = items.some((item) => (
item.workItemType === 'order_task'
|| (item.workItemType === 'order_intake' && item.sourceType === 'eml')
));
const convId = stabilizer?.conversationId;
if (hasOrderTask) {
stabilizer?.markSeen?.(convId);
@@ -945,24 +973,27 @@ export function normalizeConversationProcessingProjection(
}
/**
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
* 从统一 work_items 合成 ConversationProcessingProjection(order_task 与 EML order_intake)。
*
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组;
* 核心逻辑:order_task 与 EML order_intake 均进入状态区;非 EML intake 不入组;
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
*
* @param workItems - 统一投影 work_items
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
* @returns 兼容投影;无 order_task 时返回 null
* @returns 兼容投影;无可展示任务时返回 null
*/
export function projectConversationProcessingFromWorkItems(
workItems: ShippingProcessingProjection[] | null | undefined,
previousProjection?: ConversationProcessingProjection | null,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
const orderTasks = items.filter((row) => row.workItemType === 'order_task');
const orderTasks = items.filter((row) => (
row.workItemType === 'order_task'
|| (row.workItemType === 'order_intake' && row.sourceType === 'eml')
));
if (!orderTasks.length) return null;
const rawTasks: ConversationProcessingUserTask[] = [];
const rawTaskEntries: Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }> = [];
for (const item of orderTasks) {
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
@@ -1019,15 +1050,111 @@ export function projectConversationProcessingFromWorkItems(
available_actions: normalizedActions,
primary_action: gateNextAction || normalizedActions[0] || null,
userStatus: item.userStatus ?? null,
userStage: item.userStage ?? null,
blockingReason: userBlocking,
primaryAction: userPrimaryAction,
facts: userFacts,
userGroup: item.userGroup ?? null,
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
userCurrentGateCode: item.userCurrentGateCode ?? null,
legacyStatus: item.legacyStatus ?? null,
legacyStage: item.legacyStage ?? null,
aggregateSummary: item.aggregateSummary ?? null,
aggregateChildren: item.aggregateChildren ?? [],
};
rawTasks.push(task);
rawTaskEntries.push({ task, item });
}
const rawTasks: ConversationProcessingUserTask[] = [];
const emlGroups = new Map<string, Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }>>();
for (const entry of rawTaskEntries) {
if (entry.item.sourceType !== 'eml' || !entry.item.intakeNo) {
rawTasks.push(entry.task);
continue;
}
const key = String(entry.item.intakeNo).trim();
const group = emlGroups.get(key) || [];
group.push(entry);
emlGroups.set(key, group);
}
for (const [intakeNo, entries] of emlGroups) {
if (entries.length === 1) {
rawTasks.push({
...entries[0]!.task,
aggregateChildren: entries[0]!.task.aggregateChildren?.length
? entries[0]!.task.aggregateChildren
: entries[0]!.item.aggregateChildren || [],
});
continue;
}
const completed = entries.filter(({ item }) => String(item.userStatus ?? item.status).toLowerCase() === 'completed').length;
const failed = entries.filter(({ item }) => ['failed', 'retryable'].includes(String(item.userStatus ?? item.status).toLowerCase())).length;
const needsAction = entries.filter(({ task }) => task.group === 'needs_action').length;
const processing = entries.filter(({ task }) => task.group === 'processing').length;
const stages = [...new Set(entries.flatMap(({ item }) => [item.userStage, item.stage].filter(Boolean).map(String)))];
const reasonCodes = [...new Set(entries.flatMap(({ item }) => [
item.blockingReason?.code,
item.sourceSummary?.failureReasonCode,
].filter(Boolean).map(String)))];
const entryGroups = entries.map(({ task, item }) => {
const children = item.aggregateChildren || [];
const childStatuses = children.map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
if (childStatuses.some((value) => value === 'failed')) return 'failed';
if (childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready')) return 'waiting_human';
if (childStatuses.length > 0 && childStatuses.every((value, index) => value === 'completed' && children[index]?.facts?.uploadState === 'succeeded')) return 'completed';
const explicit = String(item.userGroup || '').trim().toLowerCase();
if (explicit) return explicit;
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
if (status === 'failed' || status === 'retryable') return 'failed';
if (task.group === 'needs_action') return 'waiting_human';
if (task.group === 'completed' && status === 'completed') return 'completed';
if (task.group === 'history') return status === 'cancelled' ? 'cancelled' : 'archived';
return 'processing';
});
const aggregateUserGroup = entryGroups.includes('failed')
? 'failed'
: entryGroups.includes('waiting_human')
? 'waiting_human'
: entryGroups.includes('processing')
? 'processing'
: entryGroups.includes('completed') && entryGroups.every((value) => value === 'completed')
? 'completed'
: entryGroups.includes('cancelled')
? 'cancelled'
: entryGroups.includes('archived')
? 'archived'
: 'processing';
const group = aggregateUserGroup === 'failed' || aggregateUserGroup === 'waiting_human'
? 'needs_action'
: aggregateUserGroup === 'completed'
? 'completed'
: aggregateUserGroup === 'cancelled' || aggregateUserGroup === 'archived'
? 'history'
: 'processing';
const representative = entries[0]!.task;
const documentNames = [...new Set(entries.flatMap(({ task }) => task.document_names || []).filter(Boolean))];
const fileCount = entries.reduce((sum, { task }) => sum + Number(task.file_count || 0), 0);
rawTasks.push({
...representative,
title: representative.title || `EML ${intakeNo}`,
display_kind: fileCount > 1 ? 'multi_document_task' : representative.display_kind,
document_names: documentNames,
file_count: fileCount,
group,
available_actions: [...new Set(entries.flatMap(({ task }) => task.available_actions || []))].sort(),
aggregateSummary: {
intakeNo,
total: entries.length,
completed,
processing,
needsAction,
failed,
stages,
reasonCodes,
},
aggregateChildren: entries.flatMap(({ item }) => item.aggregateChildren || [item]),
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
});
}
if (!rawTasks.length) return null;
@@ -1082,6 +1209,15 @@ export function projectConversationProcessingFromWorkItems(
stabilizedAll.filter((t) => t.group === 'history'),
);
const status_groups = {
failed: stabilizedAll.filter((task) => task.userGroup === 'failed'),
waiting_human: stabilizedAll.filter((task) => task.userGroup === 'waiting_human'),
processing: stabilizedAll.filter((task) => task.userGroup === 'processing'),
completed: stabilizedAll.filter((task) => task.userGroup === 'completed'),
cancelled: stabilizedAll.filter((task) => task.userGroup === 'cancelled'),
archived: stabilizedAll.filter((task) => task.userGroup === 'archived'),
};
return {
summary: {
total_tasks: active.length,
@@ -1097,5 +1233,6 @@ export function projectConversationProcessingFromWorkItems(
processing,
completed,
history,
status_groups,
};
}
@@ -230,6 +230,29 @@ function normalizeFacts(raw: unknown): ShippingProcessingFacts | undefined {
return out;
}
function normalizeAggregateSummary(
raw: unknown,
): ShippingProcessingProjection['aggregateSummary'] {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const array = (value: unknown): string[] => Array.isArray(value)
? value.map((entry) => String(entry || '').trim()).filter(Boolean)
: [];
const count = (key: string): number => Number(item[key] || 0) || 0;
const intakeNo = String(item.intake_no ?? item.intakeNo ?? '').trim();
if (!intakeNo) return null;
return {
intakeNo,
total: count('total'),
completed: count('completed'),
processing: count('processing'),
needsAction: count('needs_action') || count('needsAction'),
failed: count('failed'),
stages: array(item.stages),
reasonCodes: array(item.reason_codes ?? item.reasonCodes),
};
}
/**
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
* 注意:failed_sources 会进一步透传到 exhausted_sources 分开(二者互斥;仅 max_attempts 耗尽的源进 exhausted)。
@@ -324,6 +347,12 @@ export function normalizeShippingProcessingProjection(
const stageNodes = Array.isArray(stageNodesRaw)
? stageNodesRaw.map(normalizeStageNode).filter((row): row is ShippingProcessingStageNode => Boolean(row))
: undefined;
const aggregateChildrenRaw = item.aggregate_children ?? item.aggregateChildren;
const aggregateChildren = Array.isArray(aggregateChildrenRaw)
? aggregateChildrenRaw
.map(normalizeShippingProcessingProjection)
.filter((entry): entry is ShippingProcessingProjection => Boolean(entry))
: undefined;
return {
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
@@ -368,6 +397,9 @@ export function normalizeShippingProcessingProjection(
(item.retryable as boolean | undefined) == null ? false : Boolean(item.retryable),
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
facts: normalizeFacts(item.facts),
userGroup: readNullableString(item, 'user_group', 'userGroup') as ShippingProcessingProjection['userGroup'],
aggregateSummary: normalizeAggregateSummary(item.aggregate_summary ?? item.aggregateSummary),
aggregateChildren: aggregateChildren?.length ? aggregateChildren : undefined,
legacyStatus: readNullableString(item, 'legacy_status', 'legacyStatus'),
legacyStage: readNullableString(item, 'legacy_stage', 'legacyStage'),
hasFormalOt:
@@ -311,7 +311,7 @@ describe('useShippingNoticeWorkflow', () => {
ctl.stop();
});
it('derives sibling OT tasks from work_items when embedded conversation_processing omits them', async () => {
it('aggregates sibling EML OT work_items into one highest-attention Intake card', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [
@@ -397,7 +397,12 @@ describe('useShippingNoticeWorkflow', () => {
await Promise.resolve();
expect(ctl.processing.value?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(ctl.processing.value?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
expect(ctl.processing.value?.processing).toEqual([]);
expect(ctl.processing.value?.needs_action[0]?.aggregateSummary).toMatchObject({
intakeNo: 'SNI-1',
total: 2,
processing: 1,
});
expect(ctl.processing.value?.focused_task_no).toBe('OT-ROOT');
expect(ctl.processing.value?.recent_task_no).toBe('OT-SIBLING');
ctl.stop();
@@ -136,6 +136,80 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
harness.runs.stopPolling();
});
it('merges sibling Runs from one upload batch into one chat status card', async () => {
const first = Object.assign(run({
run_no: 'SNER-BATCH-1',
conversation_id: 'conv-batch',
intake_nos: ['SNI-BATCH-1'],
summary: {
total_documents: 1,
pending_documents: 1,
processing_documents: 0,
completed_documents: 0,
review_required_documents: 0,
failed_documents: 0,
candidate_count: 0,
},
documents: [{
unit_id: 1,
document_id: 101,
file_name: 'notice-a.pdf',
status: 'queued',
line_count: 0,
email_supplement: { status: 'none', relation_codes: [] },
available_actions: [],
}],
}), { upload_batch_id: 'upload-batch-1' });
const second = Object.assign(run({
run_no: 'SNER-BATCH-2',
conversation_id: 'conv-batch',
intake_nos: ['SNI-BATCH-2'],
summary: {
total_documents: 1,
pending_documents: 0,
processing_documents: 1,
completed_documents: 0,
review_required_documents: 0,
failed_documents: 0,
candidate_count: 0,
},
documents: [{
unit_id: 2,
document_id: 102,
file_name: 'notice-b.pdf',
status: 'processing',
line_count: 0,
email_supplement: { status: 'none', relation_codes: [] },
available_actions: [],
}],
}), { upload_batch_id: 'upload-batch-1' });
api.createSubmission.mockResolvedValue({
decision: 'created',
user_task_no: null,
run_no: first.run_no,
created_new: true,
operation_id: 'op-batch',
});
api.getRun.mockResolvedValue(first);
api.listRuns.mockResolvedValue({ items: [first, second] });
const harness = createHarness();
await harness.runs.startRun('', ['SNI-BATCH-1', 'SNI-BATCH-2'], [], 'upload-batch-1');
const cards = harness.messages.value.filter((message) => message.shipping_order_extraction_state);
expect(cards).toHaveLength(1);
expect(cards[0]?.shipping_order_extraction_state?.summary).toMatchObject({
totalDocuments: 2,
pendingDocuments: 1,
processingDocuments: 1,
});
expect(cards[0]?.shipping_order_extraction_state?.documents?.map((item) => item.fileName)).toEqual([
'notice-a.pdf',
'notice-b.pdf',
]);
harness.runs.stopPolling();
});
it('keeps an appended submission in the user message and the existing Run state card only', async () => {
const queued = run({
run_no: 'SNER-APPENDED',
@@ -54,6 +54,69 @@ const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
/**
* 将同一上传批次的独立 Run 合成单张聊天状态卡。
*
* 核心逻辑:Run 仍按 Intake 独立执行、审计和复核;仅把同会话同 upload_batch_id
* 的用户态摘要相加,保证一次文件选择在聊天区只出现一个卡片。
*/
function mergeUploadBatchRuns(primary: ShippingOrderExtractionRun, runs: ShippingOrderExtractionRun[]): ShippingOrderExtractionRun {
const batchId = String(primary.upload_batch_id || '').trim();
if (!batchId) return primary;
const members = runs.filter((item) => (
item.conversation_id === primary.conversation_id
&& String(item.upload_batch_id || '').trim() === batchId
));
if (members.length <= 1) return primary;
const activeMembers = members.filter((item) => ACTIVE_RUN_STATUSES.has(item.status));
const status = activeMembers.some((item) => item.status === 'processing')
? 'processing'
: activeMembers.length > 0
? 'queued'
: members.some((item) => item.status === 'failed')
? 'failed'
: members.some((item) => item.status === 'review_required')
? 'review_required'
: members.some((item) => item.status === 'partially_completed')
? 'partially_completed'
: 'completed';
const failedParseMembers = members.filter((item) => (
item.documents || []
).some((document) => document.reason_code === 'intake_parse_failed' || String(document.user_visible_stage || '') === 'parse_failed'));
const effectiveStatus = failedParseMembers.length > 0 && activeMembers.length === 0 ? 'failed' : status;
const summaryKeys = [
'total_documents', 'pending_documents', 'processing_documents', 'completed_documents',
'review_required_documents', 'failed_documents', 'cancelled_documents', 'candidate_count',
'opened_existing_documents',
] as const;
const summary = summaryKeys.reduce((result, key) => {
result[key] = members.reduce((total, item) => total + Number(item.summary?.[key] || 0), 0);
return result;
}, {} as ShippingOrderExtractionRun['summary']);
const documentIds = new Set<number>();
const documents = members.flatMap((item) => item.documents || []).filter((item) => {
const id = Number(item.document_id || 0);
if (id && documentIds.has(id)) return false;
if (id) documentIds.add(id);
return true;
});
const mostRecent = [...members].sort((left, right) => String(right.last_activity_at || '').localeCompare(String(left.last_activity_at || '')))[0] || primary;
return {
...primary,
status: effectiveStatus,
phase: effectiveStatus,
intake_nos: [...new Set(members.flatMap((item) => item.intake_nos || []))],
summary,
documents,
current_activity: mostRecent.current_activity || primary.current_activity,
available_actions: [...new Set(members.flatMap((item) => item.available_actions || []))],
handling_items: members.flatMap((item) => item.handling_items || []),
health_tips: members.flatMap((item) => item.health_tips || []),
progress_version: Math.max(...members.map((item) => Number(item.progress_version || 0))),
last_activity_at: mostRecent.last_activity_at || primary.last_activity_at,
};
}
/** 按页面可见性选择轮询间隔;后台放慢,失败退避另算。 */
function resolvePollIntervalMs(failureCount = 0): number {
if (failureCount > 0) {
@@ -72,6 +135,7 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
userTaskNo: run.user_task_no || null,
submissionOrdinal: run.submission_ordinal ?? null,
composerContextId: run.composer_context_id || null,
uploadBatchId: run.upload_batch_id || null,
runNo: run.run_no,
sourceRunNo: run.reparse?.source_run_no || null,
supersedingRunNo: run.reparse?.superseding_run_no || null,
@@ -110,6 +174,20 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
lastActivityAt: run.current_activity.last_activity_at || null,
}
: null,
documents: Array.isArray(run.documents)
? run.documents.map((item) => ({
unitId: Number(item.unit_id || 0),
documentId: Number(item.document_id || 0),
intakeId: item.intake_id != null ? Number(item.intake_id || 0) || null : null,
documentType: item.document_type || null,
fileName: item.file_name || null,
status: String(item.status || ''),
userVisibleStage: item.user_visible_stage || null,
reasonCode: item.reason_code || null,
explainability: item.explainability ? { message: item.explainability.message || null } : null,
emailSupplement: item.email_supplement ? { status: item.email_supplement.status || null } : null,
}))
: [],
selectionPlan: run.selection_plan
? {
selectionVersion: run.selection_plan.selection_version || null,
@@ -218,6 +296,22 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
return composerContextId;
}
/**
* 读取同批次兄弟 Run 后生成聊天展示快照。
*
* 仅在服务端已返回 upload_batch_id 时查询;旧 Run 或重识别 Run 保持原有单卡逻辑。
*/
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => {
if (!String(run.upload_batch_id || '').trim()) return run;
try {
const response = await listWorkspaceShippingOrderExtractionRuns(run.conversation_id, 100);
return mergeUploadBatchRuns(run, response.items || []);
} catch {
// 聚合读失败时宁可显示本 Run 的真实状态,也不阻断轮询或误改业务状态。
return run;
}
};
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
const stopPolling = () => {
if (pollTimer) clearTimeout(pollTimer);
@@ -260,10 +354,18 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
): Promise<ChatMessage> => {
const formId = `shipping-order-extraction-run:${run.run_no}`;
const state = mapOrderExtractionRunToMessageState(run);
const uploadBatchId = String(run.upload_batch_id || '').trim();
const stateCards = options.messages.value.filter((item) => {
if (item.role !== 'assistant') return false;
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
return payload.formId === formId || payload.order_extraction_run_no === run.run_no;
const cardBatchId = String(
payload.shipping_order_extraction_upload_batch_id
|| item.shipping_order_extraction_state?.uploadBatchId
|| '',
).trim();
return payload.formId === formId
|| payload.order_extraction_run_no === run.run_no
|| Boolean(uploadBatchId && cardBatchId === uploadBatchId);
});
let message = stateCards.find((item) => {
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
@@ -287,6 +389,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
message.payload = {
formId,
order_extraction_run_no: run.run_no,
shipping_order_extraction_upload_batch_id: run.upload_batch_id || null,
shipping_order_extraction_state: state,
order_extraction_reparse: run.reparse || null,
shipping_order_extraction_review: reviewAttachments || [],
@@ -386,18 +489,20 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const request = createRequestController(generation);
const run = await getWorkspaceShippingOrderExtractionRun(runNo, request.signal).finally(request.release);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
const displayRun = await loadDisplayRun(run);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
pollFailureCount = 0;
setRunRefreshFailed(run.run_no, false);
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
const reviewAttachments = await refreshTerminalFacts(run);
setRunRefreshFailed(displayRun.run_no, false);
if (!ACTIVE_RUN_STATUSES.has(displayRun.status)) {
const reviewAttachments = await refreshTerminalFacts(displayRun);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
stopPolling();
await upsertRunMessage(run, reviewAttachments);
await acknowledgeTerminalRunWhenVisible(run);
await upsertRunMessage(displayRun, reviewAttachments);
await acknowledgeTerminalRunWhenVisible(displayRun);
return;
}
await upsertRunMessage(run);
await acknowledgeTerminalRunWhenVisible(run);
await upsertRunMessage(displayRun);
await acknowledgeTerminalRunWhenVisible(displayRun);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
pollTimer = setTimeout(() => void pollRun(run.run_no, generation), resolvePollIntervalMs(0));
} catch {
@@ -456,7 +561,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
focused_user_task_no: focusedUserTaskNo,
});
// 统一提交只返回决策摘要;再拉 Run 投影供状态卡与轮询。
const run = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
const submittedRun = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
const run = await loadDisplayRun(submittedRun);
if (!options.conversationId.value) {
options.conversationId.value = run.conversation_id;
composerBoundConversationId = run.conversation_id;
@@ -487,7 +593,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
await options.onConversationResolved(run.conversation_id);
options.onWorkflowRefresh?.();
if (ACTIVE_RUN_STATUSES.has(run.status)) {
beginPolling(run.run_no, 1000);
beginPolling(submittedRun.run_no, 1000);
} else {
const reviewAttachments = await refreshTerminalFacts(run);
await upsertRunMessage(run, reviewAttachments);
@@ -524,7 +630,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const normalizedRunNo = String(runNo || '').trim();
if (!normalizedRunNo) return false;
try {
const run = await getWorkspaceShippingOrderExtractionRun(normalizedRunNo);
const fetchedRun = await getWorkspaceShippingOrderExtractionRun(normalizedRunNo);
const run = await loadDisplayRun(fetchedRun);
setRunRefreshFailed(run.run_no, false);
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
const reviewAttachments = await refreshTerminalFacts(run);
@@ -533,7 +640,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
return true;
}
await upsertRunMessage(run);
if (activeRunNo !== run.run_no || !pollTimer) beginPolling(run.run_no, FOREGROUND_POLL_MS);
if (activeRunNo !== fetchedRun.run_no || !pollTimer) beginPolling(fetchedRun.run_no, FOREGROUND_POLL_MS);
return true;
} catch (error) {
setRunRefreshFailed(normalizedRunNo, true);
@@ -662,15 +769,16 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const latest = items[0];
if (!latest) return;
activeRunNo = latest.run_no;
const reviewAttachments = ACTIVE_RUN_STATUSES.has(latest.status)
const displayRun = mergeUploadBatchRuns(latest, items);
const reviewAttachments = ACTIVE_RUN_STATUSES.has(displayRun.status)
? undefined
: await refreshTerminalFacts(latest);
: await refreshTerminalFacts(displayRun);
if (options.conversationId.value !== conversationId) return;
await upsertRunMessage(latest, reviewAttachments);
await acknowledgeTerminalRunWhenVisible(latest);
await upsertRunMessage(displayRun, reviewAttachments);
await acknowledgeTerminalRunWhenVisible(displayRun);
options.onWorkflowRefresh?.();
if (options.conversationId.value !== conversationId) return;
if (ACTIVE_RUN_STATUSES.has(latest.status)) {
if (ACTIVE_RUN_STATUSES.has(displayRun.status)) {
beginPolling(latest.run_no, 1000);
}
} catch {
@@ -77,6 +77,20 @@ export interface ShippingOrderExtractionCurrentActivityState {
lastActivityAt?: string | null;
}
/** 聊天批处理卡按文件展示的只读状态;业务真相仍由 Run/Unit 后端投影提供。 */
export interface ShippingOrderExtractionFileState {
unitId: number;
documentId: number;
intakeId?: number | null;
documentType?: string | null;
fileName?: string | null;
status: string;
userVisibleStage?: string | null;
reasonCode?: string | null;
explainability?: { message?: string | null } | null;
emailSupplement?: { status?: string | null } | null;
}
export interface ShippingOrderExtractionSelectionPlanState {
selectionVersion?: string | null;
maxInitialAttachments?: number;
@@ -143,6 +157,8 @@ export interface ShippingOrderExtractionState {
submissionOrdinal?: number | null;
/** 当前输入区短生命周期上下文;发送决策用,非业务主键 */
composerContextId?: string | null;
/** 同一次文件选择的聊天卡聚合键;绝不参与业务写入或任务路由。 */
uploadBatchId?: string | null;
/** Run 版本谱系;由后端投影,供历史消息只读隔离。 */
runNo?: string | null;
sourceRunNo?: string | null;
@@ -151,6 +167,7 @@ export interface ShippingOrderExtractionState {
readOnlyReason?: string | null;
summary: ShippingOrderExtractionStateSummary;
currentActivity?: ShippingOrderExtractionCurrentActivityState | null;
documents?: ShippingOrderExtractionFileState[];
selectionPlan?: ShippingOrderExtractionSelectionPlanState | null;
unitSummary?: ShippingOrderExtractionUnitSummaryState | null;
availableActions: string[];
@@ -343,6 +343,12 @@ export interface ShippingProcessingProjection {
primaryAction?: ShippingProcessingPrimaryAction | null;
/** 子状态事实字典(inventorySourceStatus / candidateSourceCodes / preparedSourceCodes / pendingSourceCodes / lineResolutions / exportState / uploadState / switchState)。 */
facts?: ShippingProcessingFacts;
/** EML Intake 的用户可见全局分组;由后端按子附件最高关注级别裁决。 */
userGroup?: 'failed' | 'waiting_human' | 'processing' | 'completed' | 'cancelled' | 'archived' | null;
/** 同一 EML Intake 的后端聚合摘要;子附件仍以 aggregate_children 保留在服务端。 */
aggregateSummary?: ConversationProcessingUserTask['aggregateSummary'];
/** EML Intake 聚合卡的真实子附件工作项;仅展示,不作为写操作目标。 */
aggregateChildren?: ShippingProcessingProjection[];
/** 旧 status 备份(T8 apply_user_projection_fields.legacy_status);调试用。 */
legacyStatus?: string | null;
/** 旧 stage 备份(T8 apply_user_projection_fields.legacy_stage);调试用。 */
@@ -581,8 +587,23 @@ export interface ConversationProcessingUserTask {
retryable?: boolean;
primaryAction?: ShippingProcessingPrimaryAction | null;
facts?: ShippingProcessingFacts;
/** EML Intake 的用户可见全局分组;前端只消费,不从附件状态自行推导。 */
userGroup?: ShippingProcessingProjection['userGroup'];
legacyStatus?: string | null;
legacyStage?: string | null;
/** 同一 EML Intake 聚合后的子任务状态,仅供展示,不作为写操作事实。 */
aggregateSummary?: {
intakeNo: string;
total: number;
completed: number;
processing: number;
needsAction: number;
failed: number;
stages: string[];
reasonCodes: string[];
} | null;
/** EML 聚合内的真实邮件/附件子项;仅用于展开明细展示。 */
aggregateChildren?: ShippingProcessingProjection[];
}
/**
@@ -625,6 +646,15 @@ export interface ConversationProcessingProjection {
/** 成功完成待查看;与 needs_action 异常态分离 */
completed?: ConversationProcessingUserTask[];
history: ConversationProcessingUserTask[];
/** 按 EML Intake 唯一归组后的六类用户状态;同一 EML 只允许出现一次。 */
status_groups?: {
failed: ConversationProcessingUserTask[];
waiting_human: ConversationProcessingUserTask[];
processing: ConversationProcessingUserTask[];
completed: ConversationProcessingUserTask[];
cancelled: ConversationProcessingUserTask[];
archived: ConversationProcessingUserTask[];
};
}
/**
@@ -1662,6 +1692,8 @@ export interface ShippingOrderExtractionEmailSupplementResult {
export interface ShippingOrderExtractionDocumentResult {
unit_id: number;
document_id: number;
intake_id?: number | null;
document_type?: string | null;
file_name?: string | null;
status: ShippingOrderExtractionDocumentStatus;
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
@@ -1718,6 +1750,8 @@ export interface ShippingOrderExtractionRun {
status: ShippingOrderExtractionRunStatus;
phase: string;
intake_nos: string[];
/** 同一次文件选择的展示聚合键;不是 user_task_no,不能用于业务写入。 */
upload_batch_id?: string | null;
schema_version_id: number;
schema_version?: number | null;
schema_checksum?: string | null;
@@ -1764,6 +1798,7 @@ export interface ShippingOrderExtractionRun {
technical_failure_reason_codes?: string[];
} | null;
current_activity?: ShippingOrderExtractionCurrentActivity | null;
documents?: ShippingOrderExtractionDocumentResult[];
available_actions: string[];
/** Run 级处理事项;聊天卡与右侧「本次处理」按类别展示。 */
handling_items?: Array<{
@@ -47,6 +47,13 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
retry_failed_attachments: 'retry',
retry_upload: 'retry',
retry_freight_upload_rpa: 'retry',
// 订单识别复核卡后端动作码:统一复用右侧「进入订单处理/重试解析/查看结果」执行器。
edit_draft: 'open_order_review',
reconcile_and_progress: 'open_order_review',
create_draft: 'open_order_review',
retry_stp_auto_create: 'retry',
reparse: 'retry',
view: 'view_result',
refresh: 'refresh',
regenerate_excel: 'regenerate_excel',
generate_excel: 'regenerate_excel',
@@ -189,7 +196,10 @@ export function resolveProcessingActionPresentation(
if (key === 'regenerate_manual_upload_todo') return;
if (seen.has(key)) return;
seen.add(key);
const intent = mapActionCodeToIntent(code);
// 识别/建单失败的 view 是进入当前 Case 处理;已完成任务才打开只读结果。
const intent = key === 'view' && NEEDS_ACTION_STATUSES.has(status)
? 'open_order_review'
: mapActionCodeToIntent(code);
if (!intent || intent === 'none') {
// [fail-closed] 未知动作不渲染原始码,仅告警。
warnUnregisteredWorkbenchAction({
@@ -290,7 +300,9 @@ export function resolveConversationTaskActionPresentation(
if (!code) return;
const key = code.toLowerCase();
if (seen.has(key)) return;
const intent = mapActionCodeToIntent(code);
const intent = key === 'view' && isNeedsAction
? 'open_order_review'
: mapActionCodeToIntent(code);
if (!intent || intent === 'none') return;
seen.add(key);
items.push(toItem(code, intent, surface));