refactor(agent, shipping): 简化代理模型并完善订单抽取业务
- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码 - 删除废弃的 AgentRuntimeBinding 模型及其依赖 - 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑 - 修复附件完整性检测、订单抽取状态映射问题 - 更新多语言错误文案与前端单元测试配置 - 清理平台配置中不再使用的暴露模式配置
This commit is contained in:
1 parent
1f3ecb87b7
commit
61ac6403c4
159 files changed
+12883
-5099
No files matched your search
@@ -44,7 +44,7 @@ export const hydrateShippingOrderExtractionState = (message: ChatMessage): ChatM
|
||||
const state = payload.shipping_order_extraction_state;
|
||||
if (!state || typeof state !== 'object') return message;
|
||||
const status = String((state as Record<string, unknown>).status || '');
|
||||
if (!['extracting', 'completed', 'partially_completed', 'failed'].includes(status)) return message;
|
||||
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) return message;
|
||||
message.shipping_order_extraction_state = state as ShippingOrderExtractionState;
|
||||
return message;
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ShippingBatchUiState,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingDecisionResponse,
|
||||
ShippingOrderExtractionDocumentsResponse,
|
||||
ShippingNoticeHeader,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeUploadResponse,
|
||||
@@ -160,6 +161,7 @@ export const createWorkspaceShippingOrderExtractionRun = (payload: {
|
||||
agent_id: number;
|
||||
conversation_id?: string | null;
|
||||
intake_nos: string[];
|
||||
upload_batch_id: string;
|
||||
}) => requestJson<ShippingOrderExtractionRunCreateResponse>(
|
||||
'/api/workspace/shipping-notice/order-extraction-runs',
|
||||
jsonPost(payload),
|
||||
@@ -192,6 +194,12 @@ export const reparseWorkspaceShippingOrderExtractionRun = (
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/** 获取当前订单抽取 Run 的按 PDF 归并详情。 */
|
||||
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) =>
|
||||
requestJson<ShippingOrderExtractionDocumentsResponse>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents`,
|
||||
);
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
@@ -686,12 +694,14 @@ export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
|
||||
export const createShippingNoticeIntake = (
|
||||
assetNo: string,
|
||||
conversationId?: string | null,
|
||||
uploadBatchId?: string,
|
||||
) => requestJson<ShippingNoticeIntakeResponse>('/api/workspace/shipping-notice/intakes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
asset_no: assetNo,
|
||||
conversation_id: conversationId || undefined,
|
||||
upload_batch_id: uploadBatchId || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -106,24 +106,47 @@ const attachmentUrlInput = ref('');
|
||||
|
||||
/**
|
||||
* 汇总 EML 附件解析进度,供输入栏徽标展示。
|
||||
* 核心逻辑:failed/empty/skipped/超限/文本预算耗尽计为问题;duplicate 单独提示,不记为失败。
|
||||
* 核心逻辑:阶段 1 仅展示快览结果;优先说明发现了多少附件,技术失败/目录不完整再退化为问题提示。
|
||||
*/
|
||||
function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachment): string {
|
||||
const summary = attachment.parseSummary;
|
||||
const total = Number(summary?.attachment_count || 0);
|
||||
const rows = summary?.attachments || [];
|
||||
// 兼容旧摘要:早期快览未标记签名图,按内嵌标记、目录原因和图片 MIME 一并排除。
|
||||
const businessRows = rows.filter((item) => {
|
||||
const mimeType = String(item.mime_type || '').toLowerCase();
|
||||
const catalogReason = String(item.catalog_reason || '').toLowerCase();
|
||||
return !item.is_inline_resource
|
||||
&& !mimeType.startsWith('image/')
|
||||
&& catalogReason !== 'signature_or_logo'
|
||||
&& catalogReason !== 'inline_resource';
|
||||
});
|
||||
const inlineCount = rows.length - businessRows.length;
|
||||
const total = Math.max(0, Number(summary?.attachment_count || 0) - inlineCount);
|
||||
const warnings = summary?.warnings || [];
|
||||
const hasBlockingWarning = warnings.some((w) => isBlockingWarning(String(w || '')));
|
||||
if (!total && !hasBlockingWarning && !rows.length) return '';
|
||||
if (!total && !hasBlockingWarning && !businessRows.length) return '';
|
||||
|
||||
const effectiveTotal = total || rows.length;
|
||||
const ok = rows.filter((item) => item.parse_status === 'parsed').length;
|
||||
const problematic = rows.filter((item) =>
|
||||
const effectiveTotal = total || businessRows.length;
|
||||
const ok = Number(summary?.ready_attachment_count || businessRows.filter((item) => item.ready_for_extraction).length);
|
||||
const problematic = businessRows.filter((item) =>
|
||||
['failed', 'empty', 'skipped'].includes(String(item.parse_status || '')),
|
||||
).length;
|
||||
const duplicates = rows.filter((item) => item.parse_status === 'duplicate').length;
|
||||
const overflow = Math.max(0, effectiveTotal - rows.length);
|
||||
const issues = problematic + overflow + (hasBlockingWarning && problematic === 0 && overflow === 0 ? 1 : 0);
|
||||
const duplicates = Number(
|
||||
summary?.duplicate_attachment_count
|
||||
|| businessRows.filter((item) => item.parse_status === 'duplicate').length,
|
||||
);
|
||||
const overflow = Math.max(0, effectiveTotal - businessRows.length);
|
||||
const previewStatus = String(summary?.preview_status || '').trim().toLowerCase();
|
||||
const issues = problematic
|
||||
+ overflow
|
||||
+ (hasBlockingWarning && problematic === 0 && overflow === 0 ? 1 : 0)
|
||||
+ (
|
||||
(summary?.technical_failure || previewStatus === 'technical_failed' || previewStatus === 'directory_incomplete')
|
||||
&& problematic === 0
|
||||
&& overflow === 0
|
||||
? 1
|
||||
: 0
|
||||
);
|
||||
|
||||
if (issues > 0) {
|
||||
return t('chat.shippingNoticeAttachmentHintPartial', {
|
||||
@@ -132,14 +155,11 @@ function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachmen
|
||||
failed: issues,
|
||||
});
|
||||
}
|
||||
if (attachment.layoutStatus === 'processing') {
|
||||
return t('chat.shippingNoticeAttachmentHintLayoutProcessing', { ok, total: effectiveTotal });
|
||||
}
|
||||
if (duplicates > 0) {
|
||||
return t('chat.shippingNoticeAttachmentHintWithDup', { ok, total: effectiveTotal, duplicates });
|
||||
return t('chat.shippingNoticeAttachmentHintDiscoveredWithDup', { total: effectiveTotal, duplicates });
|
||||
}
|
||||
if (!effectiveTotal) return '';
|
||||
return t('chat.shippingNoticeAttachmentHint', { ok, total: effectiveTotal });
|
||||
return t('chat.shippingNoticeAttachmentHintDiscovered', { total: effectiveTotal });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,20 +5,16 @@
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件与文字共用同一气泡,助手正文与特殊交互委托页面 handlers。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
CircleCheck,
|
||||
CircleX,
|
||||
Copy,
|
||||
Download,
|
||||
Edit2,
|
||||
Eye,
|
||||
LayoutGrid,
|
||||
LoaderCircle,
|
||||
MessageSquareText,
|
||||
RotateCw,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
@@ -33,14 +29,13 @@ import TrainingExamQuestionMessage, { type TrainingHandlers } from './TrainingEx
|
||||
import TrainingVideoMessage from './TrainingVideoMessage.vue';
|
||||
import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
|
||||
import TrainingResultCard from './TrainingResultCard.vue';
|
||||
import ShippingOrderExtractionCard from '../shipping/ShippingOrderExtractionCard.vue';
|
||||
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
|
||||
import type { ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { ShippingNoticePendingAttachment } from '../../types/shipping.types';
|
||||
import type { ShippingOrderExtractionReviewAttachment } from '../../types/chat.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
import { listWorkspaceShippingOrderExtractionProgressEvents } from '../../api/shipping.api';
|
||||
import type { ShippingOrderExtractionProgressEvent } from '../../types/shipping.api.types';
|
||||
|
||||
export interface ChatMessageBubbleHandlers {
|
||||
renderMarkdown: (text: string) => string;
|
||||
@@ -142,12 +137,7 @@ const showShippingActionsPanel = computed(() =>
|
||||
);
|
||||
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
|
||||
const retryingOrderExtraction = ref(false);
|
||||
const showOrderExtractionDetails = ref(false);
|
||||
const orderExtractionEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
const loadingOrderExtractionEvents = ref(false);
|
||||
const orderExtractionEventsError = ref(false);
|
||||
const orderExtractionClock = ref(Date.now());
|
||||
let orderExtractionClockTimer: ReturnType<typeof setInterval> | null = null;
|
||||
const reviewAttachmentsSection = ref<HTMLElement | null>(null);
|
||||
const shippingOrderExtractionRunNo = computed(() => {
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
@@ -211,89 +201,11 @@ const retryShippingOrderExtraction = async () => {
|
||||
retryingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const shippingOrderExtractionTitleKey = computed(() => {
|
||||
switch (shippingOrderExtractionState.value?.status) {
|
||||
case 'completed': return 'chat.shippingOrderExtractionCompleted';
|
||||
case 'partially_completed': return 'chat.shippingOrderExtractionPartiallyCompleted';
|
||||
case 'failed': return 'chat.shippingOrderExtractionFailed';
|
||||
default: return 'chat.shippingOrderExtractionProcessing';
|
||||
}
|
||||
});
|
||||
const shippingOrderExtractionFailureHintKey = computed(() => (
|
||||
shippingOrderExtractionState.value?.status === 'failed'
|
||||
? 'chat.shippingOrderExtractionFailureHint'
|
||||
: ''
|
||||
));
|
||||
const shippingOrderExtractionStageKey = computed(() => {
|
||||
const code = String(shippingOrderExtractionState.value?.current_stage_code || '').trim();
|
||||
const known = new Set(['queued', 'workflow_accepted', 'document_processing', 'order_recognition', 'result_processing', 'provider_result_ready', 'hxops_persistence', 'auto_recovering', 'generic_processing']);
|
||||
return known.has(code) ? `chat.shippingOrderExtractionStage.${code}` : 'chat.shippingOrderExtractionProcessing';
|
||||
});
|
||||
const orderExtractionElapsedSeconds = computed(() => {
|
||||
const raw = shippingOrderExtractionState.value?.started_at;
|
||||
const started = raw ? Date.parse(raw) : NaN;
|
||||
if (!Number.isFinite(started)) return null;
|
||||
return Math.max(0, Math.floor((orderExtractionClock.value - started) / 1000));
|
||||
});
|
||||
|
||||
/**
|
||||
* 识别运行时刷新纯展示时钟,避免网络轮询间隔或无状态变化时运行时长停滞。
|
||||
* 仅在当前消息处于识别中时启动;后台 Run 的真实健康状态仍完全由服务端计算。
|
||||
*/
|
||||
watch(
|
||||
() => shippingOrderExtractionState.value?.status,
|
||||
(status) => {
|
||||
if (orderExtractionClockTimer) {
|
||||
clearInterval(orderExtractionClockTimer);
|
||||
orderExtractionClockTimer = null;
|
||||
}
|
||||
if (status === 'extracting') {
|
||||
orderExtractionClock.value = Date.now();
|
||||
orderExtractionClockTimer = setInterval(() => {
|
||||
orderExtractionClock.value = Date.now();
|
||||
}, 1000);
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (orderExtractionClockTimer) clearInterval(orderExtractionClockTimer);
|
||||
});
|
||||
const toggleOrderExtractionDetails = async () => {
|
||||
if (!shippingOrderExtractionRunNo.value) return;
|
||||
showOrderExtractionDetails.value = !showOrderExtractionDetails.value;
|
||||
if (!showOrderExtractionDetails.value || orderExtractionEvents.value.length || loadingOrderExtractionEvents.value) return;
|
||||
loadingOrderExtractionEvents.value = true;
|
||||
orderExtractionEventsError.value = false;
|
||||
try {
|
||||
const { items } = await listWorkspaceShippingOrderExtractionProgressEvents(shippingOrderExtractionRunNo.value);
|
||||
orderExtractionEvents.value = items;
|
||||
} catch {
|
||||
// 详情加载失败不影响 Run 短轮询或后台订单识别,只给出可理解的局部提示。
|
||||
orderExtractionEventsError.value = true;
|
||||
} finally {
|
||||
loadingOrderExtractionEvents.value = false;
|
||||
}
|
||||
const enterOrderExtractionManualReview = async () => {
|
||||
if (!shippingOrderExtractionReviewAttachments.value.length) return;
|
||||
await nextTick();
|
||||
reviewAttachmentsSection.value?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
};
|
||||
|
||||
/** 将服务端脱敏事件时间格式化为用户本地时间;无效值不伪造时间。 */
|
||||
const formatOrderExtractionEventTime = (value: string): string => {
|
||||
const timestamp = Date.parse(value);
|
||||
return Number.isFinite(timestamp) ? new Date(timestamp).toLocaleTimeString() : '';
|
||||
};
|
||||
|
||||
/** 把固定的阶段生命周期状态映射为本地化文案键,未知值使用中性兜底。 */
|
||||
const shippingOrderExtractionEventStatusKey = (status: string): string => {
|
||||
const known = new Set(['started', 'running', 'completed', 'failed', 'recovered']);
|
||||
return known.has(status) ? `chat.shippingOrderExtractionEventStatus.${status}` : 'chat.shippingOrderExtractionEventStatus.updated';
|
||||
};
|
||||
const showShippingOrderExtractionMessage = computed(() => {
|
||||
const stateMessage = String(shippingOrderExtractionState.value?.message || '').trim();
|
||||
const assistantContent = String(message.content || '').trim();
|
||||
return !!stateMessage && stateMessage !== assistantContent && !assistantContent.includes(stateMessage);
|
||||
});
|
||||
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
@@ -816,128 +728,19 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
<div v-if="hasUserContent" class="whitespace-pre-wrap px-2.5 py-1">{{ message.content }}</div>
|
||||
</template>
|
||||
<div v-else>
|
||||
<div
|
||||
<ShippingOrderExtractionCard
|
||||
v-if="shippingOrderExtractionState"
|
||||
class="mb-3 flex min-h-[60px] items-start gap-3 rounded-lg border px-3.5 py-3"
|
||||
:class="{
|
||||
'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100': shippingOrderExtractionState.status === 'extracting',
|
||||
'border-emerald-200 bg-emerald-50/80 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100': shippingOrderExtractionState.status === 'completed',
|
||||
'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100': shippingOrderExtractionState.status === 'partially_completed',
|
||||
'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100': shippingOrderExtractionState.status === 'failed',
|
||||
}"
|
||||
:state="shippingOrderExtractionState"
|
||||
:run-no="shippingOrderExtractionRunNo"
|
||||
:has-review-attachments="shippingOrderExtractionReviewAttachments.length > 0"
|
||||
@retry="retryShippingOrderExtraction"
|
||||
@enter-manual-review="enterOrderExtractionManualReview"
|
||||
/>
|
||||
<div
|
||||
v-if="shippingOrderExtractionReviewAttachments.length"
|
||||
ref="reviewAttachmentsSection"
|
||||
class="mb-3 space-y-2"
|
||||
>
|
||||
<LoaderCircle
|
||||
v-if="shippingOrderExtractionState.status === 'extracting'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck
|
||||
v-else-if="shippingOrderExtractionState.status === 'completed'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
/>
|
||||
<TriangleAlert
|
||||
v-else-if="shippingOrderExtractionState.status === 'partially_completed'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
/>
|
||||
<CircleX v-else class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-semibold">{{ $t(shippingOrderExtractionTitleKey) }}</div>
|
||||
<template v-if="shippingOrderExtractionState.status === 'extracting'">
|
||||
<div class="mt-1 text-xs opacity-80">{{ $t(shippingOrderExtractionStageKey) }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-x-2 text-xs opacity-70">
|
||||
<span v-if="orderExtractionElapsedSeconds !== null">
|
||||
{{ $t('chat.shippingOrderExtractionElapsed', { seconds: orderExtractionElapsedSeconds }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.health === 'slow'">
|
||||
{{ $t('chat.shippingOrderExtractionSlow') }}
|
||||
</span>
|
||||
<span v-else-if="shippingOrderExtractionState.health === 'idle'">
|
||||
{{ $t('chat.shippingOrderExtractionIdle') }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
<div
|
||||
data-testid="shipping-order-extraction-progress"
|
||||
class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-black/10 dark:bg-white/15"
|
||||
role="progressbar"
|
||||
:aria-label="$t(shippingOrderExtractionTitleKey)"
|
||||
aria-valuemin="0"
|
||||
aria-valuemax="100"
|
||||
:aria-valuenow="shippingOrderExtractionState.terminal ? 100 : undefined"
|
||||
:aria-busy="shippingOrderExtractionState.status === 'extracting'"
|
||||
>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState.status === 'extracting'"
|
||||
class="shipping-order-extraction-indeterminate h-full w-2/5 rounded-full bg-sky-500"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="h-full w-full rounded-full"
|
||||
:class="{
|
||||
'bg-emerald-500': shippingOrderExtractionState.status === 'completed',
|
||||
'bg-amber-500': shippingOrderExtractionState.status === 'partially_completed',
|
||||
'bg-rose-500': shippingOrderExtractionState.status === 'failed',
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState.terminal"
|
||||
class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs"
|
||||
>
|
||||
<span v-if="shippingOrderExtractionState.created_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionCreatedCount', { count: shippingOrderExtractionState.created_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.opened_existing_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionOpenedExistingCount', { count: shippingOrderExtractionState.opened_existing_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.pending_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionPendingCount', { count: shippingOrderExtractionState.pending_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.non_shipping_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionIgnoredCount', { count: shippingOrderExtractionState.non_shipping_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.created_with_missing_fields_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionMissingFieldsCount', { count: shippingOrderExtractionState.created_with_missing_fields_count }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="shippingOrderExtractionFailureHintKey" class="mt-1 break-words text-xs opacity-80">
|
||||
{{ $t(shippingOrderExtractionFailureHintKey) }}
|
||||
</div>
|
||||
<div v-else-if="showShippingOrderExtractionMessage" class="mt-1 break-words text-xs opacity-80">
|
||||
{{ shippingOrderExtractionState.message }}
|
||||
</div>
|
||||
<button
|
||||
v-if="shippingOrderExtractionRunNo"
|
||||
type="button"
|
||||
class="mt-2 text-xs font-medium underline underline-offset-2 opacity-80 hover:opacity-100"
|
||||
@click="toggleOrderExtractionDetails"
|
||||
>
|
||||
{{ $t(showOrderExtractionDetails ? 'chat.shippingOrderExtractionHideDetails' : 'chat.shippingOrderExtractionShowDetails') }}
|
||||
</button>
|
||||
<div v-if="showOrderExtractionDetails" class="mt-2 space-y-1 border-t border-current/15 pt-2 text-xs opacity-85">
|
||||
<div v-if="loadingOrderExtractionEvents">{{ $t('chat.shippingOrderExtractionLoadingDetails') }}</div>
|
||||
<div v-else-if="orderExtractionEventsError">{{ $t('chat.shippingOrderExtractionDetailsUnavailable') }}</div>
|
||||
<div v-else-if="orderExtractionEvents.length === 0">{{ $t('chat.shippingOrderExtractionNoDetails') }}</div>
|
||||
<div v-for="event in orderExtractionEvents" :key="`${event.stage_code}:${event.occurred_at}`">
|
||||
<span>{{ $t(`chat.shippingOrderExtractionStage.${event.stage_code}`) }}</span>
|
||||
<span class="ml-1 opacity-75">{{ $t(shippingOrderExtractionEventStatusKey(event.status)) }}</span>
|
||||
<time v-if="formatOrderExtractionEventTime(event.occurred_at)" class="ml-1 opacity-65">
|
||||
{{ formatOrderExtractionEventTime(event.occurred_at) }}
|
||||
</time>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-if="shippingOrderExtractionState.status === 'failed' && shippingOrderExtractionRunNo"
|
||||
type="button"
|
||||
class="mt-3 inline-flex items-center gap-1.5 rounded-md border border-rose-300 bg-white/75 px-3 py-1.5 text-xs font-medium text-rose-700 transition hover:bg-white disabled:cursor-not-allowed disabled:opacity-60 dark:border-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
|
||||
:disabled="retryingOrderExtraction"
|
||||
@click="retryShippingOrderExtraction"
|
||||
>
|
||||
<RotateCw class="h-3.5 w-3.5" :class="{ 'animate-spin': retryingOrderExtraction }" />
|
||||
{{ $t(retryingOrderExtraction ? 'chat.shippingOrderExtractionRetrying' : 'chat.shippingOrderExtractionRetry') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="shippingOrderExtractionReviewAttachments.length" class="mb-3 space-y-2">
|
||||
<ShippingNoticeCandidateReview
|
||||
v-for="attachment in shippingOrderExtractionReviewAttachments"
|
||||
:key="attachment.intakeNo"
|
||||
@@ -1348,28 +1151,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.shipping-order-extraction-indeterminate {
|
||||
animation: shipping-order-extraction-progress 1.25s ease-in-out infinite;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
@keyframes shipping-order-extraction-progress {
|
||||
from {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateX(250%);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.shipping-order-extraction-indeterminate {
|
||||
animation: none;
|
||||
transform: translateX(75%);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.chat-markdown) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderDocumentResultItem.vue
|
||||
* 用途:渲染单个 PDF 的订单抽取结果摘要,供详情抽屉按文档逐项展示。
|
||||
* 依赖:订单抽取文档 DTO、vue-i18n。
|
||||
* 逻辑:只显示用户可理解的业务字段;人工复核入口复用现有候选审核区,不直接暴露内部证据细节。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleCheck, CircleX, FileText, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import type { ShippingOrderExtractionDocumentResult } from '../../types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
document: ShippingOrderExtractionDocumentResult;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const statusTone = computed(() => {
|
||||
switch (props.document.status) {
|
||||
case 'candidate_ready':
|
||||
return 'border-emerald-200 bg-emerald-50/70 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/25 dark:text-emerald-100';
|
||||
case 'review_required':
|
||||
return 'border-amber-200 bg-amber-50/70 text-amber-950 dark:border-amber-800 dark:bg-amber-950/25 dark:text-amber-100';
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
return 'border-rose-200 bg-rose-50/70 text-rose-900 dark:border-rose-800 dark:bg-rose-950/25 dark:text-rose-100';
|
||||
default:
|
||||
return 'border-slate-200 bg-slate-50/70 text-slate-900 dark:border-slate-700 dark:bg-slate-900/40 dark:text-slate-100';
|
||||
}
|
||||
});
|
||||
|
||||
const statusLabel = computed(() => t(`chat.shippingOrderExtractionDocumentStatus.${props.document.status}`));
|
||||
const reasonLabel = computed(() => (
|
||||
props.document.reason_code
|
||||
? t(`chat.shippingOrderExtractionReason.${props.document.reason_code}`)
|
||||
: ''
|
||||
));
|
||||
const emailSupplementLabel = computed(() => {
|
||||
const status = props.document.email_supplement?.status || 'none';
|
||||
const key = `chat.shippingOrderExtractionEmailSupplement.${status}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderExtractionEmailSupplement.none');
|
||||
});
|
||||
const emailSupplementRelations = computed(() => (
|
||||
(props.document.email_supplement?.relation_codes || [])
|
||||
.map((code) => {
|
||||
const key = `chat.shippingOrderExtractionEmailSupplementRelation.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
})
|
||||
));
|
||||
const reservationStatusLabel = computed(() => {
|
||||
const key = `chat.shippingOrderExtractionEmailSupplementFieldStatus.${props.document.email_supplement?.reservation_id_status || 'none'}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderExtractionEmailSupplementFieldStatus.none');
|
||||
});
|
||||
const sourceTypeStatusLabel = computed(() => {
|
||||
const key = `chat.shippingOrderExtractionEmailSupplementFieldStatus.${props.document.email_supplement?.source_type_status || 'none'}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderExtractionEmailSupplementFieldStatus.none');
|
||||
});
|
||||
const retryStatusLabel = computed(() => {
|
||||
const status = String(props.document.retry_status || '').trim();
|
||||
const key = `chat.shippingOrderExtractionRetryStatus.${status}`;
|
||||
return status && te(key) ? t(key) : '';
|
||||
});
|
||||
const budgetCostLabel = computed(() => {
|
||||
if (!props.document.budget_cost) return '';
|
||||
return t('chat.shippingOrderExtractionBudgetCost', {
|
||||
attachments: props.document.budget_cost.initial_attachment_budget || 0,
|
||||
concurrency: props.document.budget_cost.initial_concurrency_budget || 0,
|
||||
selected: props.document.budget_cost.selected_in_batch || 0,
|
||||
});
|
||||
});
|
||||
const reviewDetails = computed(() => props.document.review_details || []);
|
||||
const reviewFieldLabel = (fieldCode: string | null | undefined): string => {
|
||||
const key = `chat.shippingOrderExtractionReviewField.${fieldCode || ''}`;
|
||||
return fieldCode && te(key) ? t(key) : (fieldCode || t('chat.shippingOrderExtractionReviewField.unknown'));
|
||||
};
|
||||
|
||||
const canEnterManualReview = computed(() => (
|
||||
props.hasReviewAttachments
|
||||
&& props.document.available_actions.some((action) => action === 'review_candidate' || action === 'manual_review')
|
||||
));
|
||||
const canViewEvidence = computed(() => (
|
||||
props.hasReviewAttachments
|
||||
&& props.document.available_actions.includes('view_evidence')
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="rounded-lg border p-3" :class="statusTone">
|
||||
<div class="flex items-start gap-2">
|
||||
<LoaderCircle
|
||||
v-if="['pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'].includes(document.status)"
|
||||
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck v-else-if="document.status === 'candidate_ready'" class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<TriangleAlert v-else-if="document.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="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<div class="truncate text-sm font-semibold">{{ document.file_name || t('chat.shippingOrderExtractionUnknownDocument') }}</div>
|
||||
<span class="rounded-full bg-black/10 px-2 py-0.5 text-[11px] dark:bg-white/10">{{ statusLabel }}</span>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs opacity-85">
|
||||
<span v-if="document.selection_batch">
|
||||
{{ t('chat.shippingOrderExtractionSelectionBatch', { batch: document.selection_batch }) }}
|
||||
</span>
|
||||
<span v-if="document.group_key">
|
||||
{{ t('chat.shippingOrderExtractionGroupKey', { key: document.group_key }) }}
|
||||
</span>
|
||||
<span v-if="document.po_number">
|
||||
{{ t('chat.shippingOrderExtractionPoNumber', { value: document.po_number }) }}
|
||||
</span>
|
||||
<span v-if="document.line_count > 0">
|
||||
{{ t('chat.shippingOrderExtractionLineCount', { count: document.line_count }) }}
|
||||
</span>
|
||||
<span v-if="document.profile">
|
||||
{{ t('chat.shippingOrderExtractionProfileSummary', {
|
||||
name: document.profile.name || document.profile.code,
|
||||
version: document.profile.version,
|
||||
}) }}
|
||||
</span>
|
||||
<span>
|
||||
{{ emailSupplementLabel }}
|
||||
</span>
|
||||
<span>
|
||||
{{ t('chat.shippingOrderExtractionEmailSupplementField.reservation') }}{{ reservationStatusLabel }}
|
||||
</span>
|
||||
<span>
|
||||
{{ t('chat.shippingOrderExtractionEmailSupplementField.sourceType') }}{{ sourceTypeStatusLabel }}
|
||||
</span>
|
||||
<span v-for="relation in emailSupplementRelations" :key="relation">
|
||||
{{ relation }}
|
||||
</span>
|
||||
<span v-if="document.email_supplement.conflict_count > 0">
|
||||
{{ t('chat.shippingOrderExtractionEmailSupplementConflictCount', { count: document.email_supplement.conflict_count }) }}
|
||||
</span>
|
||||
<span v-if="retryStatusLabel">
|
||||
{{ retryStatusLabel }}
|
||||
</span>
|
||||
<span v-if="budgetCostLabel">
|
||||
{{ budgetCostLabel }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="reasonLabel" class="mt-2 text-xs font-medium opacity-90">
|
||||
{{ reasonLabel }}
|
||||
</div>
|
||||
<ul v-if="reviewDetails.length" class="mt-2 space-y-1 text-xs font-medium opacity-90">
|
||||
<li v-for="detail in reviewDetails" :key="`${detail.line_number}-${detail.field_code || 'general'}`">
|
||||
{{ t('chat.shippingOrderExtractionReviewDetail', {
|
||||
line: detail.line_number,
|
||||
field: reviewFieldLabel(detail.field_code),
|
||||
}) }}
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="document.status === 'failed'" class="mt-1 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionTechnicalFailureUserHint') }}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="canViewEvidence"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="emit('enterManualReview')"
|
||||
>
|
||||
<FileText class="h-3.5 w-3.5" />
|
||||
{{ t('chat.shippingOrderExtractionAction.view_evidence') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canEnterManualReview"
|
||||
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"
|
||||
@click="emit('enterManualReview')"
|
||||
>
|
||||
{{ t(`chat.shippingOrderExtractionAction.${document.available_actions.includes('review_candidate') ? 'review_candidate' : 'manual_review'}`) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,422 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts
|
||||
* 用途:覆盖订单解析摘要卡、详情抽屉和单 PDF 结果项的关键交互。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、本域组件与 DTO 类型。
|
||||
* 逻辑:验证按钮由后端 available_actions 驱动,详情抽屉按需加载并支持键盘关闭。
|
||||
*/
|
||||
import { nextTick } from 'vue';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderDocumentResultItem from './ShippingOrderDocumentResultItem.vue';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listDocuments: vi.fn(),
|
||||
listProgressEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../api/shipping.api', () => ({
|
||||
listWorkspaceShippingOrderExtractionDocuments: api.listDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents: api.listProgressEvents,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: chatZhCn,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const flushUi = async () => {
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): ShippingOrderExtractionState => ({
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
currentActivity: {
|
||||
unitId: 12,
|
||||
fileName: 'PO-450003.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
terminal: false,
|
||||
refreshFailed: false,
|
||||
errorCode: null,
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
...patch,
|
||||
});
|
||||
|
||||
const buildDocument = (
|
||||
patch: Partial<ShippingOrderExtractionDocumentResult> = {},
|
||||
): ShippingOrderExtractionDocumentResult => ({
|
||||
unit_id: 11,
|
||||
document_id: 85,
|
||||
file_name: 'PO-450001.pdf',
|
||||
status: 'candidate_ready',
|
||||
po_number: '450001',
|
||||
line_count: 4,
|
||||
profile: {
|
||||
code: 'vendor_a_po',
|
||||
name: 'Vendor A Purchase Order',
|
||||
version: 2,
|
||||
},
|
||||
email_supplement: {
|
||||
status: 'merged',
|
||||
relation_codes: ['po_mpn'],
|
||||
conflict_count: 0,
|
||||
reservation_id_status: 'merged',
|
||||
source_type_status: 'unavailable',
|
||||
},
|
||||
reason_code: null,
|
||||
available_actions: ['view_evidence', 'review_candidate'],
|
||||
...patch,
|
||||
});
|
||||
|
||||
const buildProgressEvent = (
|
||||
patch: Partial<ShippingOrderExtractionProgressEvent> = {},
|
||||
): ShippingOrderExtractionProgressEvent => ({
|
||||
event_code: 'expansion_wave_started',
|
||||
status: 'completed',
|
||||
unit_id: null,
|
||||
document_id: null,
|
||||
reason_code: null,
|
||||
summary: {
|
||||
selection_batch: 2,
|
||||
reason_codes: ['required_field_missing'],
|
||||
},
|
||||
occurred_at: '2026-07-28T10:30:00Z',
|
||||
...patch,
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('loads documents once when opening details from server actions', async () => {
|
||||
api.listDocuments.mockResolvedValue({ items: [buildDocument()] });
|
||||
api.listProgressEvents.mockResolvedValue({ items: [buildProgressEvent()] });
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
selectionPlan: {
|
||||
maxInitialAttachments: 2,
|
||||
maxInitialConcurrency: 2,
|
||||
expansionBatchSize: 2,
|
||||
maxTotalAttachments: 6,
|
||||
totalAttachmentCount: 5,
|
||||
eligibleAttachmentCount: 3,
|
||||
selectedAttachmentCount: 2,
|
||||
plannedAttachmentCount: 3,
|
||||
pendingExpansionAttachmentCount: 1,
|
||||
pendingExpansionBatches: { '2': 1 },
|
||||
skippedAttachmentCount: 3,
|
||||
duplicateAttachmentCount: 1,
|
||||
budgetLimitedAttachmentCount: 1,
|
||||
groupCount: 2,
|
||||
},
|
||||
unitSummary: {
|
||||
totalUnits: 2,
|
||||
selectedUnits: 2,
|
||||
retryingUnits: 1,
|
||||
pendingRetryUnits: 0,
|
||||
failedUnits: 0,
|
||||
reviewRequiredUnits: 0,
|
||||
succeededUnits: 0,
|
||||
selectionBatches: { '1': 2 },
|
||||
reviewRequiredReasonCodes: ['required_field_missing'],
|
||||
expansionTriggerReasonCodes: ['missing_reservation_id'],
|
||||
technicalFailureReasonCodes: [],
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-001',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const detailButton = wrapper.findAll('button').find((item) => item.text().includes('查看处理详情'));
|
||||
expect(detailButton).toBeTruthy();
|
||||
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(1);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(1);
|
||||
expect(api.listDocuments).toHaveBeenCalledWith('SNER-001');
|
||||
expect(api.listProgressEvents).toHaveBeenCalledWith('SNER-001');
|
||||
expect(wrapper.text()).toContain('处理详情');
|
||||
expect(wrapper.text()).toContain('运行时间线');
|
||||
expect(wrapper.text()).toContain('系统已开始分析下一轮候选附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).toContain('PO-450001.pdf');
|
||||
expect(wrapper.text()).toContain('本轮从 5 个附件中规划 2 个订单组');
|
||||
expect(wrapper.text()).toContain('已选 2 个附件');
|
||||
expect(wrapper.text()).toContain('待扩展 1 个附件');
|
||||
expect(wrapper.text()).toContain('预算受限 1 个');
|
||||
expect(wrapper.text()).toContain('技术重试 1 个');
|
||||
expect(wrapper.text()).toContain('待复核原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).toContain('扩批触发:仍缺少 Reservation 字段,需要后续附件补证。');
|
||||
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(1);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('emits manual review directly when attachments are already available', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
availableActions: ['enter_manual_review'],
|
||||
}),
|
||||
runNo: 'SNER-002',
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const reviewButton = wrapper.findAll('button').find((item) => item.text().includes('进入人工复核'));
|
||||
expect(reviewButton).toBeTruthy();
|
||||
|
||||
await reviewButton!.trigger('click');
|
||||
|
||||
expect(wrapper.emitted('enterManualReview')).toHaveLength(1);
|
||||
expect(api.listDocuments).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments without mutating state locally', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'failed',
|
||||
terminal: true,
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 2,
|
||||
},
|
||||
currentActivity: null,
|
||||
availableActions: ['retry_failed_attachments'],
|
||||
}),
|
||||
runNo: 'SNER-003',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const retryButton = wrapper.findAll('button').find((item) => item.text().includes('重试失败附件'));
|
||||
expect(retryButton).toBeTruthy();
|
||||
|
||||
await retryButton!.trigger('click');
|
||||
|
||||
expect(wrapper.emitted('retry')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders run-level activity text without forcing an unknown file label', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
currentActivity: {
|
||||
unitId: 0,
|
||||
fileName: null,
|
||||
eventCode: 'plan_created',
|
||||
selectionBatch: 2,
|
||||
reasonCodes: ['required_field_missing'],
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-004',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('识别计划已创建,正在准备首轮附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).not.toContain('未命名 PDF');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionDetailsDrawer', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('closes on Escape when the drawer is open', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionDetailsDrawer, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
open: false,
|
||||
state: buildState({
|
||||
status: 'partially_completed',
|
||||
terminal: true,
|
||||
availableActions: ['view_details', 'enter_manual_review'],
|
||||
}),
|
||||
documents: [buildDocument()],
|
||||
progressEvents: [buildProgressEvent()],
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
await wrapper.setProps({ open: true });
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
await nextTick();
|
||||
|
||||
expect(wrapper.emitted('close')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders run timeline entries with batch and reason context', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
state: buildState(),
|
||||
documents: [buildDocument()],
|
||||
progressEvents: [buildProgressEvent()],
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('运行时间线');
|
||||
expect(wrapper.text()).toContain('业务复核');
|
||||
expect(wrapper.text()).toContain('系统已开始分析下一轮候选附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShippingOrderDocumentResultItem', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('renders business reason and server-declared actions for a review-required PDF', async () => {
|
||||
const wrapper = mount(ShippingOrderDocumentResultItem, {
|
||||
props: {
|
||||
document: buildDocument({
|
||||
status: 'review_required',
|
||||
reason_code: 'multiple_po_detected',
|
||||
po_number: null,
|
||||
line_count: 0,
|
||||
email_supplement: {
|
||||
status: 'conflict',
|
||||
relation_codes: ['po_mpn'],
|
||||
conflict_count: 2,
|
||||
reservation_id_status: 'conflict',
|
||||
source_type_status: 'none',
|
||||
},
|
||||
available_actions: ['view_evidence', 'manual_review'],
|
||||
}),
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('需要人工复核');
|
||||
expect(wrapper.text()).toContain('一份 PDF 中检测到多个不同 PO');
|
||||
expect(wrapper.text()).toContain('正文冲突 2 项');
|
||||
|
||||
const actionButtons = wrapper.findAll('button');
|
||||
expect(actionButtons.map((item) => item.text())).toEqual(
|
||||
expect.arrayContaining(['查看证据', '人工复核']),
|
||||
);
|
||||
|
||||
await actionButtons[0].trigger('click');
|
||||
|
||||
expect(wrapper.emitted('enterManualReview')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders a user-safe retry hint rather than a technical failure code for a failed attachment', async () => {
|
||||
const wrapper = mount(ShippingOrderDocumentResultItem, {
|
||||
props: {
|
||||
document: buildDocument({
|
||||
status: 'failed',
|
||||
reason_code: 'technical_failure',
|
||||
selection_batch: 2,
|
||||
group_key: 'PO-GRP-02',
|
||||
retry_status: 'failed',
|
||||
technical_failure_reason_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
budget_cost: {
|
||||
initial_attachment_budget: 2,
|
||||
initial_concurrency_budget: 2,
|
||||
selected_in_batch: 1,
|
||||
},
|
||||
available_actions: [],
|
||||
}),
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('选择批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('订单组:PO-GRP-02');
|
||||
expect(wrapper.text()).toContain('系统暂未完成处理,您可以稍后重试。');
|
||||
expect(wrapper.text()).toContain('首轮预算:附件 2 个,并发 2 个,本轮已选 1 个');
|
||||
expect(wrapper.text()).not.toContain('SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:渲染聊天中的订单抽取摘要卡,并在需要时打开 PDF 详情抽屉。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、documents API、详情抽屉。
|
||||
* 逻辑:卡片只显示 Run 汇总、当前活动和下一步动作;逐 PDF 结果与 Run 事实时间线延迟到抽屉内按需加载。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import {
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents,
|
||||
} from '../../api/shipping.api';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
state: ShippingOrderExtractionState;
|
||||
runNo?: string;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const detailsOpen = ref(false);
|
||||
const documents = ref<ShippingOrderExtractionDocumentResult[]>([]);
|
||||
const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
const loadingDocuments = ref(false);
|
||||
const documentsLoadFailed = ref(false);
|
||||
const documentsLoadedForRun = ref('');
|
||||
const loadingProgressEvents = ref(false);
|
||||
const progressEventsLoadFailed = ref(false);
|
||||
const progressEventsLoadedForRun = ref('');
|
||||
|
||||
watch(
|
||||
() => props.runNo,
|
||||
() => {
|
||||
detailsOpen.value = false;
|
||||
documents.value = [];
|
||||
progressEvents.value = [];
|
||||
loadingDocuments.value = false;
|
||||
loadingProgressEvents.value = false;
|
||||
documentsLoadFailed.value = false;
|
||||
progressEventsLoadFailed.value = false;
|
||||
documentsLoadedForRun.value = '';
|
||||
progressEventsLoadedForRun.value = '';
|
||||
},
|
||||
);
|
||||
|
||||
const toneClass = computed(() => {
|
||||
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';
|
||||
}
|
||||
});
|
||||
|
||||
const titleKey = computed(() => `chat.shippingOrderExtractionCardTitle.${props.state.status}`);
|
||||
const activityKey = computed(() => {
|
||||
const code = String(props.state.currentActivity?.eventCode || '').trim();
|
||||
const key = `chat.shippingOrderExtractionActivity.${code}`;
|
||||
return code && te(key) ? key : 'chat.shippingOrderExtractionActivity.generic_processing';
|
||||
});
|
||||
const completedLabel = computed(() => `${props.state.summary.completedDocuments} / ${props.state.summary.totalDocuments}`);
|
||||
const selectionSummaryItems = computed(() => {
|
||||
const selectionPlan = props.state.selectionPlan;
|
||||
const unitSummary = props.state.unitSummary;
|
||||
return [
|
||||
selectionPlan?.selectedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanSelected', { count: selectionPlan.selectedAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.pendingExpansionAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanPendingExpansion', { count: selectionPlan.pendingExpansionAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.skippedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanSkipped', { count: selectionPlan.skippedAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.budgetLimitedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanBudgetLimited', { count: selectionPlan.budgetLimitedAttachmentCount })
|
||||
: '',
|
||||
unitSummary?.retryingUnits
|
||||
? t('chat.shippingOrderExtractionPlanRetrying', { count: unitSummary.retryingUnits })
|
||||
: '',
|
||||
unitSummary?.failedUnits
|
||||
? t('chat.shippingOrderExtractionPlanTechnicalFailures', { count: unitSummary.failedUnits })
|
||||
: '',
|
||||
].filter(Boolean);
|
||||
});
|
||||
const selectionPlanHint = computed(() => {
|
||||
const selectionPlan = props.state.selectionPlan;
|
||||
if (!selectionPlan?.totalAttachmentCount) return '';
|
||||
return t('chat.shippingOrderExtractionPlanSummary', {
|
||||
total: selectionPlan.totalAttachmentCount,
|
||||
groups: selectionPlan.groupCount || 0,
|
||||
attachments: selectionPlan.maxInitialAttachments || 0,
|
||||
concurrency: selectionPlan.maxInitialConcurrency || 0,
|
||||
});
|
||||
});
|
||||
|
||||
const translateReasonCodes = (codes: string[] | undefined): string[] => (
|
||||
(codes || [])
|
||||
.map((code) => {
|
||||
const normalized = String(code || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderExtractionReason.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
})
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const reviewReasonSummary = computed(() => {
|
||||
const labels = translateReasonCodes(props.state.unitSummary?.reviewRequiredReasonCodes);
|
||||
return labels.length
|
||||
? t('chat.shippingOrderExtractionReviewReasonCodes', { codes: labels.join(' / ') })
|
||||
: '';
|
||||
});
|
||||
|
||||
const expansionTriggerSummary = computed(() => {
|
||||
const labels = translateReasonCodes(props.state.unitSummary?.expansionTriggerReasonCodes);
|
||||
return labels.length
|
||||
? t('chat.shippingOrderExtractionExpansionTriggerCodes', { codes: labels.join(' / ') })
|
||||
: '';
|
||||
});
|
||||
|
||||
const currentActivityContextSummary = computed(() => {
|
||||
const parts: string[] = [];
|
||||
const batch = Number(props.state.currentActivity?.selectionBatch || 0);
|
||||
if (batch > 0) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivitySelectionBatch', { batch }));
|
||||
}
|
||||
const labels = translateReasonCodes(props.state.currentActivity?.reasonCodes);
|
||||
if (labels.length) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivityReasonCodes', { codes: labels.join(' / ') }));
|
||||
}
|
||||
return parts.join(' · ');
|
||||
});
|
||||
|
||||
const openDetails = async () => {
|
||||
if (!props.runNo) return;
|
||||
detailsOpen.value = true;
|
||||
const tasks: Promise<void>[] = [];
|
||||
if (documentsLoadedForRun.value !== props.runNo && !loadingDocuments.value) {
|
||||
loadingDocuments.value = true;
|
||||
documentsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
listWorkspaceShippingOrderExtractionDocuments(props.runNo)
|
||||
.then((response) => {
|
||||
documents.value = response.items;
|
||||
documentsLoadedForRun.value = props.runNo || '';
|
||||
})
|
||||
.catch(() => {
|
||||
documentsLoadFailed.value = true;
|
||||
})
|
||||
.finally(() => {
|
||||
loadingDocuments.value = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (progressEventsLoadedForRun.value !== props.runNo && !loadingProgressEvents.value) {
|
||||
loadingProgressEvents.value = true;
|
||||
progressEventsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
listWorkspaceShippingOrderExtractionProgressEvents(props.runNo)
|
||||
.then((response) => {
|
||||
progressEvents.value = response.items;
|
||||
progressEventsLoadedForRun.value = props.runNo || '';
|
||||
})
|
||||
.catch(() => {
|
||||
progressEventsLoadFailed.value = true;
|
||||
})
|
||||
.finally(() => {
|
||||
loadingProgressEvents.value = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (tasks.length) {
|
||||
await Promise.all(tasks);
|
||||
}
|
||||
};
|
||||
|
||||
const handleActionClick = async (action: string) => {
|
||||
switch (action) {
|
||||
case 'view_details':
|
||||
await openDetails();
|
||||
return;
|
||||
case 'enter_manual_review':
|
||||
if (props.hasReviewAttachments) {
|
||||
emit('enterManualReview');
|
||||
} else {
|
||||
await openDetails();
|
||||
}
|
||||
return;
|
||||
case 'retry_failed_attachments':
|
||||
emit('retry');
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mb-3 rounded-lg border px-3.5 py-3" :class="toneClass">
|
||||
<div class="flex items-start gap-3">
|
||||
<LoaderCircle
|
||||
v-if="state.status === 'queued' || state.status === 'processing'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck v-else-if="state.status === 'completed'" class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<TriangleAlert
|
||||
v-else-if="state.status === 'partially_completed' || state.status === 'review_required'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
/>
|
||||
<CircleX v-else class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-semibold">{{ t(titleKey) }}</div>
|
||||
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs opacity-90">
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.completedProgress', { value: completedLabel }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.candidates', { count: state.summary.candidateCount }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}</span>
|
||||
<span v-if="state.summary.failedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="state.currentActivity?.fileName" class="mt-2 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionCurrentFile', { fileName: state.currentActivity.fileName || t('chat.shippingOrderExtractionUnknownDocument') }) }}
|
||||
</div>
|
||||
<div v-if="state.currentActivity" class="mt-1 text-xs opacity-80">
|
||||
{{ t(activityKey) }}
|
||||
</div>
|
||||
<div v-if="currentActivityContextSummary" class="mt-1 text-xs opacity-80">
|
||||
{{ currentActivityContextSummary }}
|
||||
</div>
|
||||
<div v-if="selectionPlanHint" class="mt-2 text-xs opacity-85">
|
||||
{{ selectionPlanHint }}
|
||||
</div>
|
||||
<div v-if="reviewReasonSummary" class="mt-2 text-xs opacity-85">
|
||||
{{ reviewReasonSummary }}
|
||||
</div>
|
||||
<div v-if="expansionTriggerSummary" class="mt-1 text-xs opacity-85">
|
||||
{{ expansionTriggerSummary }}
|
||||
</div>
|
||||
<div v-if="selectionSummaryItems.length" class="mt-2 flex flex-wrap gap-2 text-[11px] font-medium opacity-90">
|
||||
<span
|
||||
v-for="item in selectionSummaryItems"
|
||||
:key="item"
|
||||
class="rounded-full bg-black/10 px-2 py-0.5 dark:bg-white/10"
|
||||
>
|
||||
{{ item }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="state.refreshFailed" class="mt-2 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionRefreshFailed') }}
|
||||
</div>
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="action in state.availableActions"
|
||||
:key="action"
|
||||
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"
|
||||
@click="handleActionClick(action)"
|
||||
>
|
||||
{{ t(`chat.shippingOrderExtractionAction.${action}`) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingOrderExtractionDetailsDrawer
|
||||
:open="detailsOpen"
|
||||
:state="state"
|
||||
:documents="documents"
|
||||
:progress-events="progressEvents"
|
||||
:loading="loadingDocuments"
|
||||
:load-failed="documentsLoadFailed"
|
||||
:progress-loading="loadingProgressEvents"
|
||||
:progress-load-failed="progressEventsLoadFailed"
|
||||
:has-review-attachments="hasReviewAttachments"
|
||||
@close="detailsOpen = false"
|
||||
@enter-manual-review="emit('enterManualReview')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionDetailsDrawer.vue
|
||||
* 用途:以抽屉形式展示一次订单抽取 Run 的按 PDF 归并详情和事实时间线。
|
||||
* 依赖:订单抽取状态卡、文档结果项、订单抽取 progress-events DTO、vue-i18n。
|
||||
* 逻辑:聊天摘要卡只显示概览;需要查看逐文档结果和每轮事件原因时由本抽屉承接新的 Run 级事实时间线。
|
||||
*/
|
||||
import { onBeforeUnmount, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { X } from 'lucide-vue-next';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
import { classifyOrderExtractionTimelineEvent } from '../../shipping/orderExtractionTimeline';
|
||||
import ShippingOrderDocumentResultItem from './ShippingOrderDocumentResultItem.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
state: ShippingOrderExtractionState;
|
||||
documents: ShippingOrderExtractionDocumentResult[];
|
||||
progressEvents: ShippingOrderExtractionProgressEvent[];
|
||||
loading: boolean;
|
||||
loadFailed: boolean;
|
||||
progressLoading: boolean;
|
||||
progressLoadFailed: boolean;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te, locale } = useI18n();
|
||||
let removeKeydownListener: (() => void) | null = null;
|
||||
|
||||
const translateReasonCodes = (codes: string[] | undefined): string[] => (
|
||||
(codes || [])
|
||||
.map((code) => {
|
||||
const normalized = String(code || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderExtractionReason.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
})
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const eventActivityLabel = (event: ShippingOrderExtractionProgressEvent): string => {
|
||||
const key = `chat.shippingOrderExtractionActivity.${String(event.event_code || '').trim()}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderExtractionActivity.generic_processing');
|
||||
};
|
||||
|
||||
const eventOccurredAtLabel = (value: string | undefined): string => {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) return '';
|
||||
const date = new Date(raw);
|
||||
if (Number.isNaN(date.getTime())) return raw;
|
||||
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(date);
|
||||
};
|
||||
|
||||
const eventContextLabel = (event: ShippingOrderExtractionProgressEvent): string => {
|
||||
const summary = event.summary && typeof event.summary === 'object'
|
||||
? event.summary as Record<string, unknown>
|
||||
: {};
|
||||
const parts: string[] = [];
|
||||
const batch = Number(summary.selection_batch || 0);
|
||||
if (batch > 0) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivitySelectionBatch', { batch }));
|
||||
}
|
||||
const labels = translateReasonCodes([
|
||||
...(Array.isArray(summary.reason_codes) ? summary.reason_codes.map((item) => String(item || '').trim()) : []),
|
||||
String(event.reason_code || '').trim(),
|
||||
].filter(Boolean));
|
||||
if (labels.length) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivityReasonCodes', { codes: labels.join(' / ') }));
|
||||
}
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
const eventCategoryKey = (event: ShippingOrderExtractionProgressEvent): string =>
|
||||
`chat.shippingOrderExtractionTimelineTag.${classifyOrderExtractionTimelineEvent(event)}`;
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
removeKeydownListener?.();
|
||||
removeKeydownListener = null;
|
||||
if (!open) return;
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') emit('close');
|
||||
};
|
||||
window.addEventListener('keydown', handleKeydown);
|
||||
removeKeydownListener = () => window.removeEventListener('keydown', handleKeydown);
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
removeKeydownListener?.();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex justify-end bg-slate-950/40"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<aside
|
||||
class="flex h-full w-full max-w-[560px] flex-col bg-white shadow-2xl dark:bg-slate-900"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('chat.shippingOrderExtractionDetailsTitle')"
|
||||
>
|
||||
<header class="flex items-start justify-between border-b border-slate-200 px-4 py-3 dark:border-slate-800">
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-sm font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ t('chat.shippingOrderExtractionDetailsTitle') }}
|
||||
</h3>
|
||||
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-slate-600 dark:text-slate-300">
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.completed', { count: state.summary.completedDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}</span>
|
||||
<span v-if="state.selectionPlan?.selectedAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanSelected', { count: state.selectionPlan.selectedAttachmentCount }) }}
|
||||
</span>
|
||||
<span v-if="state.selectionPlan?.pendingExpansionAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanPendingExpansion', { count: state.selectionPlan.pendingExpansionAttachmentCount }) }}
|
||||
</span>
|
||||
<span v-if="state.selectionPlan?.budgetLimitedAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanBudgetLimited', { count: state.selectionPlan.budgetLimitedAttachmentCount }) }}
|
||||
</span>
|
||||
<span v-if="state.unitSummary?.retryingUnits">
|
||||
{{ t('chat.shippingOrderExtractionPlanRetrying', { count: state.unitSummary.retryingUnits }) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md p-1 text-slate-500 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-slate-100"
|
||||
:aria-label="t('chat.shippingOrderExtractionCloseDetails')"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="flex-1 space-y-3 overflow-y-auto px-4 py-4">
|
||||
<div
|
||||
v-if="state.selectionPlan?.totalAttachmentCount || state.unitSummary?.technicalFailureReasonCodes?.length"
|
||||
class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-3 text-xs text-slate-700 dark:border-slate-700 dark:bg-slate-900/60 dark:text-slate-200"
|
||||
>
|
||||
<div v-if="state.selectionPlan?.totalAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanSummary', {
|
||||
total: state.selectionPlan.totalAttachmentCount,
|
||||
groups: state.selectionPlan.groupCount || 0,
|
||||
attachments: state.selectionPlan.maxInitialAttachments || 0,
|
||||
concurrency: state.selectionPlan.maxInitialConcurrency || 0,
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.reviewRequiredReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionReviewReasonCodes', {
|
||||
codes: translateReasonCodes(state.unitSummary.reviewRequiredReasonCodes).join(' / '),
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.expansionTriggerReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionExpansionTriggerCodes', {
|
||||
codes: translateReasonCodes(state.unitSummary.expansionTriggerReasonCodes).join(' / '),
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.technicalFailureReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionTechnicalFailureCodes', {
|
||||
codes: state.unitSummary.technicalFailureReasonCodes.join(', '),
|
||||
}) }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-lg border border-slate-200 bg-white px-3 py-3 dark:border-slate-700 dark:bg-slate-950/40">
|
||||
<div class="text-xs font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ t('chat.shippingOrderExtractionTimelineTitle') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="progressLoading"
|
||||
class="mt-2 text-sm text-slate-600 dark:text-slate-300"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionTimelineLoading') }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="progressLoadFailed"
|
||||
class="mt-2 text-sm text-amber-700 dark:text-amber-200"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionTimelineUnavailable') }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="progressEvents.length === 0"
|
||||
class="mt-2 text-sm text-slate-600 dark:text-slate-300"
|
||||
>
|
||||
{{ 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>
|
||||
<div v-if="loading" class="rounded-lg border border-dashed border-slate-300 px-3 py-4 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderExtractionDocumentsLoading') }}
|
||||
</div>
|
||||
<div v-else-if="loadFailed" class="rounded-lg border border-amber-300 bg-amber-50 px-3 py-4 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-100">
|
||||
{{ t('chat.shippingOrderExtractionDocumentsUnavailable') }}
|
||||
</div>
|
||||
<div v-else-if="documents.length === 0" class="rounded-lg border border-dashed border-slate-300 px-3 py-4 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderExtractionNoDocuments') }}
|
||||
</div>
|
||||
<ShippingOrderDocumentResultItem
|
||||
v-for="document in documents"
|
||||
:key="document.unit_id"
|
||||
:document="document"
|
||||
:has-review-attachments="hasReviewAttachments"
|
||||
@enter-manual-review="emit('enterManualReview')"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -137,47 +137,81 @@ describe('useChat shipping_order_extraction_state SSE', () => {
|
||||
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
event: 'shipping_order_extraction_state',
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '正在识别邮件及附件中的订单',
|
||||
created_count: -1,
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 2,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 1,
|
||||
},
|
||||
currentActivity: {
|
||||
unitId: 12,
|
||||
fileName: 'PO-450001.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
},
|
||||
selectionPlan: {
|
||||
maxInitialAttachments: 2,
|
||||
pendingExpansionAttachmentCount: 1,
|
||||
},
|
||||
unitSummary: {
|
||||
reviewRequiredReasonCodes: ['required_field_missing'],
|
||||
expansionTriggerReasonCodes: ['missing_reservation_id'],
|
||||
technicalFailureReasonCodes: ['SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'],
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
terminal: false,
|
||||
});
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(message.shipping_order_extraction_state?.created_count).toBe(0);
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('processing');
|
||||
expect(message.shipping_order_extraction_state?.summary.processingDocuments).toBe(2);
|
||||
expect(message.shipping_order_extraction_state?.selectionPlan?.pendingExpansionAttachmentCount).toBe(1);
|
||||
expect(message.shipping_order_extraction_state?.unitSummary?.reviewRequiredReasonCodes).toEqual(['required_field_missing']);
|
||||
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
event: 'shipping_order_extraction_state',
|
||||
status: 'completed',
|
||||
phase: 'result_persisted',
|
||||
message: '已创建 1 个发货任务',
|
||||
created_count: 1,
|
||||
opened_existing_count: 2,
|
||||
pending_count: 0,
|
||||
non_shipping_count: 3,
|
||||
created_with_missing_fields_count: 1,
|
||||
batch_no: 'SB-STATE-001',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 3,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 3,
|
||||
},
|
||||
currentActivity: null,
|
||||
availableActions: ['view_details'],
|
||||
terminal: true,
|
||||
});
|
||||
|
||||
expect(message.content).toBe('Dify 最终正文保持不变');
|
||||
expect(message.shipping_order_extraction_state).toMatchObject({
|
||||
status: 'completed',
|
||||
created_count: 1,
|
||||
opened_existing_count: 2,
|
||||
non_shipping_count: 3,
|
||||
batch_no: 'SB-STATE-001',
|
||||
summary: {
|
||||
completedDocuments: 3,
|
||||
candidateCount: 3,
|
||||
},
|
||||
terminal: true,
|
||||
});
|
||||
expect((message.payload as Record<string, unknown>).existing_key).toBe('kept');
|
||||
expect((message.payload as { shipping_order_extraction_state?: { created_count?: number } })
|
||||
.shipping_order_extraction_state?.created_count).toBe(1);
|
||||
expect((message.payload as { shipping_order_extraction_state?: { summary?: { candidateCount?: number } } })
|
||||
.shipping_order_extraction_state?.summary?.candidateCount).toBe(3);
|
||||
|
||||
// 关键断言:网络重排导致的迟到进行态不能覆盖已经展示的终态。
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '迟到事件',
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
terminal: false,
|
||||
});
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('completed');
|
||||
@@ -196,14 +230,22 @@ describe('useChat shipping_order_extraction_state SSE', () => {
|
||||
payload: {
|
||||
shipping_order_extraction_state: {
|
||||
status: 'partially_completed',
|
||||
phase: 'result_persisted',
|
||||
message: '仍有 1 个订单需要补充信息',
|
||||
created_count: 1,
|
||||
opened_existing_count: 0,
|
||||
pending_count: 1,
|
||||
non_shipping_count: 0,
|
||||
created_with_missing_fields_count: 0,
|
||||
batch_no: 'SB-HISTORY-001',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 1,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
selectionPlan: {
|
||||
pendingExpansionAttachmentCount: 2,
|
||||
},
|
||||
unitSummary: {
|
||||
reviewRequiredReasonCodes: ['multiple_po_detected'],
|
||||
},
|
||||
availableActions: ['view_details', 'enter_manual_review'],
|
||||
terminal: true,
|
||||
},
|
||||
},
|
||||
@@ -212,7 +254,9 @@ describe('useChat shipping_order_extraction_state SSE', () => {
|
||||
hydrateShippingOrderExtractionState(message);
|
||||
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
|
||||
expect(message.shipping_order_extraction_state?.pending_count).toBe(1);
|
||||
expect(message.shipping_order_extraction_state?.batch_no).toBe('SB-HISTORY-001');
|
||||
expect(message.shipping_order_extraction_state?.summary.reviewRequiredDocuments).toBe(1);
|
||||
expect(message.shipping_order_extraction_state?.selectionPlan?.pendingExpansionAttachmentCount).toBe(2);
|
||||
expect(message.shipping_order_extraction_state?.unitSummary?.reviewRequiredReasonCodes).toEqual(['multiple_po_detected']);
|
||||
expect(message.shipping_order_extraction_state?.availableActions).toEqual(['view_details', 'enter_manual_review']);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
ChatMessageAttachment,
|
||||
ChatRun,
|
||||
RetrieverResource,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
@@ -166,9 +167,125 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
|
||||
};
|
||||
|
||||
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
|
||||
eventName === 'shipping_ui_state'
|
||||
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
|
||||
);
|
||||
|
||||
const normalizeShippingOrderExtractionState = (
|
||||
data: Record<string, unknown>,
|
||||
): ShippingOrderExtractionState | null => {
|
||||
const status = String(data.status || '').trim();
|
||||
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) {
|
||||
return null;
|
||||
}
|
||||
const rawSummary = data.summary && typeof data.summary === 'object'
|
||||
? data.summary as Record<string, unknown>
|
||||
: {};
|
||||
const rawActivity = data.currentActivity && typeof data.currentActivity === 'object'
|
||||
? data.currentActivity as Record<string, unknown>
|
||||
: null;
|
||||
const rawSelectionPlan = data.selectionPlan && typeof data.selectionPlan === 'object'
|
||||
? data.selectionPlan as Record<string, unknown>
|
||||
: null;
|
||||
const rawUnitSummary = data.unitSummary && typeof data.unitSummary === 'object'
|
||||
? data.unitSummary as Record<string, unknown>
|
||||
: null;
|
||||
return {
|
||||
status: status as ShippingOrderExtractionState['status'],
|
||||
summary: {
|
||||
totalDocuments: Math.max(0, Number(rawSummary.totalDocuments || 0)),
|
||||
pendingDocuments: Math.max(0, Number(rawSummary.pendingDocuments || 0)),
|
||||
processingDocuments: Math.max(0, Number(rawSummary.processingDocuments || 0)),
|
||||
completedDocuments: Math.max(0, Number(rawSummary.completedDocuments || 0)),
|
||||
reviewRequiredDocuments: Math.max(0, Number(rawSummary.reviewRequiredDocuments || 0)),
|
||||
failedDocuments: Math.max(0, Number(rawSummary.failedDocuments || 0)),
|
||||
candidateCount: Math.max(0, Number(rawSummary.candidateCount || 0)),
|
||||
},
|
||||
currentActivity: rawActivity
|
||||
? {
|
||||
unitId: Math.max(0, Number(rawActivity.unitId || 0)),
|
||||
fileName: String(rawActivity.fileName || '').trim() || null,
|
||||
eventCode: String(rawActivity.eventCode || '').trim(),
|
||||
selectionBatch: rawActivity.selectionBatch != null
|
||||
? Math.max(0, Number(rawActivity.selectionBatch || 0)) || null
|
||||
: null,
|
||||
reasonCodes: Array.isArray(rawActivity.reasonCodes)
|
||||
? rawActivity.reasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
selectionPlan: rawSelectionPlan
|
||||
? {
|
||||
selectionVersion: String(rawSelectionPlan.selectionVersion || '').trim() || null,
|
||||
maxInitialAttachments: Math.max(0, Number(rawSelectionPlan.maxInitialAttachments || 0)),
|
||||
maxInitialConcurrency: Math.max(0, Number(rawSelectionPlan.maxInitialConcurrency || 0)),
|
||||
expansionBatchSize: Math.max(0, Number(rawSelectionPlan.expansionBatchSize || 0)),
|
||||
maxTotalAttachments: Math.max(0, Number(rawSelectionPlan.maxTotalAttachments || 0)),
|
||||
totalAttachmentCount: Math.max(0, Number(rawSelectionPlan.totalAttachmentCount || 0)),
|
||||
eligibleAttachmentCount: Math.max(0, Number(rawSelectionPlan.eligibleAttachmentCount || 0)),
|
||||
selectedAttachmentCount: Math.max(0, Number(rawSelectionPlan.selectedAttachmentCount || 0)),
|
||||
plannedAttachmentCount: Math.max(0, Number(rawSelectionPlan.plannedAttachmentCount || 0)),
|
||||
pendingExpansionAttachmentCount: Math.max(0, Number(rawSelectionPlan.pendingExpansionAttachmentCount || 0)),
|
||||
pendingExpansionBatches: rawSelectionPlan.pendingExpansionBatches && typeof rawSelectionPlan.pendingExpansionBatches === 'object'
|
||||
? rawSelectionPlan.pendingExpansionBatches as Record<string, number>
|
||||
: {},
|
||||
skippedAttachmentCount: Math.max(0, Number(rawSelectionPlan.skippedAttachmentCount || 0)),
|
||||
duplicateAttachmentCount: Math.max(0, Number(rawSelectionPlan.duplicateAttachmentCount || 0)),
|
||||
budgetLimitedAttachmentCount: Math.max(0, Number(rawSelectionPlan.budgetLimitedAttachmentCount || 0)),
|
||||
groupCount: Math.max(0, Number(rawSelectionPlan.groupCount || 0)),
|
||||
}
|
||||
: null,
|
||||
unitSummary: rawUnitSummary
|
||||
? {
|
||||
totalUnits: Math.max(0, Number(rawUnitSummary.totalUnits || 0)),
|
||||
selectedUnits: Math.max(0, Number(rawUnitSummary.selectedUnits || 0)),
|
||||
retryingUnits: Math.max(0, Number(rawUnitSummary.retryingUnits || 0)),
|
||||
pendingRetryUnits: Math.max(0, Number(rawUnitSummary.pendingRetryUnits || 0)),
|
||||
failedUnits: Math.max(0, Number(rawUnitSummary.failedUnits || 0)),
|
||||
reviewRequiredUnits: Math.max(0, Number(rawUnitSummary.reviewRequiredUnits || 0)),
|
||||
succeededUnits: Math.max(0, Number(rawUnitSummary.succeededUnits || 0)),
|
||||
selectionBatches: rawUnitSummary.selectionBatches && typeof rawUnitSummary.selectionBatches === 'object'
|
||||
? rawUnitSummary.selectionBatches as Record<string, number>
|
||||
: {},
|
||||
reviewRequiredReasonCodes: Array.isArray(rawUnitSummary.reviewRequiredReasonCodes)
|
||||
? rawUnitSummary.reviewRequiredReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
expansionTriggerReasonCodes: Array.isArray(rawUnitSummary.expansionTriggerReasonCodes)
|
||||
? rawUnitSummary.expansionTriggerReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
technicalFailureReasonCodes: Array.isArray(rawUnitSummary.technicalFailureReasonCodes)
|
||||
? rawUnitSummary.technicalFailureReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
availableActions: Array.isArray(data.availableActions)
|
||||
? data.availableActions.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
terminal: Boolean(data.terminal),
|
||||
refreshFailed: Boolean(data.refreshFailed),
|
||||
errorCode: String(data.errorCode || '').trim() || null,
|
||||
startedAt: String(data.startedAt || '').trim() || null,
|
||||
finishedAt: String(data.finishedAt || '').trim() || null,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 将订单抽取状态消息同步到当前助手消息。
|
||||
*
|
||||
* 说明:订单抽取已经迁移为 HXOPS 自有 Run 事实;即使流式正文已完成,
|
||||
* 服务端后续补发的领域状态也允许继续覆盖当前卡片,但迟到的非终态不得回退终态展示。
|
||||
*/
|
||||
export const applyShippingOrderExtractionStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||||
const next = normalizeShippingOrderExtractionState(data);
|
||||
if (!next) return;
|
||||
const previous = msg.shipping_order_extraction_state;
|
||||
if (previous?.terminal && !next.terminal) return;
|
||||
msg.shipping_order_extraction_state = next;
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
shipping_order_extraction_state: next,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 把 SSE 事件附带的元数据同步到当前消息对象。
|
||||
*
|
||||
@@ -605,7 +722,10 @@ export function useChat() {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
applyShippingUiStateToMessage(botMsg, data);
|
||||
|
||||
} else if (eventName === 'shipping_order_extraction_state') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
applyShippingOrderExtractionStateToMessage(botMsg, data);
|
||||
} else if (eventName === 'message' || eventName === 'agent_message') {
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
const botMsg = ensureBotMessage();
|
||||
|
||||
@@ -52,15 +52,22 @@ const extractionMessage: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
shipping_order_extraction_state: {
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '正在识别邮件及附件中的订单',
|
||||
created_count: 0,
|
||||
opened_existing_count: 0,
|
||||
pending_count: 0,
|
||||
non_shipping_count: 0,
|
||||
created_with_missing_fields_count: 0,
|
||||
batch_no: null,
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 1,
|
||||
},
|
||||
currentActivity: {
|
||||
unitId: 8,
|
||||
fileName: 'PO-450001.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
terminal: false,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionTimeline.spec.ts
|
||||
* 用途:验证订单抽取 Run 时间线事件分类纯函数。
|
||||
* 依赖:Vitest、progress-event DTO 类型、orderExtractionTimeline 纯函数。
|
||||
* 逻辑:卡住业务复核、技术失败、预算停止和普通进度的最小分类契约。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ShippingOrderExtractionProgressEvent } from '../types/shipping.api.types';
|
||||
import { classifyOrderExtractionTimelineEvent } from './orderExtractionTimeline';
|
||||
|
||||
const event = (patch: Partial<ShippingOrderExtractionProgressEvent> = {}): ShippingOrderExtractionProgressEvent => ({
|
||||
event_code: 'initial_wave_started',
|
||||
status: 'completed',
|
||||
occurred_at: '2026-07-28T10:00:00Z',
|
||||
...patch,
|
||||
});
|
||||
|
||||
describe('classifyOrderExtractionTimelineEvent', () => {
|
||||
it('classifies review and expansion reasons as business timeline items', () => {
|
||||
expect(classifyOrderExtractionTimelineEvent(event({
|
||||
event_code: 'expansion_wave_started',
|
||||
summary: { reason_codes: ['required_field_missing'] },
|
||||
}))).toBe('business');
|
||||
});
|
||||
|
||||
it('classifies technical failure codes as technical timeline items', () => {
|
||||
expect(classifyOrderExtractionTimelineEvent(event({
|
||||
event_code: 'technical_failed',
|
||||
reason_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
}))).toBe('technical');
|
||||
});
|
||||
|
||||
it('classifies budget stop reasons as budget timeline items', () => {
|
||||
expect(classifyOrderExtractionTimelineEvent(event({
|
||||
event_code: 'budget_stopped',
|
||||
reason_code: 'budget_initial_limit',
|
||||
}))).toBe('budget');
|
||||
});
|
||||
|
||||
it('keeps neutral progress events in the progress bucket', () => {
|
||||
expect(classifyOrderExtractionTimelineEvent(event({
|
||||
event_code: 'plan_created',
|
||||
summary: { selection_batch: 1 },
|
||||
}))).toBe('progress');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionTimeline.ts
|
||||
* 用途:归类订单抽取 Run 时间线事件,供卡片/抽屉统一展示标签。
|
||||
* 依赖:订单抽取 progress-event DTO(纯函数,不依赖 Vue)。
|
||||
* 逻辑:区分业务复核、技术失败、预算停止与普通进度,避免组件散落条件分支。
|
||||
*/
|
||||
import type { ShippingOrderExtractionProgressEvent } from '../types/shipping.api.types';
|
||||
|
||||
export type OrderExtractionTimelineCategory = 'business' | 'technical' | 'budget' | 'progress';
|
||||
|
||||
const TECHNICAL_EVENT_CODES = new Set([
|
||||
'technical_retrying',
|
||||
'technical_failed',
|
||||
]);
|
||||
|
||||
const BUDGET_EVENT_CODES = new Set([
|
||||
'budget_stopped',
|
||||
]);
|
||||
|
||||
const BUSINESS_EVENT_CODES = new Set([
|
||||
'review_required',
|
||||
'expansion_wave_started',
|
||||
]);
|
||||
|
||||
const BUDGET_REASON_CODES = new Set([
|
||||
'budget_initial_limit',
|
||||
'budget_total_limit',
|
||||
]);
|
||||
|
||||
const TECHNICAL_REASON_PREFIXES = [
|
||||
'SHIPPING_NOTICE.',
|
||||
'SYSTEM.',
|
||||
];
|
||||
|
||||
const collectEventReasonCodes = (event: ShippingOrderExtractionProgressEvent): string[] => {
|
||||
const summary = event.summary && typeof event.summary === 'object'
|
||||
? event.summary as Record<string, unknown>
|
||||
: {};
|
||||
const reasonCodes = [
|
||||
String(event.reason_code || '').trim(),
|
||||
...(Array.isArray(summary.reason_codes) ? summary.reason_codes.map((item) => String(item || '').trim()) : []),
|
||||
].filter(Boolean);
|
||||
return Array.from(new Set(reasonCodes));
|
||||
};
|
||||
|
||||
export function classifyOrderExtractionTimelineEvent(
|
||||
event: ShippingOrderExtractionProgressEvent,
|
||||
): OrderExtractionTimelineCategory {
|
||||
const eventCode = String(event.event_code || '').trim();
|
||||
const reasonCodes = collectEventReasonCodes(event);
|
||||
|
||||
if (
|
||||
TECHNICAL_EVENT_CODES.has(eventCode)
|
||||
|| reasonCodes.some((code) => TECHNICAL_REASON_PREFIXES.some((prefix) => code.startsWith(prefix)))
|
||||
) {
|
||||
return 'technical';
|
||||
}
|
||||
|
||||
if (
|
||||
BUDGET_EVENT_CODES.has(eventCode)
|
||||
|| reasonCodes.some((code) => BUDGET_REASON_CODES.has(code))
|
||||
) {
|
||||
return 'budget';
|
||||
}
|
||||
|
||||
if (
|
||||
BUSINESS_EVENT_CODES.has(eventCode)
|
||||
|| reasonCodes.some((code) => !TECHNICAL_REASON_PREFIXES.some((prefix) => code.startsWith(prefix)))
|
||||
) {
|
||||
return 'business';
|
||||
}
|
||||
|
||||
return 'progress';
|
||||
}
|
||||
@@ -38,6 +38,16 @@ export function isShippingNoticeAttachmentParseIncomplete(
|
||||
summary?: ShippingNoticeParseSummary | null,
|
||||
): boolean {
|
||||
if (!summary) return false;
|
||||
const previewStatus = String(summary.preview_status || '').trim().toLowerCase();
|
||||
if (summary.technical_failure) {
|
||||
return true;
|
||||
}
|
||||
if (previewStatus === 'technical_failed' || previewStatus === 'directory_incomplete') {
|
||||
return true;
|
||||
}
|
||||
if (summary.attachment_directory_complete === false || summary.ready_for_extraction === false) {
|
||||
return true;
|
||||
}
|
||||
const warnings = summary.warnings || [];
|
||||
if (warnings.some((item) => isBlockingWarning(String(item || '')))) {
|
||||
return true;
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingSendHandler.spec.ts
|
||||
* 用途:验证上传预处理与点击发送完整抽取链路,以及建批提交中的并发拦截。
|
||||
* 用途:验证阶段 2 发送语义,只冻结当前输入框这批 Intake,并允许空备注启动识别。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingSendHandlers, type ShippingSendHandlerContext } from './useChatShippingSendHandler';
|
||||
|
||||
const isShippingNoticeBatchSubmitting = vi.hoisted(() => vi.fn(() => false));
|
||||
|
||||
vi.mock('./useChatShippingUploadHandler', () => ({
|
||||
isShippingNoticeBatchSubmitting,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingSendHandlerContext> = {},
|
||||
): ShippingSendHandlerContext => ({
|
||||
@@ -22,14 +16,7 @@ const createContext = (
|
||||
conversationId: ref('conv-send'),
|
||||
history: ref([]),
|
||||
input: ref(''),
|
||||
attachments: ref([{
|
||||
id: 'local-notice',
|
||||
kind: 'local',
|
||||
file: new File(['notice'], 'notice.txt', { type: 'text/plain' }),
|
||||
type: 'document',
|
||||
uploadStatus: 'waiting',
|
||||
uploadProgress: 0,
|
||||
}]),
|
||||
attachments: ref([]),
|
||||
shippingAutoFlowRequested: ref(true),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
getActiveShippingBatchNo: () => '',
|
||||
@@ -39,7 +26,7 @@ const createContext = (
|
||||
getActiveShippingTaskId: () => '',
|
||||
lastAssistantMessageContent: () => '',
|
||||
lastAssistantShippingActions: () => [],
|
||||
sendMessage: vi.fn(async () => true),
|
||||
sendMessage: vi.fn(async () => ({ ok: true } as never)),
|
||||
buildFileSpecsForSend: vi.fn(async () => []),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
@@ -50,9 +37,17 @@ const createContext = (
|
||||
handleShippingMenuAction: vi.fn(async () => undefined),
|
||||
handleShippingAutoUploadFile: vi.fn(async () => undefined),
|
||||
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
|
||||
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
|
||||
markOrderExtractionStarted: vi.fn(),
|
||||
rollbackOrderExtractionStarted: vi.fn(),
|
||||
isShippingNoticeBatchSubmitting: () => false,
|
||||
hasBlockingNoticeIntake: () => false,
|
||||
hasNoticeIntakeFailures: () => false,
|
||||
hasBlockingNoticeDuplicates: () => false,
|
||||
hasCandidateReviewIssues: () => false,
|
||||
hasSelectedNoticeCandidates: () => false,
|
||||
openShippingDuplicateDialog: vi.fn(),
|
||||
getParsedIntakeNos: () => [],
|
||||
startOrderExtractionRun: vi.fn(async () => true),
|
||||
applyShippingMessageRecovery: vi.fn(async () => false),
|
||||
applyShippingBatchSnapshot: vi.fn(() => false),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
shippingSuggestedPrompt: computed(() => ''),
|
||||
@@ -65,211 +60,158 @@ const createContext = (
|
||||
|
||||
describe('useChatShippingSendHandler', () => {
|
||||
beforeEach(() => {
|
||||
isShippingNoticeBatchSubmitting.mockReset();
|
||||
isShippingNoticeBatchSubmitting.mockReturnValue(false);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('consumes send while notice batch is submitting and does not call sendMessage', async () => {
|
||||
isShippingNoticeBatchSubmitting.mockReturnValue(true);
|
||||
const ctx = createContext();
|
||||
it('blocks send while current notice attachments are still previewing', async () => {
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-waiting',
|
||||
kind: 'shipping_notice',
|
||||
type: 'document',
|
||||
uploadStatus: 'uploaded',
|
||||
parseStatus: 'parsing',
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-WAITING',
|
||||
}]),
|
||||
hasBlockingNoticeIntake: () => true,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.sendMessage).not.toHaveBeenCalled();
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
|
||||
expect(ctx.startOrderExtractionRun).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeWaitingForParse');
|
||||
});
|
||||
|
||||
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
|
||||
const completionOrder: string[] = [];
|
||||
const attachment = {
|
||||
id: 'notice-1',
|
||||
it('starts extraction only for the current parsed intake batch and removes only submitted notice attachments', async () => {
|
||||
const currentNotice = {
|
||||
id: 'notice-current',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
orderExtractionStatus: 'not_started' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
originalFilename: 'orders-current.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-1',
|
||||
intakeNo: 'SNI-CURRENT',
|
||||
uploadBatchId: 'batch-current',
|
||||
};
|
||||
const ctx = createContext({
|
||||
attachments: ref([attachment]),
|
||||
hasCandidateReviewIssues: () => true,
|
||||
hasSelectedNoticeCandidates: () => true,
|
||||
getParsedIntakeNos: () => ['SNI-1'],
|
||||
applyShippingBatchSnapshot: vi.fn(() => { completionOrder.push('snapshot'); return true; }),
|
||||
refreshNoticeIntakeStatuses: vi.fn(async () => { completionOrder.push('intakes'); }),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => { completionOrder.push('workspace'); return true; }),
|
||||
clearConsumedNoticeAttachments: vi.fn(() => { completionOrder.push('clear'); }),
|
||||
refreshShippingActions: vi.fn(async () => { completionOrder.push('actions'); }),
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
expect(ctx.sendMessage).toHaveBeenCalledWith(
|
||||
'chat.shippingOrderExtractionDefaultPrompt',
|
||||
1,
|
||||
'',
|
||||
[],
|
||||
{
|
||||
shipping_intake_nos: ['SNI-1'],
|
||||
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
|
||||
},
|
||||
expect.objectContaining({
|
||||
userAttachments: [{
|
||||
name: 'orders.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
onAssistantMessageFinished: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
expect(ctx.markOrderExtractionStarted).toHaveBeenCalledWith(['SNI-1']);
|
||||
|
||||
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
|
||||
const assistantMessage = { role: 'assistant', content: '已打开已有任务' } as const;
|
||||
await hooks?.onAssistantMessageFinished?.(assistantMessage, []);
|
||||
expect(ctx.applyShippingBatchSnapshot).toHaveBeenCalledWith(assistantMessage);
|
||||
expect(completionOrder).toEqual(['snapshot', 'intakes', 'workspace', 'clear', 'actions']);
|
||||
expect(ctx.syncShippingConversationWorkspace).toHaveBeenCalledWith({ preferLatest: true });
|
||||
});
|
||||
|
||||
it('uses the user query for full extraction even when no candidate exists before send', async () => {
|
||||
const attachment = {
|
||||
id: 'notice-1',
|
||||
const laterNotice = {
|
||||
id: 'notice-later',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
orderExtractionStatus: 'not_started' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-1',
|
||||
originalFilename: 'orders-later.eml',
|
||||
fileSize: 120,
|
||||
intakeNo: 'SNI-LATER',
|
||||
uploadBatchId: 'batch-later',
|
||||
};
|
||||
const otherAttachment = {
|
||||
id: 'local-note',
|
||||
kind: 'local' as const,
|
||||
file: new File(['inventory'], 'inventory.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'waiting' as const,
|
||||
uploadProgress: 0,
|
||||
};
|
||||
const attachments = ref([currentNotice, laterNotice, otherAttachment]);
|
||||
const startOrderExtractionRun = vi.fn(async () => true);
|
||||
const ctx = createContext({
|
||||
attachments: ref([attachment]),
|
||||
hasCandidateReviewIssues: () => false,
|
||||
hasSelectedNoticeCandidates: () => false,
|
||||
getParsedIntakeNos: () => ['SNI-1'],
|
||||
attachments,
|
||||
getParsedIntakeNos: () => ['SNI-CURRENT'],
|
||||
startOrderExtractionRun,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '请解析这些附件', '请解析这些附件');
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '请优先处理当前批次', '请优先处理当前批次');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
expect(ctx.sendMessage).toHaveBeenCalledWith(
|
||||
'请解析这些附件',
|
||||
1,
|
||||
expect(startOrderExtractionRun).toHaveBeenCalledWith(
|
||||
'请优先处理当前批次',
|
||||
['SNI-CURRENT'],
|
||||
[{
|
||||
name: 'orders-current.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
'batch-current',
|
||||
);
|
||||
expect(attachments.value).toEqual([laterNotice, otherAttachment]);
|
||||
});
|
||||
|
||||
it('allows an empty note when the user only authorizes attachment analysis', async () => {
|
||||
const startOrderExtractionRun = vi.fn(async () => true);
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-empty-note',
|
||||
kind: 'shipping_notice',
|
||||
type: 'document',
|
||||
uploadStatus: 'uploaded',
|
||||
parseStatus: 'parsed',
|
||||
orderExtractionStatus: 'not_started',
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-EMPTY-NOTE',
|
||||
uploadBatchId: 'batch-empty-note',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-EMPTY-NOTE'],
|
||||
startOrderExtractionRun,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(startOrderExtractionRun).toHaveBeenCalledWith(
|
||||
'',
|
||||
[],
|
||||
{
|
||||
shipping_intake_nos: ['SNI-1'],
|
||||
display_query: '请解析这些附件',
|
||||
},
|
||||
expect.objectContaining({
|
||||
userAttachments: [{
|
||||
name: 'orders.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
onAssistantMessageFinished: expect.any(Function),
|
||||
}),
|
||||
['SNI-EMPTY-NOTE'],
|
||||
[{
|
||||
name: 'orders.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
'batch-empty-note',
|
||||
);
|
||||
});
|
||||
|
||||
it('retries the conversation workspace once when the first refresh fails', async () => {
|
||||
const syncWorkspace = vi.fn()
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true);
|
||||
it('keeps attachments in the input when starting the run fails', async () => {
|
||||
const attachment = {
|
||||
id: 'notice-start-failed',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
orderExtractionStatus: 'not_started' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-START-FAILED',
|
||||
};
|
||||
const attachments = ref([attachment]);
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-retry',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-RETRY',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-RETRY'],
|
||||
syncShippingConversationWorkspace: syncWorkspace,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
|
||||
await hooks?.onAssistantMessageFinished?.({} as never, []);
|
||||
|
||||
expect(syncWorkspace).toHaveBeenCalledTimes(2);
|
||||
expect(syncWorkspace).toHaveBeenNthCalledWith(1, { preferLatest: true });
|
||||
expect(syncWorkspace).toHaveBeenNthCalledWith(2, { preferLatest: true });
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('rolls back the local extracting state when the chat request fails', async () => {
|
||||
const rollback = vi.fn();
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-failed-send',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-FAILED-SEND',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-FAILED-SEND'],
|
||||
sendMessage: vi.fn(async () => { throw new Error('network failed'); }),
|
||||
rollbackOrderExtractionStarted: rollback,
|
||||
attachments,
|
||||
getParsedIntakeNos: () => ['SNI-START-FAILED'],
|
||||
startOrderExtractionRun: vi.fn(async () => { throw new Error('run create failed'); }),
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(rollback).toHaveBeenCalledWith(['SNI-FAILED-SEND']);
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('network failed');
|
||||
});
|
||||
|
||||
it('rolls back extraction state when sendMessage reports a handled stream failure', async () => {
|
||||
const rollback = vi.fn();
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-handled-failure',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-HANDLED-FAILURE',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
|
||||
sendMessage: vi.fn(async () => false),
|
||||
rollbackOrderExtractionStarted: rollback,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
|
||||
expect(ctx.loadHistory).not.toHaveBeenCalled();
|
||||
expect(attachments.value).toEqual([attachment]);
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('run create failed');
|
||||
});
|
||||
});
|
||||
@@ -72,7 +72,12 @@ export interface ShippingSendHandlerContext {
|
||||
hasSelectedNoticeCandidates?: () => boolean;
|
||||
openShippingDuplicateDialog?: (attachmentId?: string) => void;
|
||||
getParsedIntakeNos?: () => string[];
|
||||
startOrderExtractionRun?: (query: string, intakeNos: string[], attachments: ReturnType<typeof createChatMessageAttachmentSnapshots>) => Promise<boolean>;
|
||||
startOrderExtractionRun?: (
|
||||
query: string,
|
||||
intakeNos: string[],
|
||||
attachments: ReturnType<typeof createChatMessageAttachmentSnapshots>,
|
||||
uploadBatchId?: string,
|
||||
) => Promise<boolean>;
|
||||
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
|
||||
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
@@ -214,14 +219,33 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
}
|
||||
const intakeNos = ctx.getParsedIntakeNos?.() || [];
|
||||
if (intakeNos.length) {
|
||||
const userAttachments = createChatMessageAttachmentSnapshots(noticeItems);
|
||||
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
|
||||
const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase()));
|
||||
const batchIds = new Set(
|
||||
noticeItems
|
||||
.filter((item) => item.intakeNo && submittedIntakes.has(item.intakeNo.trim().toUpperCase()))
|
||||
.map((item) => String(item.uploadBatchId || '').trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
if (batchIds.size > 1) {
|
||||
ctx.msg.warning('当前发送批次不一致,请重新上传需要一起识别的文件');
|
||||
return true;
|
||||
}
|
||||
const userAttachments = createChatMessageAttachmentSnapshots(
|
||||
noticeItems.filter((item) =>
|
||||
item.intakeNo
|
||||
&& submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
|
||||
),
|
||||
);
|
||||
// 阶段 2:发送是“授权开始识别”,备注允许为空,不能再偷偷注入默认提示词。
|
||||
const query = trimmed;
|
||||
ctx.shippingAutoFlowRequested.value = false;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
try {
|
||||
const started = await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments);
|
||||
const uploadBatchId = [...batchIds][0];
|
||||
const started = uploadBatchId
|
||||
? await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments, uploadBatchId)
|
||||
: await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments);
|
||||
if (!started) return true;
|
||||
const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase()));
|
||||
ctx.attachments.value = ctx.attachments.value.filter(
|
||||
(item) => item.kind !== 'shipping_notice'
|
||||
|| !item.intakeNo
|
||||
|
||||
@@ -31,8 +31,14 @@ describe('shipping notice order extraction state', () => {
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'partially_completed' })).toBe(false);
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'completed' })).toBe(false);
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'failed' })).toBe(true);
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, layoutStatus: 'processing' })).toBe(false);
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, layoutStatus: 'completed' })).toBe(true);
|
||||
expect(isOrderExtractionEligibleIntake({
|
||||
...base,
|
||||
parseSummary: {
|
||||
preview_status: 'directory_incomplete',
|
||||
ready_for_extraction: false,
|
||||
attachment_directory_complete: false,
|
||||
},
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
|
||||
@@ -52,7 +58,7 @@ describe('shipping notice order extraction state', () => {
|
||||
parseStatus: 'parsed',
|
||||
orderExtractionStatus: 'not_started',
|
||||
layoutStatus: 'processing',
|
||||
})).toBe(true);
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('preserves the immediate extracting state until the backend leaves not_started', () => {
|
||||
@@ -66,12 +72,21 @@ describe('shipping notice order extraction state', () => {
|
||||
expect(shouldRestoreShippingNoticeIntake('queued')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsing')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, {
|
||||
preview_status: 'ready_for_extraction',
|
||||
ready_for_extraction: true,
|
||||
attachment_directory_complete: true,
|
||||
})).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'failed', 0)).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 2)).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, 'processing')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, {
|
||||
preview_status: 'directory_incomplete',
|
||||
ready_for_extraction: false,
|
||||
attachment_directory_complete: false,
|
||||
})).toBe(false);
|
||||
|
||||
// 已完成且没有待审核 Candidate 的文件仅保留在用户消息气泡中。
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed')).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed')).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 0)).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed', 2)).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('consumed')).toBe(false);
|
||||
|
||||
@@ -40,8 +40,8 @@ const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
|
||||
/**
|
||||
* 判断服务端 Intake 是否应恢复到输入栏。
|
||||
* AI 触发时机:无;页面刷新或重新打开会话时调用。
|
||||
* 已解析文件已作为用户消息附件固化在对话气泡中,不能再次显示在输入栏;但存在待审核
|
||||
* Candidate 的部分完成 Intake 必须恢复,否则用户无法补充字段并继续建单。
|
||||
* 上传快览与发送授权已拆分:未发送但已快览成功的附件,刷新后也必须恢复到输入栏;
|
||||
* 已进入订单抽取终态的附件仅保留在消息气泡中,避免把旧批次误带回当前输入框。
|
||||
* @param parseStatus - 服务端返回的预解析状态。
|
||||
* @param orderExtractionStatus - 服务端返回的订单抽取状态。
|
||||
* @param candidateCount - 当前仍可审核的订单 Candidate 数量。
|
||||
@@ -51,13 +51,17 @@ export function shouldRestoreShippingNoticeIntake(
|
||||
parseStatus: string | null | undefined,
|
||||
orderExtractionStatus?: string | null,
|
||||
candidateCount = 0,
|
||||
layoutStatus?: ShippingNoticePendingAttachment['layoutStatus'],
|
||||
parseSummary?: ShippingNoticePendingAttachment['parseSummary'],
|
||||
): boolean {
|
||||
const status = String(parseStatus || '').trim().toLowerCase();
|
||||
const extractionStatus = String(orderExtractionStatus || '').trim().toLowerCase();
|
||||
return ACTIVE_PARSE.has(status)
|
||||
|| status === 'parse_failed'
|
||||
|| layoutStatus === 'processing'
|
||||
|| (
|
||||
status === 'parsed'
|
||||
&& (!extractionStatus || extractionStatus === 'not_started')
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(parseSummary)
|
||||
)
|
||||
|| extractionStatus === 'failed'
|
||||
|| (extractionStatus === 'partially_completed' && candidateCount > 0);
|
||||
}
|
||||
@@ -67,8 +71,7 @@ export function shouldPollShippingNoticeIntake(
|
||||
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus' | 'layoutStatus'>,
|
||||
): boolean {
|
||||
return !TERMINAL_PARSE.has(item.parseStatus)
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase())
|
||||
|| item.layoutStatus === 'processing';
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
|
||||
}
|
||||
|
||||
/** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */
|
||||
@@ -79,7 +82,6 @@ export function isOrderExtractionEligibleIntake(
|
||||
return item.parseStatus === 'parsed'
|
||||
&& Boolean(item.intakeNo)
|
||||
&& (extractionStatus === 'not_started' || extractionStatus === 'failed')
|
||||
&& item.layoutStatus !== 'processing'
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary);
|
||||
}
|
||||
|
||||
@@ -222,7 +224,7 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
|
||||
};
|
||||
}
|
||||
|
||||
function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
|
||||
function createPendingAttachment(file: File, uploadBatchId: string): ShippingNoticePendingAttachment {
|
||||
return {
|
||||
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
kind: 'shipping_notice',
|
||||
@@ -233,6 +235,7 @@ function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
|
||||
uploadProgress: 0,
|
||||
originalFilename: file.name,
|
||||
fileSize: file.size,
|
||||
uploadBatchId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -246,6 +249,8 @@ export interface UseShippingNoticeIntakesOptions {
|
||||
export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) {
|
||||
const pollTimer = ref<ReturnType<typeof setTimeout> | null>(null);
|
||||
const pollRound = ref(0);
|
||||
// 新文件选择显式推进当前批次;恢复历史卡片不能覆盖它。
|
||||
const currentUploadBatchId = ref<string | null>(null);
|
||||
|
||||
const noticeAttachments = computed(() =>
|
||||
options.attachments.value.filter(
|
||||
@@ -253,20 +258,26 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
),
|
||||
);
|
||||
|
||||
const currentBatchAttachments = computed(() => {
|
||||
const batchId = currentUploadBatchId.value;
|
||||
return batchId
|
||||
? noticeAttachments.value.filter((item) => item.uploadBatchId === batchId)
|
||||
: noticeAttachments.value;
|
||||
});
|
||||
|
||||
const hasBlockingUploadOrParse = computed(() =>
|
||||
noticeAttachments.value.some((item) =>
|
||||
currentBatchAttachments.value.some((item) =>
|
||||
item.uploadStatus === 'uploading'
|
||||
|| item.uploadStatus === 'waiting'
|
||||
|| ACTIVE_PARSE.has(item.parseStatus)
|
||||
|| item.parseStatus === 'queued'
|
||||
|| item.parseStatus === 'parsing'
|
||||
|| item.layoutStatus === 'processing'
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()),
|
||||
),
|
||||
);
|
||||
|
||||
const hasParseFailures = computed(() =>
|
||||
noticeAttachments.value.some(
|
||||
currentBatchAttachments.value.some(
|
||||
(item) =>
|
||||
item.parseStatus === 'failed'
|
||||
|| isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
|
||||
@@ -274,8 +285,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
);
|
||||
|
||||
const allParsedReady = computed(() =>
|
||||
noticeAttachments.value.length > 0
|
||||
&& noticeAttachments.value.every(
|
||||
currentBatchAttachments.value.length > 0
|
||||
&& currentBatchAttachments.value.every(
|
||||
(item) =>
|
||||
item.parseStatus === 'parsed'
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
|
||||
@@ -283,7 +294,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
);
|
||||
|
||||
const hasBlockingDuplicates = computed(() =>
|
||||
noticeAttachments.value.some(
|
||||
currentBatchAttachments.value.some(
|
||||
(item) => (item.candidates?.length
|
||||
? item.candidates.some((candidate) =>
|
||||
candidate.selected && candidate.duplicate?.blocking && !candidate.duplicateResolution?.action,
|
||||
@@ -293,7 +304,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
);
|
||||
|
||||
const hasCandidateReviewIssues = computed(() =>
|
||||
noticeAttachments.value.some((item) =>
|
||||
currentBatchAttachments.value.some((item) =>
|
||||
(item.candidates || []).some((candidate) =>
|
||||
candidate.selected && candidate.validationStatus !== 'ready',
|
||||
),
|
||||
@@ -305,7 +316,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
&& !hasBlockingDuplicates.value
|
||||
&& !hasCandidateReviewIssues.value
|
||||
&& !hasParseFailures.value
|
||||
&& noticeAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)),
|
||||
&& currentBatchAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)),
|
||||
);
|
||||
|
||||
const stopPolling = () => {
|
||||
@@ -386,9 +397,11 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
const intake = await createShippingNoticeIntake(
|
||||
asset.asset_no,
|
||||
options.conversationId.value,
|
||||
attachment.uploadBatchId,
|
||||
);
|
||||
patchAttachment(attachment.id, {
|
||||
intakeNo: intake.intake_no,
|
||||
uploadBatchId: intake.upload_batch_id || attachment.uploadBatchId,
|
||||
parseStatus: mapServerParseStatus(intake.parse_status),
|
||||
orderExtractionStatus: intake.order_extraction_status || undefined,
|
||||
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
@@ -412,8 +425,12 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
};
|
||||
|
||||
const enqueueNoticeFiles = async (files: File[]) => {
|
||||
// 同一次选择共享一个持久化批次;后续发送只会自动取这个最新批次。
|
||||
const uploadBatchId = globalThis.crypto?.randomUUID?.()
|
||||
|| `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`;
|
||||
currentUploadBatchId.value = uploadBatchId;
|
||||
for (const file of files) {
|
||||
const attachment = createPendingAttachment(file);
|
||||
const attachment = createPendingAttachment(file, uploadBatchId);
|
||||
options.attachments.value = [...options.attachments.value, attachment];
|
||||
await processSingleFile(attachment);
|
||||
}
|
||||
@@ -452,10 +469,14 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
schedulePoll();
|
||||
};
|
||||
|
||||
const getParsedIntakeNos = () =>
|
||||
noticeAttachments.value
|
||||
.filter(isOrderExtractionEligibleIntake)
|
||||
const getParsedIntakeNos = () => {
|
||||
const eligible = noticeAttachments.value.filter(isOrderExtractionEligibleIntake);
|
||||
const currentBatchId = currentUploadBatchId.value
|
||||
|| [...noticeAttachments.value].reverse().find((item) => item.uploadBatchId)?.uploadBatchId;
|
||||
return eligible
|
||||
.filter((item) => item.uploadBatchId === currentBatchId)
|
||||
.map((item) => String(item.intakeNo));
|
||||
};
|
||||
|
||||
/** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */
|
||||
const markOrderExtractionStarted = (intakeNos: string[]) => {
|
||||
@@ -497,7 +518,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
item.parse_status,
|
||||
item.order_extraction_status,
|
||||
item.candidates?.length || 0,
|
||||
item.layout_status,
|
||||
(item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
))
|
||||
.map((item) => ({
|
||||
id: `restored_${item.intake_no}`,
|
||||
@@ -505,6 +526,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
type: 'document' as const,
|
||||
assetNo: item.asset_no || undefined,
|
||||
intakeNo: item.intake_no,
|
||||
uploadBatchId: item.upload_batch_id || undefined,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: mapServerParseStatus(item.parse_status),
|
||||
orderExtractionStatus: item.order_extraction_status || undefined,
|
||||
|
||||
@@ -37,6 +37,17 @@ const run = (patch: Partial<ShippingOrderExtractionRun>): ShippingOrderExtractio
|
||||
intake_nos: ['SNI-1'],
|
||||
schema_version_id: 1,
|
||||
attempt_count: 0,
|
||||
summary: {
|
||||
total_documents: 1,
|
||||
pending_documents: 1,
|
||||
processing_documents: 0,
|
||||
completed_documents: 0,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 0,
|
||||
},
|
||||
current_activity: null,
|
||||
available_actions: ['view_details'],
|
||||
...patch,
|
||||
});
|
||||
|
||||
@@ -86,7 +97,8 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
api.getRun.mockResolvedValue(queued);
|
||||
const harness = createHarness();
|
||||
|
||||
await harness.runs.startRun('解析附件', ['SNI-1'], []);
|
||||
await harness.runs.startRun('解析附件', ['SNI-1'], [], 'batch-1');
|
||||
expect(api.createRun).toHaveBeenCalledWith(expect.objectContaining({ upload_batch_id: 'batch-1' }));
|
||||
expect(harness.conversationId.value).toBe('conv-created');
|
||||
expect(harness.options.onConversationResolved).toHaveBeenCalledWith('conv-created');
|
||||
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
|
||||
@@ -101,10 +113,42 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('persists an attachment-only user message when the run starts without a text note', async () => {
|
||||
const queued = run({ run_no: 'SNER-EMPTY-NOTE', conversation_id: 'conv-empty-note' });
|
||||
api.createRun.mockResolvedValue({ run: queued, reused: false });
|
||||
const harness = createHarness();
|
||||
|
||||
await harness.runs.startRun('', ['SNI-1'], [{
|
||||
name: 'orders.eml',
|
||||
size: 128,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}]);
|
||||
|
||||
expect(harness.messages.value[0]).toMatchObject({
|
||||
role: 'user',
|
||||
content: '',
|
||||
attachments: [{
|
||||
name: 'orders.eml',
|
||||
size: 128,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
});
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ content: '' }),
|
||||
undefined,
|
||||
);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('absorbs restore failures and ignores an old conversation late response', async () => {
|
||||
const pending = deferred<ShippingOrderExtractionRun>();
|
||||
api.listRuns
|
||||
.mockResolvedValueOnce({ items: [run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'running' })] })
|
||||
.mockResolvedValueOnce({ items: [run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'processing' })] })
|
||||
.mockRejectedValueOnce(new Error('offline'));
|
||||
api.getRun.mockReturnValueOnce(pending.promise);
|
||||
const harness = createHarness();
|
||||
@@ -118,7 +162,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
await Promise.resolve();
|
||||
expect(harness.runs.getActiveRunNo()).toBe('');
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('processing');
|
||||
});
|
||||
|
||||
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
|
||||
@@ -132,7 +176,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
await vi.advanceTimersByTimeAsync(11000);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-TIMEOUT', expect.any(AbortSignal));
|
||||
expect(harness.runs.getActiveRunNo()).toBe('SNER-TIMEOUT');
|
||||
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('queued');
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
@@ -151,7 +195,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(api.retryRun).toHaveBeenCalledWith('SNER-RETRY');
|
||||
expect(harness.options.refreshNoticeIntakeStatuses).toHaveBeenCalledTimes(2);
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('queued');
|
||||
expect(harness.runs.getActiveRunNo()).toBe('SNER-RETRY');
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
@@ -167,7 +211,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
});
|
||||
|
||||
it('creates a new Run for reidentification and switches polling to the new version', async () => {
|
||||
const source = run({ run_no: 'SNER-SOURCE', status: 'needs_review' });
|
||||
const source = run({ run_no: 'SNER-SOURCE', status: 'review_required' });
|
||||
const replacement = run({
|
||||
run_no: 'SNER-REPLACEMENT', status: 'queued',
|
||||
reparse: { source_run_no: 'SNER-SOURCE', reason: 'field_mapping_error' },
|
||||
@@ -190,34 +234,75 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
|
||||
|
||||
describe('mapOrderExtractionRunToMessageState', () => {
|
||||
it('maps queued/running to indeterminate extracting state', () => {
|
||||
it('maps queued and processing to the new Run summary state', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'running',
|
||||
phase: 'calling_provider',
|
||||
progress: {
|
||||
version: 3,
|
||||
current_stage_code: 'document_processing',
|
||||
health: 'normal',
|
||||
last_activity_at: '2026-07-21T03:24:51Z',
|
||||
status: 'processing',
|
||||
selection_plan: {
|
||||
max_initial_attachments: 2,
|
||||
max_initial_concurrency: 2,
|
||||
expansion_batch_size: 2,
|
||||
max_total_attachments: 6,
|
||||
total_attachment_count: 5,
|
||||
eligible_attachment_count: 4,
|
||||
selected_attachment_count: 2,
|
||||
planned_attachment_count: 4,
|
||||
pending_expansion_attachment_count: 2,
|
||||
pending_expansion_batches: { '2': 2 },
|
||||
skipped_attachment_count: 1,
|
||||
duplicate_attachment_count: 1,
|
||||
budget_limited_attachment_count: 0,
|
||||
group_count: 2,
|
||||
},
|
||||
current_activity: { unit_id: 7, file_name: 'PO-1.pdf', event_code: 'profile_matching' },
|
||||
summary: {
|
||||
total_documents: 3,
|
||||
pending_documents: 0,
|
||||
processing_documents: 1,
|
||||
completed_documents: 2,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 2,
|
||||
},
|
||||
}))).toMatchObject({
|
||||
status: 'extracting', terminal: false, phase: 'llm_extraction',
|
||||
current_stage_code: 'document_processing', health: 'normal',
|
||||
last_activity_at: '2026-07-21T03:24:51Z',
|
||||
status: 'processing',
|
||||
terminal: false,
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 2,
|
||||
candidateCount: 2,
|
||||
},
|
||||
selectionPlan: {
|
||||
expansionBatchSize: 2,
|
||||
maxTotalAttachments: 6,
|
||||
plannedAttachmentCount: 4,
|
||||
pendingExpansionAttachmentCount: 2,
|
||||
pendingExpansionBatches: { '2': 2 },
|
||||
},
|
||||
currentActivity: { unitId: 7, fileName: 'PO-1.pdf', eventCode: 'profile_matching' },
|
||||
});
|
||||
});
|
||||
|
||||
it('persists a changed progress projection even when Run status and result are unchanged', async () => {
|
||||
it('persists a changed summary projection even when Run status is unchanged', async () => {
|
||||
vi.useFakeTimers();
|
||||
const first = run({
|
||||
run_no: 'SNER-PROGRESS',
|
||||
status: 'running',
|
||||
progress: { version: 1, current_stage_code: 'workflow_accepted' },
|
||||
status: 'processing',
|
||||
current_activity: { unit_id: 1, file_name: 'PO-A.pdf', event_code: 'document_queued' },
|
||||
});
|
||||
const second = run({
|
||||
run_no: 'SNER-PROGRESS',
|
||||
status: 'running',
|
||||
progress: { version: 2, current_stage_code: 'order_recognition' },
|
||||
status: 'processing',
|
||||
current_activity: { unit_id: 1, file_name: 'PO-A.pdf', event_code: 'profile_matching' },
|
||||
summary: {
|
||||
total_documents: 2,
|
||||
pending_documents: 0,
|
||||
processing_documents: 1,
|
||||
completed_documents: 1,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 1,
|
||||
},
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [first] });
|
||||
api.getRun.mockResolvedValueOnce(second);
|
||||
@@ -229,14 +314,15 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.current_stage_code).toBe('order_recognition');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.currentActivity?.eventCode).toBe('profile_matching');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.summary.completedDocuments).toBe(1);
|
||||
harness.runs.stopPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('merges duplicate local cards for one Run when a terminal update arrives', async () => {
|
||||
vi.useFakeTimers();
|
||||
const active = run({ run_no: 'SNER-DUPLICATE', status: 'running' });
|
||||
const active = run({ run_no: 'SNER-DUPLICATE', status: 'processing' });
|
||||
const failed = run({
|
||||
run_no: 'SNER-DUPLICATE', status: 'failed', phase: 'failed', error: { code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED' },
|
||||
});
|
||||
@@ -262,8 +348,22 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
|
||||
it('refreshes Intake candidates and persists them on the terminal Run card without page reload', async () => {
|
||||
vi.useFakeTimers();
|
||||
const active = run({ run_no: 'SNER-REVIEW', status: 'running' });
|
||||
const terminal = run({ run_no: 'SNER-REVIEW', status: 'needs_review', result: { pending_count: 1 } });
|
||||
const active = run({ run_no: 'SNER-REVIEW', status: 'processing' });
|
||||
const terminal = run({
|
||||
run_no: 'SNER-REVIEW',
|
||||
status: 'review_required',
|
||||
summary: {
|
||||
total_documents: 1,
|
||||
pending_documents: 0,
|
||||
processing_documents: 0,
|
||||
completed_documents: 0,
|
||||
review_required_documents: 1,
|
||||
failed_documents: 0,
|
||||
candidate_count: 0,
|
||||
},
|
||||
result: { pending_count: 1 },
|
||||
available_actions: ['view_details', 'enter_manual_review'],
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [active] });
|
||||
api.getRun.mockResolvedValue(terminal);
|
||||
const harness = createHarness();
|
||||
@@ -287,22 +387,49 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('maps completed result counters without guessing from text', () => {
|
||||
it('maps completed summaries without guessing from text', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'completed',
|
||||
result: { batch_no: 'SB-1', created_count: 2, opened_existing_count: 1, pending_count: 0 },
|
||||
summary: {
|
||||
total_documents: 3,
|
||||
pending_documents: 0,
|
||||
processing_documents: 0,
|
||||
completed_documents: 3,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 3,
|
||||
},
|
||||
available_actions: ['view_details'],
|
||||
}))).toMatchObject({
|
||||
status: 'completed', terminal: true, batch_no: 'SB-1', created_count: 2, opened_existing_count: 1,
|
||||
status: 'completed',
|
||||
terminal: true,
|
||||
summary: { completedDocuments: 3, candidateCount: 3 },
|
||||
availableActions: ['view_details'],
|
||||
});
|
||||
});
|
||||
|
||||
it('maps needs_review and failed to distinct terminal states', () => {
|
||||
it('maps review_required and failed to distinct terminal states', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'needs_review', result: { pending_count: 3 },
|
||||
}))).toMatchObject({ status: 'partially_completed', pending_count: 3, terminal: true });
|
||||
status: 'review_required',
|
||||
summary: {
|
||||
total_documents: 3,
|
||||
pending_documents: 0,
|
||||
processing_documents: 0,
|
||||
completed_documents: 0,
|
||||
review_required_documents: 3,
|
||||
failed_documents: 0,
|
||||
candidate_count: 0,
|
||||
},
|
||||
available_actions: ['view_details', 'enter_manual_review'],
|
||||
}))).toMatchObject({
|
||||
status: 'review_required',
|
||||
terminal: true,
|
||||
summary: { reviewRequiredDocuments: 3 },
|
||||
availableActions: ['view_details', 'enter_manual_review'],
|
||||
});
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'failed', error: { code: 'X' },
|
||||
}))).toMatchObject({ status: 'failed', message: '', terminal: true });
|
||||
}))).toMatchObject({ status: 'failed', errorCode: 'X', terminal: true });
|
||||
});
|
||||
|
||||
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
|
||||
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run,终态后刷新 Intake、批次工作台与动作。
|
||||
*/
|
||||
import { onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
|
||||
import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
|
||||
import {
|
||||
createWorkspaceShippingOrderExtractionRun,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
@@ -34,30 +34,80 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
const ACTIVE_RUN_STATUSES = new Set(['queued', 'running', 'result_persisted']);
|
||||
const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
|
||||
|
||||
/** 把领域 Run 转为聊天组件既有的订单抽取状态卡契约。 */
|
||||
export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtractionRun): ShippingOrderExtractionState {
|
||||
const result = run.result || {};
|
||||
const failed = run.status === 'failed' || run.status === 'cancelled';
|
||||
const partial = run.status === 'needs_review';
|
||||
const completed = run.status === 'completed';
|
||||
return {
|
||||
status: failed ? 'failed' : partial ? 'partially_completed' : completed ? 'completed' : 'extracting',
|
||||
phase: failed ? 'failed' : run.status === 'result_persisted' ? 'result_persisted' : 'llm_extraction',
|
||||
// Provider/网络错误正文仅供管理员诊断,用户卡片统一展示可操作的业务提示。
|
||||
message: '',
|
||||
created_count: Number(result.created_count || 0),
|
||||
opened_existing_count: Number(result.opened_existing_count || 0),
|
||||
pending_count: Number(result.pending_count || 0),
|
||||
non_shipping_count: Number(result.non_shipping_count || 0),
|
||||
created_with_missing_fields_count: Number(result.created_with_missing_fields_count || 0),
|
||||
batch_no: result.batch_no || null,
|
||||
terminal: failed || partial || completed,
|
||||
current_stage_code: run.progress?.current_stage_code || null,
|
||||
health: run.progress?.health || 'normal',
|
||||
last_activity_at: run.progress?.last_activity_at || null,
|
||||
started_at: run.started_at || run.created_at || null,
|
||||
status: run.status,
|
||||
summary: {
|
||||
totalDocuments: Number(run.summary?.total_documents || 0),
|
||||
pendingDocuments: Number(run.summary?.pending_documents || 0),
|
||||
processingDocuments: Number(run.summary?.processing_documents || 0),
|
||||
completedDocuments: Number(run.summary?.completed_documents || 0),
|
||||
reviewRequiredDocuments: Number(run.summary?.review_required_documents || 0),
|
||||
failedDocuments: Number(run.summary?.failed_documents || 0),
|
||||
candidateCount: Number(run.summary?.candidate_count || 0),
|
||||
},
|
||||
currentActivity: run.current_activity
|
||||
? {
|
||||
unitId: Number(run.current_activity.unit_id || 0),
|
||||
fileName: run.current_activity.file_name || null,
|
||||
eventCode: String(run.current_activity.event_code || ''),
|
||||
selectionBatch: run.current_activity.selection_batch != null
|
||||
? Number(run.current_activity.selection_batch || 0) || null
|
||||
: null,
|
||||
reasonCodes: Array.isArray(run.current_activity.reason_codes)
|
||||
? run.current_activity.reason_codes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
selectionPlan: run.selection_plan
|
||||
? {
|
||||
selectionVersion: run.selection_plan.selection_version || null,
|
||||
maxInitialAttachments: Number(run.selection_plan.max_initial_attachments || 0),
|
||||
maxInitialConcurrency: Number(run.selection_plan.max_initial_concurrency || 0),
|
||||
expansionBatchSize: Number(run.selection_plan.expansion_batch_size || 0),
|
||||
maxTotalAttachments: Number(run.selection_plan.max_total_attachments || 0),
|
||||
totalAttachmentCount: Number(run.selection_plan.total_attachment_count || 0),
|
||||
eligibleAttachmentCount: Number(run.selection_plan.eligible_attachment_count || 0),
|
||||
selectedAttachmentCount: Number(run.selection_plan.selected_attachment_count || 0),
|
||||
plannedAttachmentCount: Number(run.selection_plan.planned_attachment_count || 0),
|
||||
pendingExpansionAttachmentCount: Number(run.selection_plan.pending_expansion_attachment_count || 0),
|
||||
pendingExpansionBatches: run.selection_plan.pending_expansion_batches || {},
|
||||
skippedAttachmentCount: Number(run.selection_plan.skipped_attachment_count || 0),
|
||||
duplicateAttachmentCount: Number(run.selection_plan.duplicate_attachment_count || 0),
|
||||
budgetLimitedAttachmentCount: Number(run.selection_plan.budget_limited_attachment_count || 0),
|
||||
groupCount: Number(run.selection_plan.group_count || 0),
|
||||
}
|
||||
: null,
|
||||
unitSummary: run.unit_summary
|
||||
? {
|
||||
totalUnits: Number(run.unit_summary.total_units || 0),
|
||||
selectedUnits: Number(run.unit_summary.selected_units || 0),
|
||||
retryingUnits: Number(run.unit_summary.retrying_units || 0),
|
||||
pendingRetryUnits: Number(run.unit_summary.pending_retry_units || 0),
|
||||
failedUnits: Number(run.unit_summary.failed_units || 0),
|
||||
reviewRequiredUnits: Number(run.unit_summary.review_required_units || 0),
|
||||
succeededUnits: Number(run.unit_summary.succeeded_units || 0),
|
||||
selectionBatches: run.unit_summary.selection_batches || {},
|
||||
reviewRequiredReasonCodes: Array.isArray(run.unit_summary.review_required_reason_codes)
|
||||
? [...run.unit_summary.review_required_reason_codes]
|
||||
: [],
|
||||
expansionTriggerReasonCodes: Array.isArray(run.unit_summary.expansion_trigger_reason_codes)
|
||||
? [...run.unit_summary.expansion_trigger_reason_codes]
|
||||
: [],
|
||||
technicalFailureReasonCodes: Array.isArray(run.unit_summary.technical_failure_reason_codes)
|
||||
? [...run.unit_summary.technical_failure_reason_codes]
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
availableActions: Array.isArray(run.available_actions) ? [...run.available_actions] : [],
|
||||
terminal: !ACTIVE_RUN_STATUSES.has(run.status),
|
||||
refreshFailed: false,
|
||||
errorCode: run.error?.code || null,
|
||||
startedAt: run.started_at || null,
|
||||
finishedAt: run.finished_at || null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,6 +130,20 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
pollGeneration += 1;
|
||||
};
|
||||
|
||||
/** 网络轮询失败只更新本地提示,不得把后台业务 Run 误判为失败。 */
|
||||
const setRunRefreshFailed = (runNo: string, refreshFailed: boolean) => {
|
||||
const normalizedRunNo = String(runNo || '').trim();
|
||||
if (!normalizedRunNo) return;
|
||||
for (const message of options.messages.value) {
|
||||
const payload = message.payload && typeof message.payload === 'object' ? message.payload as Record<string, unknown> : {};
|
||||
if (payload.order_extraction_run_no !== normalizedRunNo || !message.shipping_order_extraction_state) continue;
|
||||
message.shipping_order_extraction_state = {
|
||||
...message.shipping_order_extraction_state,
|
||||
refreshFailed,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 查找或创建当前 Run 的助手状态消息,仅在业务状态真正变化时持久化。
|
||||
* @param run - 用户态 Run 摘要,不包含 Provider 快照或原始文档。
|
||||
@@ -122,7 +186,16 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
order_extraction_reparse: run.reparse || null,
|
||||
shipping_order_extraction_review: reviewAttachments || [],
|
||||
};
|
||||
const signature = JSON.stringify({ status: run.status, phase: run.phase, result: run.result, error: run.error, progress: run.progress, reparse: run.reparse, reviewAttachments });
|
||||
const signature = JSON.stringify({
|
||||
status: run.status,
|
||||
summary: run.summary,
|
||||
current_activity: run.current_activity,
|
||||
available_actions: run.available_actions,
|
||||
result: run.result,
|
||||
error: run.error,
|
||||
reparse: run.reparse,
|
||||
reviewAttachments,
|
||||
});
|
||||
if (persistedSignatures.get(run.run_no) !== signature) {
|
||||
const persisted = await options.saveLocalMessageToBackend(message);
|
||||
if (persisted) persistedSignatures.set(run.run_no, signature);
|
||||
@@ -203,6 +276,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(runNo, request.signal).finally(request.release);
|
||||
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);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
@@ -218,6 +292,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
} catch {
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollFailureCount += 1;
|
||||
setRunRefreshFailed(runNo, true);
|
||||
const delayMs = Math.min(15000, 2000 * (2 ** Math.min(pollFailureCount, 3)));
|
||||
pollTimer = setTimeout(() => void pollRun(runNo, generation), delayMs);
|
||||
}
|
||||
@@ -233,7 +308,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
|
||||
/**
|
||||
* 启动订单抽取后台 Run,并把用户操作和状态卡持久化到本地会话。
|
||||
* @param query - 用户本次展示文本;不发送给 Dify Chatflow。
|
||||
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。
|
||||
* @param intakeNos - 本次冻结的 Intake 编号。
|
||||
* @param attachments - 用户消息中的安全附件快照。
|
||||
* @returns Run 已成功创建或幂等复用时为 true。
|
||||
@@ -242,12 +317,14 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
query: string,
|
||||
intakeNos: string[],
|
||||
attachments: ChatMessageAttachment[],
|
||||
uploadBatchId?: string,
|
||||
): Promise<boolean> => {
|
||||
stopPolling();
|
||||
const response = await createWorkspaceShippingOrderExtractionRun({
|
||||
agent_id: options.currentAgentId.value,
|
||||
conversation_id: options.conversationId.value || undefined,
|
||||
intake_nos: intakeNos,
|
||||
upload_batch_id: uploadBatchId || '',
|
||||
});
|
||||
const run = response.run;
|
||||
if (!options.conversationId.value) options.conversationId.value = run.conversation_id;
|
||||
@@ -265,7 +342,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
},
|
||||
};
|
||||
options.messages.value.push(userMessage);
|
||||
await options.saveLocalMessageToBackend(userMessage, query);
|
||||
await options.saveLocalMessageToBackend(userMessage, query || undefined);
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
await options.onConversationResolved(run.conversation_id);
|
||||
@@ -369,6 +446,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}
|
||||
};
|
||||
|
||||
onBeforeUnmount(stopPolling);
|
||||
if (getCurrentInstance()) onBeforeUnmount(stopPolling);
|
||||
return { startRun, retryRun, reparseRun, restoreForConversation, stopPolling, updateCandidateReviewSnapshot, getActiveRunNo: () => activeRunNo };
|
||||
}
|
||||
@@ -21,23 +21,77 @@ export interface RetrieverResource {
|
||||
|
||||
export type ShippingOrderExtractionStatus = 'extracting' | 'completed' | 'partially_completed' | 'failed';
|
||||
|
||||
export type ShippingOrderExtractionStateStatus =
|
||||
| 'queued'
|
||||
| 'processing'
|
||||
| 'completed'
|
||||
| 'partially_completed'
|
||||
| 'review_required'
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
|
||||
export interface ShippingOrderExtractionStateSummary {
|
||||
totalDocuments: number;
|
||||
pendingDocuments: number;
|
||||
processingDocuments: number;
|
||||
completedDocuments: number;
|
||||
reviewRequiredDocuments: number;
|
||||
failedDocuments: number;
|
||||
candidateCount: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivityState {
|
||||
unitId: number;
|
||||
fileName?: string | null;
|
||||
eventCode: string;
|
||||
selectionBatch?: number | null;
|
||||
reasonCodes?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionSelectionPlanState {
|
||||
selectionVersion?: string | null;
|
||||
maxInitialAttachments?: number;
|
||||
maxInitialConcurrency?: number;
|
||||
expansionBatchSize?: number;
|
||||
maxTotalAttachments?: number;
|
||||
totalAttachmentCount?: number;
|
||||
eligibleAttachmentCount?: number;
|
||||
selectedAttachmentCount?: number;
|
||||
plannedAttachmentCount?: number;
|
||||
pendingExpansionAttachmentCount?: number;
|
||||
pendingExpansionBatches?: Record<string, number>;
|
||||
skippedAttachmentCount?: number;
|
||||
duplicateAttachmentCount?: number;
|
||||
budgetLimitedAttachmentCount?: number;
|
||||
groupCount?: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionUnitSummaryState {
|
||||
totalUnits?: number;
|
||||
selectedUnits?: number;
|
||||
retryingUnits?: number;
|
||||
pendingRetryUnits?: number;
|
||||
failedUnits?: number;
|
||||
reviewRequiredUnits?: number;
|
||||
succeededUnits?: number;
|
||||
selectionBatches?: Record<string, number>;
|
||||
reviewRequiredReasonCodes?: string[];
|
||||
expansionTriggerReasonCodes?: string[];
|
||||
technicalFailureReasonCodes?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionState {
|
||||
status: ShippingOrderExtractionStatus;
|
||||
phase: 'llm_extraction' | 'result_persisted' | 'failed';
|
||||
message: string;
|
||||
created_count: number;
|
||||
opened_existing_count: number;
|
||||
pending_count: number;
|
||||
non_shipping_count: number;
|
||||
created_with_missing_fields_count: number;
|
||||
batch_no?: string | null;
|
||||
status: ShippingOrderExtractionStateStatus;
|
||||
summary: ShippingOrderExtractionStateSummary;
|
||||
currentActivity?: ShippingOrderExtractionCurrentActivityState | null;
|
||||
selectionPlan?: ShippingOrderExtractionSelectionPlanState | null;
|
||||
unitSummary?: ShippingOrderExtractionUnitSummaryState | null;
|
||||
availableActions: string[];
|
||||
terminal: boolean;
|
||||
/** 当前服务端阶段,仅用于状态卡展示。 */
|
||||
current_stage_code?: string | null;
|
||||
/** 服务端健康提示,不包含诊断详情。 */
|
||||
health?: 'normal' | 'slow' | 'idle' | string;
|
||||
last_activity_at?: string | null;
|
||||
started_at?: string | null;
|
||||
refreshFailed?: boolean;
|
||||
errorCode?: string | null;
|
||||
startedAt?: string | null;
|
||||
finishedAt?: string | null;
|
||||
}
|
||||
|
||||
/** 订单识别终态卡保存的候选审核快照,仅含用户可见业务字段。 */
|
||||
|
||||
@@ -526,6 +526,7 @@ export interface ShippingNoticeIntakeResponse {
|
||||
intake_no: string;
|
||||
asset_no?: string | null;
|
||||
conversation_id?: string | null;
|
||||
upload_batch_id?: string | null;
|
||||
parse_status: string;
|
||||
parser_version?: string;
|
||||
order_extraction_status?: string | null;
|
||||
@@ -620,13 +621,79 @@ export interface ShippingUploadAttempt {
|
||||
|
||||
export type ShippingOrderExtractionRunStatus =
|
||||
| 'queued'
|
||||
| 'running'
|
||||
| 'result_persisted'
|
||||
| 'processing'
|
||||
| 'completed'
|
||||
| 'needs_review'
|
||||
| 'partially_completed'
|
||||
| 'review_required'
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
|
||||
export type ShippingOrderExtractionDocumentStatus =
|
||||
| 'pending'
|
||||
| 'routing'
|
||||
| 'matching_profile'
|
||||
| 'extracting'
|
||||
| 'merging_supplement'
|
||||
| 'candidate_ready'
|
||||
| 'review_required'
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
|
||||
export interface ShippingOrderExtractionRunSummary {
|
||||
total_documents: number;
|
||||
pending_documents: number;
|
||||
processing_documents: number;
|
||||
completed_documents: number;
|
||||
review_required_documents: number;
|
||||
failed_documents: number;
|
||||
candidate_count: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivity {
|
||||
unit_id: number;
|
||||
file_name?: string | null;
|
||||
event_code: string;
|
||||
selection_batch?: number | null;
|
||||
reason_codes?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionProfileSummary {
|
||||
code: string;
|
||||
name?: string | null;
|
||||
version: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionEmailSupplementResult {
|
||||
status: 'none' | 'merged' | 'conflict' | string;
|
||||
relation_codes: string[];
|
||||
conflict_count: number;
|
||||
reservation_id_status?: 'none' | 'merged' | 'conflict' | 'unavailable' | string;
|
||||
source_type_status?: 'none' | 'merged' | 'conflict' | 'unavailable' | string;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionDocumentResult {
|
||||
unit_id: number;
|
||||
document_id: number;
|
||||
file_name?: string | null;
|
||||
status: ShippingOrderExtractionDocumentStatus;
|
||||
selection_batch?: number | null;
|
||||
group_key?: string | null;
|
||||
retry_status?: string | null;
|
||||
technical_failure_reason_code?: string | null;
|
||||
budget_cost?: {
|
||||
initial_attachment_budget?: number;
|
||||
initial_concurrency_budget?: number;
|
||||
selected_in_batch?: number;
|
||||
} | null;
|
||||
po_number?: string | null;
|
||||
line_count: number;
|
||||
profile?: ShippingOrderExtractionProfileSummary | null;
|
||||
email_supplement: ShippingOrderExtractionEmailSupplementResult;
|
||||
reason_code?: string | null;
|
||||
review_details?: Array<{ line_number: number; field_code?: string | null; reason_code: string }>;
|
||||
available_actions: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionRun {
|
||||
run_no: string;
|
||||
agent_id: number;
|
||||
@@ -644,15 +711,43 @@ export interface ShippingOrderExtractionRun {
|
||||
reason?: string | null;
|
||||
superseded_at?: string | null;
|
||||
} | null;
|
||||
progress?: {
|
||||
version: number;
|
||||
current_stage_code?: string | null;
|
||||
active_stage_codes?: string[];
|
||||
completed_stage_codes?: string[];
|
||||
message_code?: string | null;
|
||||
health?: string;
|
||||
last_activity_at?: string | null;
|
||||
summary: ShippingOrderExtractionRunSummary;
|
||||
selection_plan?: {
|
||||
selection_version?: string | null;
|
||||
max_initial_attachments?: number;
|
||||
max_initial_concurrency?: number;
|
||||
expansion_batch_size?: number;
|
||||
max_total_attachments?: number;
|
||||
max_total_bytes?: number;
|
||||
max_runtime_seconds?: number;
|
||||
input_total_bytes?: number;
|
||||
planned_total_bytes?: number;
|
||||
total_attachment_count?: number;
|
||||
eligible_attachment_count?: number;
|
||||
selected_attachment_count?: number;
|
||||
planned_attachment_count?: number;
|
||||
pending_expansion_attachment_count?: number;
|
||||
pending_expansion_batches?: Record<string, number>;
|
||||
skipped_attachment_count?: number;
|
||||
duplicate_attachment_count?: number;
|
||||
budget_limited_attachment_count?: number;
|
||||
group_count?: number;
|
||||
} | null;
|
||||
unit_summary?: {
|
||||
total_units?: number;
|
||||
selected_units?: number;
|
||||
retrying_units?: number;
|
||||
pending_retry_units?: number;
|
||||
failed_units?: number;
|
||||
review_required_units?: number;
|
||||
succeeded_units?: number;
|
||||
selection_batches?: Record<string, number>;
|
||||
review_required_reason_codes?: string[];
|
||||
expansion_trigger_reason_codes?: string[];
|
||||
technical_failure_reason_codes?: string[];
|
||||
} | null;
|
||||
current_activity?: ShippingOrderExtractionCurrentActivity | null;
|
||||
available_actions: string[];
|
||||
result?: {
|
||||
batch_no?: string | null;
|
||||
created_count?: number;
|
||||
@@ -670,8 +765,12 @@ export interface ShippingOrderExtractionRun {
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionProgressEvent {
|
||||
stage_code: string;
|
||||
event_code: string;
|
||||
status: string;
|
||||
unit_id?: number | null;
|
||||
document_id?: number | null;
|
||||
reason_code?: string | null;
|
||||
summary?: Record<string, unknown> | null;
|
||||
occurred_at: string;
|
||||
}
|
||||
|
||||
@@ -680,6 +779,10 @@ export interface ShippingOrderExtractionRunCreateResponse {
|
||||
reused: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionDocumentsResponse {
|
||||
items: ShippingOrderExtractionDocumentResult[];
|
||||
}
|
||||
|
||||
export interface ShippingNoticeDocumentResponse {
|
||||
id: number;
|
||||
document_type: string;
|
||||
|
||||
@@ -102,6 +102,9 @@ export interface ShippingNoticeParseAttachmentSummary {
|
||||
size?: number;
|
||||
content_hash?: string;
|
||||
parse_status?: string;
|
||||
ready_for_extraction?: boolean;
|
||||
is_inline_resource?: boolean;
|
||||
catalog_reason?: string;
|
||||
/** 详情接口才有;状态轮询为瘦身摘要不含全文 */
|
||||
extracted_text?: string;
|
||||
/** 原始解析文本长度 */
|
||||
@@ -121,6 +124,8 @@ export interface ShippingNoticeParseEmailMeta {
|
||||
body_text?: string;
|
||||
body_text_length?: number;
|
||||
stored_body_text_length?: number;
|
||||
body_html_tables?: string[];
|
||||
body_html_table_count?: number;
|
||||
}
|
||||
|
||||
export interface ShippingNoticeParseSummary {
|
||||
@@ -130,6 +135,14 @@ export interface ShippingNoticeParseSummary {
|
||||
line_count?: number;
|
||||
warnings?: string[];
|
||||
parser_version?: string;
|
||||
eml_attachment_mode?: 'deep' | 'preview' | string;
|
||||
technical_failure?: boolean;
|
||||
preview_status?: 'ready_for_extraction' | 'directory_incomplete' | 'technical_failed' | string;
|
||||
ready_for_extraction?: boolean;
|
||||
attachment_directory_complete?: boolean;
|
||||
ready_attachment_count?: number;
|
||||
directory_only_attachment_count?: number;
|
||||
duplicate_attachment_count?: number;
|
||||
email?: ShippingNoticeParseEmailMeta;
|
||||
/** 发现的真实附件总数(含因上限未登记的) */
|
||||
attachment_count?: number;
|
||||
@@ -145,6 +158,8 @@ export type ShippingNoticePendingAttachment = {
|
||||
type: 'document';
|
||||
assetNo?: string;
|
||||
intakeNo?: string;
|
||||
/** 同一次文件选择生成的服务端上传批次,发送时用于拒绝历史附件混入。 */
|
||||
uploadBatchId?: string;
|
||||
uploadStatus: ShippingNoticeUploadStatus;
|
||||
parseStatus: ShippingNoticeParseStatus;
|
||||
uploadProgress: number;
|
||||
@@ -158,7 +173,7 @@ export type ShippingNoticePendingAttachment = {
|
||||
duplicate?: ShippingDuplicateResult;
|
||||
duplicateResolution?: ShippingDuplicateResolution;
|
||||
candidates?: ShippingNoticeCandidate[];
|
||||
/** 文档版面任务汇总;processing 时不得创建订单识别 Run。 */
|
||||
/** 文档版面任务汇总;上传快览不依赖该状态,真正的深度解析由发送后的 Run 驱动。 */
|
||||
layoutStatus?: 'processing' | 'completed' | 'not_required';
|
||||
layoutSummary?: {
|
||||
total: number;
|
||||
|
||||
@@ -71,8 +71,11 @@ describe('attachment card utils', () => {
|
||||
|
||||
it('preserves shipping parsing, failure and duplicate attention states', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'parsing' })).state).toBe('processing');
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ layoutStatus: 'processing' }))).toEqual({
|
||||
state: 'processing', labelKey: 'chat.attachment.layoutProcessing',
|
||||
expect(getAttachmentCardStatus(shippingAttachment({
|
||||
layoutStatus: 'processing',
|
||||
parseSummary: { preview_status: 'ready_for_extraction', ready_for_extraction: true },
|
||||
}))).toEqual({
|
||||
state: 'ready', labelKey: 'chat.shippingNoticeReady',
|
||||
});
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'failed' }))).toEqual({
|
||||
state: 'failed', labelKey: 'chat.attachment.parseFailed',
|
||||
@@ -89,6 +92,29 @@ describe('attachment card utils', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment()).state).toBe('ready');
|
||||
});
|
||||
|
||||
it('surfaces preview directory issues without falling back to fake processing', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment({
|
||||
parseSummary: {
|
||||
preview_status: 'directory_incomplete',
|
||||
ready_for_extraction: false,
|
||||
attachment_directory_complete: false,
|
||||
},
|
||||
}))).toEqual({
|
||||
state: 'attention',
|
||||
labelKey: 'chat.shippingNoticeAttachmentIncompleteWarn',
|
||||
});
|
||||
expect(getAttachmentCardStatus(shippingAttachment({
|
||||
parseSummary: {
|
||||
preview_status: 'technical_failed',
|
||||
technical_failure: true,
|
||||
ready_for_extraction: false,
|
||||
},
|
||||
}))).toEqual({
|
||||
state: 'failed',
|
||||
labelKey: 'chat.attachment.parseFailed',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows the order extraction lifecycle separately from attachment parsing', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'extracting' }))).toEqual({
|
||||
state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing',
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import type { ChatMessageAttachment } from '../types/chat.types';
|
||||
import type { AttachmentUiStatus, PendingAttachment } from '../types/shipping.types';
|
||||
import { isShippingNoticeAttachmentParseIncomplete } from '../shipping/shippingNoticeAttachmentIntegrity';
|
||||
|
||||
export interface AttachmentCardStatus {
|
||||
state: AttachmentUiStatus;
|
||||
@@ -70,9 +71,6 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme
|
||||
return { state: 'processing', labelKey: 'chat.attachment.processing' };
|
||||
}
|
||||
if (attachment.parseStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.parseFailed' };
|
||||
if (attachment.layoutStatus === 'processing') {
|
||||
return { state: 'processing', labelKey: 'chat.attachment.layoutProcessing' };
|
||||
}
|
||||
const extractionStatus = String(attachment.orderExtractionStatus || '').trim().toLowerCase();
|
||||
if (extractionStatus === 'extracting') {
|
||||
return { state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing' };
|
||||
@@ -87,6 +85,13 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme
|
||||
return { state: 'ready', labelKey: 'chat.shippingOrderExtractionCompleted' };
|
||||
}
|
||||
if (attachment.parseStatus === 'parsed' && !attachment.duplicateResolution?.action) {
|
||||
if (isShippingNoticeAttachmentParseIncomplete(attachment.parseSummary)) {
|
||||
const previewStatus = String(attachment.parseSummary?.preview_status || '').trim().toLowerCase();
|
||||
if (attachment.parseSummary?.technical_failure || previewStatus === 'technical_failed') {
|
||||
return { state: 'failed', labelKey: 'chat.attachment.parseFailed' };
|
||||
}
|
||||
return { state: 'attention', labelKey: 'chat.shippingNoticeAttachmentIncompleteWarn' };
|
||||
}
|
||||
if (attachment.duplicate?.blocking) {
|
||||
return { state: 'attention', labelKey: 'chat.shippingNoticeDuplicateBlockingBadge' };
|
||||
}
|
||||
@@ -95,7 +100,7 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme
|
||||
}
|
||||
}
|
||||
if (attachment.parseStatus === 'parsed' || attachment.parseStatus === 'consumed') {
|
||||
return { state: 'ready', labelKey: 'chat.attachment.ready' };
|
||||
return { state: 'ready', labelKey: 'chat.shippingNoticeReady' };
|
||||
}
|
||||
return { state: 'pending', labelKey: 'chat.attachment.pending' };
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user