refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段
统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成 设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程 删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本 替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段 更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
This commit is contained in:
1 parent
6684e7181a
commit
5ef8329bd8
178 files changed
+5091
-1734
No files matched your search
@@ -14,6 +14,7 @@ import {
|
||||
normalizeShippingProcessingProjection,
|
||||
normalizeShippingProcessingWorkItems,
|
||||
} from '../shipping/normalizeShippingProcessing';
|
||||
import { normalizeConversationProcessingProjection } from '../shipping/conversationProcessingProjection';
|
||||
import type {
|
||||
ShippingDecisionResponse,
|
||||
ShippingOrderExtractionDocumentsResponse,
|
||||
@@ -131,14 +132,12 @@ const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<str
|
||||
// #endregion
|
||||
|
||||
export const listWorkspaceShippingTasks = (params?: {
|
||||
process_status?: string;
|
||||
lifecycle_status?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}) => {
|
||||
/** 拉取当前用户可见的发货任务列表。 */
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.process_status) sp.set('process_status', params.process_status);
|
||||
if (params?.lifecycle_status) sp.set('lifecycle_status', params.lifecycle_status);
|
||||
if (params?.page) sp.set('page', String(params.page));
|
||||
if (params?.page_size) sp.set('page_size', String(params.page_size));
|
||||
@@ -258,7 +257,11 @@ export const getWorkspaceShippingProcessing = async (
|
||||
.then((raw): WorkspaceShippingProcessingResponse => ({
|
||||
conversation_id: String(raw?.conversation_id || normalized),
|
||||
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
|
||||
conversation_processing: raw?.conversation_processing ?? null,
|
||||
// 会话级 status_groups / 四阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
|
||||
// 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。
|
||||
conversation_processing: raw?.conversation_processing
|
||||
? normalizeConversationProcessingProjection(raw.conversation_processing)
|
||||
: null,
|
||||
}))
|
||||
.finally(() => {
|
||||
clearTimeout(timeout);
|
||||
@@ -934,6 +937,12 @@ export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Pr
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
/** 读取当前 Case 同 Intake 的已解析邮件正文证据;不暴露原始 EML 或附件。 */
|
||||
export const getWorkspaceShippingOrderReviewEmailEvidencePreview = (caseNo: string, documentId: number) =>
|
||||
requestJson<{ document_id: number; document_type: 'email_body'; filename: string; text: string }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/email-evidence-preview/${documentId}`,
|
||||
);
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string, uploadBatchId?: string | null) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
|
||||
@@ -48,6 +48,7 @@ const {
|
||||
pinMessagesToBottom?: boolean;
|
||||
/** 供父级滚动逻辑绑定 main 元素 */
|
||||
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
||||
compactShippingProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -61,6 +62,7 @@ const emit = defineEmits<{
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const bindScrollContainer = (node: unknown) => {
|
||||
@@ -166,6 +168,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
:leave-handlers="leaveHandlers"
|
||||
:shipping-handlers="shippingHandlers"
|
||||
:training-handlers="trainingHandlers"
|
||||
:compact-shipping-progress="compactShippingProgress"
|
||||
@copy="emit('copy', { message: msg, index })"
|
||||
@edit="emit('edit', $event)"
|
||||
@resend="emit('resend', $event)"
|
||||
@@ -174,6 +177,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
@maintenance-edit-record="emit('maintenance-edit-record', $event)"
|
||||
@maintenance-view-record-history="emit('maintenance-view-record-history', $event)"
|
||||
@maintenance-create-record-for-device="emit('maintenance-create-record-for-device', $event)"
|
||||
@open-batch-workbench="emit('open-batch-workbench')"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
|
||||
@@ -88,7 +88,8 @@ const route = useRoute();
|
||||
|
||||
const shippingProcessing = useShippingNoticeWorkflow({
|
||||
// 历史会话首屏直接使用路由 ID,与聊天消息并行拉取统一进度。
|
||||
conversationId: () => page.conversationId || String(route.query.conversation_id || ''),
|
||||
// 路由切换先于 page 历史消息回填;必须先切换 Projection,禁止短暂复用旧会话卡片。
|
||||
conversationId: () => String(route.query.conversation_id || page.conversationId || ''),
|
||||
refreshTrigger: () => page.workflowRefreshTrigger,
|
||||
});
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
|
||||
@@ -151,13 +152,39 @@ const activeExtractionRunNo = computed(() => {
|
||||
|
||||
});
|
||||
|
||||
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
|
||||
const batchWorkbenchOpen = ref(false);
|
||||
|
||||
|
||||
|
||||
const showShippingWorkflowTimeline = computed(() => (
|
||||
page.isShippingNoticeAgent
|
||||
&& batchWorkbenchOpen.value
|
||||
&& Boolean(page.conversationId || activeExtractionRunNo.value)
|
||||
));
|
||||
|
||||
const compactShippingProgress = computed(() => batchWorkbenchOpen.value);
|
||||
|
||||
function openBatchWorkbench() {
|
||||
batchWorkbenchOpen.value = true;
|
||||
}
|
||||
|
||||
function closeBatchWorkbench() {
|
||||
batchWorkbenchOpen.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批次中心只服务于用户主动打开时所在的会话。切换历史会话或 Agent 后必须关闭,
|
||||
* 否则旧会话的右侧投影会短暂占用新会话的对话区并造成“本次处理”串批错觉。
|
||||
*/
|
||||
watch(
|
||||
() => [String(page.conversationId || ''), Number(page.currentAgentId || 0)] as const,
|
||||
(next, previous) => {
|
||||
if (!previous || next[0] === previous[0] && next[1] === previous[1]) return;
|
||||
batchWorkbenchOpen.value = false;
|
||||
},
|
||||
);
|
||||
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
|
||||
const agent = page.currentAgent;
|
||||
@@ -480,9 +507,9 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
<ShippingOrderReviewView v-if="isOrderReviewMode" />
|
||||
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1" :class="showShippingWorkflowTimeline ? 'shipping-workbench-layout' : ''">
|
||||
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col" :class="showShippingWorkflowTimeline ? 'shipping-chat-column' : ''">
|
||||
|
||||
<TrainingWorkspacePanel
|
||||
|
||||
@@ -560,6 +587,8 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
|
||||
:compact-shipping-progress="compactShippingProgress"
|
||||
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
|
||||
@edit="page.input = $event"
|
||||
@@ -580,6 +609,8 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
|
||||
|
||||
@open-batch-workbench="openBatchWorkbench"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
@@ -666,6 +697,8 @@ watch(() => page.currentAgentId, () => {
|
||||
:conversation-id="page.conversationId"
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingProcessing"
|
||||
|
||||
@close="closeBatchWorkbench"
|
||||
/>
|
||||
|
||||
|
||||
@@ -816,3 +849,16 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/** 打开批次工作台后,左侧对话保留为压缩入口,右侧取得主工作区宽度。 */
|
||||
@media (min-width: 1024px) {
|
||||
.shipping-workbench-layout {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.shipping-chat-column {
|
||||
flex: 0 0 clamp(360px, 32vw, 520px);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/ShippingWorkflowStepper.vue
|
||||
* 用途:货代发货七步流程 Stepper 展示组件。
|
||||
* 用途:货代发货四阶段 Stepper 展示组件。
|
||||
* 依赖:shipping/shippingStepper、vue-i18n。
|
||||
* 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。
|
||||
*/
|
||||
@@ -33,7 +33,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4 xl:grid-cols-7' : 'md:grid-cols-4 xl:grid-cols-7'">
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4' : 'md:grid-cols-4'">
|
||||
<div
|
||||
v-for="(step, index) in steps"
|
||||
:key="step.id"
|
||||
|
||||
@@ -72,6 +72,7 @@ const {
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMessageHandlers;
|
||||
trainingHandlers: TrainingHandlers;
|
||||
compactShippingProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -83,6 +84,7 @@ const emit = defineEmits<{
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const authStore = useAuthStore();
|
||||
@@ -712,7 +714,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
: isContractReviewMessage
|
||||
? 'w-full'
|
||||
: 'chat-msg-assistant'"
|
||||
: shippingOrderExtractionState
|
||||
? 'w-full'
|
||||
: 'chat-msg-assistant'"
|
||||
>
|
||||
<template v-if="message.role === 'user'">
|
||||
<ChatMessageAttachmentList
|
||||
@@ -731,9 +735,11 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:retrying="retryingOrderExtraction"
|
||||
:refreshing="refreshingOrderExtraction"
|
||||
:cancelling="cancellingOrderExtraction"
|
||||
:compact-progress="compactShippingProgress"
|
||||
@retry="retryShippingOrderExtraction"
|
||||
@refresh="refreshShippingOrderExtraction"
|
||||
@cancel="cancelShippingOrderExtraction"
|
||||
@open-batch-workbench="emit('open-batch-workbench')"
|
||||
/>
|
||||
<LeaveMessageBlock
|
||||
v-if="isLeaveMessage"
|
||||
|
||||
+5
-1
@@ -44,6 +44,7 @@ const props = defineProps<{
|
||||
docked: boolean;
|
||||
floatSide: 'right' | 'left';
|
||||
src: string;
|
||||
emailPreview?: { document_id: number; filename: string; text: string } | null;
|
||||
evidence: ShippingOrderReviewEvidence | null;
|
||||
evidenceList: ShippingOrderReviewEvidence[];
|
||||
fieldLabel?: string;
|
||||
@@ -729,8 +730,11 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
|
||||
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
|
||||
<div v-if="emailPreview" class="min-h-0 overflow-auto whitespace-pre-wrap p-4 font-mono text-xs leading-6 text-slate-700 dark:text-slate-200" data-testid="review-email-evidence-preview">
|
||||
{{ emailPreview.text }}
|
||||
</div>
|
||||
<ReviewDocumentPreview
|
||||
v-if="src"
|
||||
v-else-if="src"
|
||||
class="min-h-0"
|
||||
:src="src"
|
||||
:evidence="evidence"
|
||||
|
||||
@@ -172,7 +172,7 @@ defineExpose({
|
||||
{{ t('chat.shippingNoticeDuplicateMatchTask', { taskNo: primaryMatch.task_no }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-muted">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.process_status }) }}
|
||||
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.lifecycle || 'active' }) }}
|
||||
</div>
|
||||
<div v-if="primaryMatch.matched_fields?.length" class="mt-0.5 text-muted">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: primaryMatch.matched_fields.join(', ') }) }}
|
||||
|
||||
+221
-45
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingConversationProcessingCard.vue
|
||||
* 用途:右侧「本次处理中」顶层任务卡——needs_action / processing / 处理记录。
|
||||
* 用途:右侧「批次进度中心」顶层任务卡——needs_action / processing / 处理记录。
|
||||
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
|
||||
* conversationProcessingDisplay、actionPresentation、shippingProcessingLabels、SidebarProgressInline。
|
||||
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems;
|
||||
@@ -33,7 +33,8 @@ import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveConversationTaskActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import { flattenBusinessFileProjections } from '@/features/chat/shipping/conversationProcessingProjection';
|
||||
import { resolveConversationTaskActionPresentation, resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import SidebarProgressInline from '@/features/shipping-progress/components/SidebarProgressInline.vue';
|
||||
import type { ActionPresentation, ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
|
||||
@@ -45,6 +46,8 @@ const props = defineProps<{
|
||||
conversationId?: string | null;
|
||||
/** 后端截断提示:history 还有未返回内容时在处理记录底部展示 */
|
||||
hasMoreHistory?: boolean;
|
||||
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
|
||||
workbenchMode?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -65,6 +68,17 @@ const uiState = createConversationProcessingUiState();
|
||||
/** 处理记录整组默认折叠。 */
|
||||
const historySectionExpanded = ref(false);
|
||||
|
||||
/** 批次中心文件叶子行;EML 仅是聚合容器,文件状态、原因与动作必须取叶子自身投影。 */
|
||||
type WorkbenchFileRow = {
|
||||
kind: 'document';
|
||||
object_key: string;
|
||||
label: string;
|
||||
filename?: string | null;
|
||||
document_id?: number | null;
|
||||
status_label?: string | null;
|
||||
projection?: ShippingProcessingProjection;
|
||||
};
|
||||
|
||||
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
|
||||
const activeProjection = computed((): ConversationProcessingProjection | null => (
|
||||
props.projection || null
|
||||
@@ -185,6 +199,7 @@ function canExpandFileDetails(task: ConversationProcessingUserTask): boolean {
|
||||
* 处理记录(completed/history)永不展实时进度。
|
||||
*/
|
||||
function progressModeForTask(task: ConversationProcessingUserTask): 'full' | 'compact' | 'hidden' {
|
||||
if (props.workbenchMode) return 'hidden';
|
||||
if (!projectionForTask(task)) return 'hidden';
|
||||
const group = String(task.group || '').trim();
|
||||
if (group === 'completed' || group === 'history') return 'hidden';
|
||||
@@ -202,6 +217,137 @@ function taskLabel(_task: ConversationProcessingUserTask): string {
|
||||
return t('chat.shippingProcessing.multiPdfTaskTitle');
|
||||
}
|
||||
|
||||
/** EML 聚合标题优先使用后端邮件文件名,普通文件则显示主文件名。 */
|
||||
function groupTitle(task: ConversationProcessingUserTask): string {
|
||||
const projection = projectionForTask(task);
|
||||
const children = task.aggregateChildren || [];
|
||||
const projectionFilename = String(projection?.sourceSummary?.filename || '').trim();
|
||||
const emlChild = children.find((child) => (
|
||||
String(child.sourceSummary?.filename || '').trim().toLowerCase().endsWith('.eml')
|
||||
));
|
||||
const emailChild = children.find((child) => Boolean(child.sourceSummary?.emailSubject));
|
||||
const isEml = projection?.sourceType === 'eml'
|
||||
&& Boolean(
|
||||
emlChild
|
||||
|| emailChild
|
||||
|| projection?.sourceSummary?.emailSubject
|
||||
|| projectionFilename.toLowerCase().endsWith('.eml'),
|
||||
);
|
||||
if (!isEml) return projection?.sourceSummary?.filename || task.title || taskLabel(task);
|
||||
// 后端在 EML 聚合根 sourceSummary 写入 Intake 原始邮件资产名;子附件列表不含
|
||||
// 邮件本体时仍必须显示该 .eml,不能回退成 Intake 编号或任一 PDF 文件名。
|
||||
if (projectionFilename.toLowerCase().endsWith('.eml')) return projectionFilename;
|
||||
if (emlChild?.sourceSummary?.filename) return emlChild.sourceSummary.filename;
|
||||
if (projection?.sourceSummary?.emailSubject) return `EML · ${projection.sourceSummary.emailSubject}`;
|
||||
if (emailChild?.sourceSummary?.emailSubject) return `EML · ${emailChild.sourceSummary.emailSubject}`;
|
||||
if (task.aggregateSummary?.intakeNo) {
|
||||
return `EML · ${task.aggregateSummary?.intakeNo || task.user_task_no}`;
|
||||
}
|
||||
return task.title || taskLabel(task);
|
||||
}
|
||||
|
||||
/** 工作台文件行:只展示后端 document objects,避免用任务标题冒充文件。 */
|
||||
function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
|
||||
const children = task.aggregateChildren || [];
|
||||
if (children.length) {
|
||||
return flattenBusinessFileProjections(children).map((child, index) => {
|
||||
const filename = String(child.sourceSummary?.filename || '').trim();
|
||||
const documentId = Number(child.sourceSummary?.documentId || 0) || 0;
|
||||
return {
|
||||
kind: 'document' as const,
|
||||
object_key: documentId ? `DOC-${documentId}` : `${task.user_task_no}-aggregate-${child.workItemNo || index}`,
|
||||
label: filename || child.workItemNo || `文件 ${index + 1}`,
|
||||
filename: filename || child.workItemNo || `文件 ${index + 1}`,
|
||||
status_label: String(child.uiState?.status || child.userStatus || child.status || ''),
|
||||
projection: child,
|
||||
};
|
||||
});
|
||||
}
|
||||
const documents = (task.objects || []).filter((item) => (
|
||||
item.kind === 'document'
|
||||
&& !String(item.filename || item.label || '').trim().toLowerCase().endsWith('.eml')
|
||||
));
|
||||
if (documents.length) {
|
||||
// direct_pdf 没有 EML aggregate_children;将唯一根 work_item 绑定到其文件行,
|
||||
// 使状态、原因和操作仍然来自同一份后端 ui_state,而不是丢失操作或回退 legacy 字段。
|
||||
const directFileProjection = projectionForTask(task);
|
||||
return documents.map((item) => ({
|
||||
kind: 'document' as const,
|
||||
object_key: item.object_key,
|
||||
label: item.label,
|
||||
filename: item.filename,
|
||||
document_id: item.document_id,
|
||||
status_label: item.status_label,
|
||||
projection: directFileProjection?.sourceType === 'direct_pdf'
|
||||
? directFileProjection
|
||||
: undefined,
|
||||
}));
|
||||
}
|
||||
const taskName = String(task.title || '').trim().toLowerCase();
|
||||
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
|
||||
return (task.document_names || []).map((filename, index) => ({
|
||||
kind: 'document' as const,
|
||||
object_key: `${task.user_task_no}-document-${index}`,
|
||||
label: filename,
|
||||
filename,
|
||||
status_label: task.status_label,
|
||||
}));
|
||||
}
|
||||
|
||||
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
|
||||
function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
|
||||
const seen = new Set<string>();
|
||||
return tasks.reduce((total, task) => total + workbenchFileRows(task).reduce((count, file) => {
|
||||
const filename = String(file.filename || file.label || '').trim().toLowerCase();
|
||||
if (filename.endsWith('.eml')) return count;
|
||||
const key = String(('document_id' in file ? file.document_id : undefined)
|
||||
|| file.object_key || file.filename || file.label || '').trim();
|
||||
if (!key || seen.has(key)) return count;
|
||||
seen.add(key);
|
||||
return count + 1;
|
||||
}, 0), 0);
|
||||
}
|
||||
|
||||
function workbenchFileStatus(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
|
||||
const status = file.projection
|
||||
? (file.projection.uiState?.status || file.projection.userStatus || file.projection.status)
|
||||
: (file.status_label || task.status_label || '');
|
||||
return resolveShippingProcessingStatusLabel(String(status), te, t);
|
||||
}
|
||||
|
||||
function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
|
||||
if (file.projection) {
|
||||
const reason = file.projection.uiState
|
||||
? file.projection.uiState.blocking_reason
|
||||
: file.projection.blockingReason;
|
||||
if (!reason) return '';
|
||||
const key = String(reason.i18nKey || '').trim();
|
||||
return key && te(key) ? t(key) : String(reason.code || '').trim();
|
||||
}
|
||||
return taskReasonLabel(task);
|
||||
}
|
||||
|
||||
/** 附件阶段来自叶子 ui_state;EML 父阶段只适用于 EML 卡,不得复制到不同状态的附件。 */
|
||||
function workbenchFileStage(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
|
||||
const stage = file.projection
|
||||
? (file.projection.uiState?.stage || file.projection.userStage || file.projection.stage)
|
||||
: stageLabel(task);
|
||||
const key = shippingProcessingStageKey(String(stage || ''));
|
||||
return key && te(key) ? t(key) : String(stage || '');
|
||||
}
|
||||
|
||||
/** 叶子文件动作由自身 ui_state 裁决;没有叶子投影时不伪造可操作按钮。 */
|
||||
function filePrimaryActionItem(file: WorkbenchFileRow): ActionPresentationItem | null {
|
||||
return file.projection
|
||||
? resolveProcessingActionPresentation(file.projection, { surface: 'right' }).primary
|
||||
: null;
|
||||
}
|
||||
|
||||
function onFileProjectionAction(file: WorkbenchFileRow) {
|
||||
const action = filePrimaryActionItem(file);
|
||||
if (file.projection && action) emit('projectionAction', { projection: file.projection, item: action });
|
||||
}
|
||||
|
||||
/**
|
||||
* 主文件副标题:有主文件名时渲染「主文件:{name}」。
|
||||
*/
|
||||
@@ -227,7 +373,11 @@ function fileCountLabel(task: ConversationProcessingUserTask): string {
|
||||
* 任务状态文案:优先统一 shippingProcessing,回退 shippingWorkflow。
|
||||
*/
|
||||
function statusLabel(task: ConversationProcessingUserTask): string {
|
||||
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
|
||||
return resolveShippingProcessingStatusLabel(
|
||||
String(task.uiState?.status || task.userStatus || task.status_label || ''),
|
||||
te,
|
||||
t,
|
||||
);
|
||||
}
|
||||
|
||||
/** 展示统一投影的真实履约阶段;识别候选不再冒充最终完成。 */
|
||||
@@ -237,17 +387,16 @@ function stageLabel(task: ConversationProcessingUserTask): string {
|
||||
return intakeStageLabel(projection);
|
||||
}
|
||||
|
||||
/** 展示后端统一投影的阻断/失败原因,不从状态码自行猜测。 */
|
||||
/** 展示后端 ui_state 已裁决的阻断原因;i18n 仅负责翻译,不映射或猜测业务原因。 */
|
||||
function taskReasonLabel(task: ConversationProcessingUserTask): string {
|
||||
const code = String(task.blockingReason?.code || task.aggregateSummary?.reasonCodes[0] || '').trim();
|
||||
if (!code) return '';
|
||||
const messages: Record<string, string> = {
|
||||
'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED': '识别结果需要人工确认,请进入订单处理继续。',
|
||||
'generic_extraction_disabled': '当前文件暂不支持自动解析,请人工处理或更换文件。',
|
||||
'SHIPPING_NOTICE.INTAKE_PARSE_FAILED': '邮件或附件解析失败,请检查文件后重试。',
|
||||
'upload_rpa_failed': '上传货代系统失败,请稍后重试。',
|
||||
};
|
||||
return messages[code] || '文件处理需要人工确认,请进入订单处理查看。';
|
||||
const reason = task.uiState
|
||||
? task.uiState.blocking_reason
|
||||
: task.blockingReason;
|
||||
if (!reason) return '';
|
||||
const key = String(reason.i18nKey || '').trim();
|
||||
if (key && te(key)) return t(key);
|
||||
// 未升级响应没有 i18n_key 时仅透传后端原因码,不根据文件名、状态或动作伪造说明。
|
||||
return String(reason.code || '').trim();
|
||||
}
|
||||
|
||||
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
|
||||
@@ -300,10 +449,14 @@ function currentNeedLabel(task: ConversationProcessingUserTask): string {
|
||||
primaryAction?: { code?: string } | null;
|
||||
};
|
||||
const action = String(
|
||||
typedTask.primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? task.available_actions?.[0]
|
||||
?? '',
|
||||
task.uiState
|
||||
? (task.uiState.primary_action?.code
|
||||
?? task.uiState.secondary_actions.find((item) => item.enabled)?.code
|
||||
?? '')
|
||||
: (typedTask.primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? task.available_actions?.[0]
|
||||
?? ''),
|
||||
).trim().toLowerCase();
|
||||
const labels: Record<string, string> = {
|
||||
confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer',
|
||||
@@ -356,6 +509,7 @@ function shouldShowOverflowActions(_task: ConversationProcessingUserTask): boole
|
||||
* 是否渲染任务级主/次动作区(不含「展开文件详情」文件控制)。
|
||||
*/
|
||||
function shouldShowTaskLevelActions(task: ConversationProcessingUserTask): boolean {
|
||||
if (props.workbenchMode) return Boolean(primaryActionItem(task));
|
||||
if (projectionForTask(task)) return false;
|
||||
return Boolean(primaryActionItem(task) || secondaryActionItem(task));
|
||||
}
|
||||
@@ -441,7 +595,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
data-testid="shipping-processing-group-failed"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
{{ t('chat.shippingProcessing.groupFailed', { count: failedTasks.length }) }}
|
||||
{{ t('chat.shippingProcessing.batchWorkbench.groups.failed', { count: groupFileCount(failedTasks) }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
@@ -463,15 +617,13 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
@click="onSelectTask(task)"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
v-if="!workbenchMode && primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
@@ -496,15 +648,18 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="task.group === 'needs_action' && currentNeedLabel(task)"
|
||||
class="mt-1 text-[11px] text-secondary"
|
||||
data-testid="shipping-processing-current-need"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-rose-200/70 pt-2">
|
||||
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-white/70 px-2 py-2 dark:bg-slate-950/30">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div>
|
||||
<div v-if="workbenchFileReason(file, task)" class="mt-0.5 truncate text-[11px] text-rose-600 dark:text-rose-300">{{ workbenchFileReason(file, task) }}</div>
|
||||
</div>
|
||||
<span class="shrink-0 rounded-full bg-rose-100 px-2 py-0.5 text-[11px] font-medium text-rose-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.failedFallback') }}</span>
|
||||
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md border border-rose-300 px-2.5 py-1 text-[11px] font-medium text-rose-700 hover:bg-rose-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
v-if="!workbenchMode && progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@@ -516,7 +671,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-if="!projectionForTask(task) && primaryActionItem(task)"
|
||||
v-if="(!workbenchMode && !projectionForTask(task)) && primaryActionItem(task)"
|
||||
type="button"
|
||||
class="rounded-md border border-brand-300 bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700 dark:border-brand-700 dark:bg-brand-700 dark:hover:bg-brand-600"
|
||||
:data-testid="`shipping-processing-action-${primaryActionItem(task)!.actionCode}`"
|
||||
@@ -535,7 +690,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
data-testid="shipping-processing-group-waiting_human"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
{{ t('chat.shippingProcessing.groupWaitingHuman', { count: waitingHumanTasks.length }) }}
|
||||
{{ t('chat.shippingProcessing.batchWorkbench.groups.waitingHuman', { count: groupFileCount(waitingHumanTasks) }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
@@ -546,23 +701,38 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
|
||||
>
|
||||
<button type="button" class="w-full text-left" @click="onSelectTask(task)">
|
||||
<div class="text-sm font-semibold text-primary">{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<div class="text-sm font-semibold text-primary">{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
|
||||
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
|
||||
</button>
|
||||
<div v-if="currentNeedLabel(task)" class="mt-1 text-[11px] text-secondary">{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}</div>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-amber-200/70 pt-2">
|
||||
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-white/70 px-2 py-2 dark:bg-slate-950/30">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div>
|
||||
<div v-if="workbenchFileReason(file, task)" class="mt-0.5 truncate text-[11px] text-rose-600 dark:text-rose-300">{{ workbenchFileReason(file, task) }}</div>
|
||||
</div>
|
||||
<span class="shrink-0 rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium text-amber-800">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.waitingFallback') }}</span>
|
||||
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<SidebarProgressInline
|
||||
v-if="projectionForTask(task)"
|
||||
v-if="!workbenchMode && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="false"
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<button
|
||||
v-if="!workbenchMode && primaryActionItem(task)"
|
||||
type="button"
|
||||
class="mt-2 rounded-md bg-brand-600 px-2.5 py-1.5 text-[11px] font-medium text-white hover:bg-brand-700"
|
||||
@click="onTaskAction(task, primaryActionItem(task)!.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
@@ -572,7 +742,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
data-testid="shipping-processing-group-processing"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
|
||||
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: processingTasks.length }) }}
|
||||
{{ t('chat.shippingProcessing.batchWorkbench.groups.processing', { count: groupFileCount(processingTasks) }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
@@ -591,14 +761,13 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
@click="onSelectTask(task)"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
v-if="!workbenchMode && primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
@@ -620,8 +789,15 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-sky-200/70 pt-2">
|
||||
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-surface-muted/40 px-2 py-2">
|
||||
<div class="min-w-0 flex-1"><div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div><div class="mt-0.5 text-[11px] text-secondary">{{ workbenchFileStage(file, task) || t('chat.shippingProcessing.batchWorkbench.fileProcessing') }}</div></div>
|
||||
<span class="shrink-0 rounded-full bg-sky-100 px-2 py-0.5 text-[11px] font-medium text-sky-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.processingFallback') }}</span>
|
||||
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md border border-brand-300 px-2.5 py-1 text-[11px] font-medium text-brand-700 hover:bg-brand-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
v-if="!workbenchMode && progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@@ -633,7 +809,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-if="!projectionForTask(task) && primaryActionItem(task)"
|
||||
v-if="!workbenchMode && !projectionForTask(task) && primaryActionItem(task)"
|
||||
type="button"
|
||||
class="rounded-md border border-brand-300 bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700 dark:border-brand-700 dark:bg-brand-700 dark:hover:bg-brand-600"
|
||||
:data-testid="`shipping-processing-action-${primaryActionItem(task)!.actionCode}`"
|
||||
|
||||
+122
-15
@@ -53,6 +53,40 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
it('opens the authoritative conversation batch even when no single run number is available', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState() },
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
provide: {
|
||||
[SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({
|
||||
status_groups: {
|
||||
failed: [], waiting_human: [], processing: [{
|
||||
user_task_no: 'INTAKE:SNI-BATCH', title: 'batch.eml', file_count: 1,
|
||||
userGroup: 'processing', group: 'processing', aggregateChildren: [],
|
||||
}], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
}),
|
||||
processingWorkItems: ref([]),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('collapses file-level progress when the batch workbench is open', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-COMPACT', compactProgress: true },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-status-groups"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses unified EML aggregation and keeps candidate creation out of completed', async () => {
|
||||
const aggregate = {
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1',
|
||||
@@ -99,13 +133,61 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
|
||||
});
|
||||
|
||||
it('does not render a historical EML snapshot while the authoritative conversation projection is loading', () => {
|
||||
const historicalAggregate = {
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-HISTORY', sourceType: 'eml', intakeNo: 'SNI-HISTORY',
|
||||
sourceSummary: { filename: 'historical.eml', documentCount: 3 },
|
||||
aggregateSummary: { intakeNo: 'SNI-HISTORY', total: 3, completed: 0, processing: 3, needsAction: 0, failed: 0, stages: [], reasonCodes: [] },
|
||||
aggregateChildren: [],
|
||||
} as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-HISTORY' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref(null),
|
||||
processingWorkItems: ref([historicalAggregate]),
|
||||
initialLoading: ref(true),
|
||||
loading: ref(true),
|
||||
} } },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-eml-aggregate"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-projection-loading"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).not.toContain('historical.eml');
|
||||
expect(wrapper.text()).not.toContain('系统处理中');
|
||||
});
|
||||
|
||||
it('does not render message document rows while the authoritative projection is loading', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({
|
||||
documents: [{
|
||||
unitId: 91,
|
||||
documentId: 191,
|
||||
documentType: 'attachment',
|
||||
fileName: 'message-snapshot.pdf',
|
||||
status: 'review_required',
|
||||
}],
|
||||
}) },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref(null),
|
||||
processingWorkItems: ref([]),
|
||||
initialLoading: ref(true),
|
||||
loading: ref(true),
|
||||
} } },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).not.toContain('message-snapshot.pdf');
|
||||
expect(wrapper.text()).not.toContain('系统处理中');
|
||||
});
|
||||
|
||||
it('expands an EML inside its status group and shows every child attachment state', async () => {
|
||||
const child = {
|
||||
workItemType: 'order_task', workItemNo: 'OT-CHILD-1', sourceType: 'eml', rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null, runNo: 'SNER-DETAIL', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-DETAIL',
|
||||
status: 'failed', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'failed.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null },
|
||||
childOrderTasks: [], userStatus: 'failed', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
|
||||
childOrderTasks: [], userStatus: 'running', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
|
||||
// 后端新裁决与旧 userStatus 冲突时,摘要卡必须使用 ui_state,不能显示成“处理中”。
|
||||
uiState: { status: 'failed', stage: 'document_parsing', blocking_reason: { code: 'PARSE_FAILED' }, primary_action: null, secondary_actions: [] },
|
||||
blockingReason: { code: 'PARSE_FAILED' },
|
||||
} as any;
|
||||
const task = { user_task_no: 'INTAKE:SNI-DETAIL', title: 'mail.eml', file_count: 1, userGroup: 'failed', group: 'needs_action', aggregateChildren: [child], aggregateSummary: { intakeNo: 'SNI-DETAIL', total: 1, completed: 0, processing: 0, needsAction: 0, failed: 1, stages: ['document_parsing'], reasonCodes: ['PARSE_FAILED'] } } as any;
|
||||
@@ -126,9 +208,11 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('异常 1');
|
||||
expect(wrapper.text()).toContain('文件处理需要人工确认');
|
||||
expect(wrapper.text()).not.toContain('PARSE_FAILED');
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-child-status-OT-CHILD-1"]')
|
||||
.classes()).toContain('text-rose-600');
|
||||
});
|
||||
|
||||
it('falls back to the matched work item children when the status task only has a summary', async () => {
|
||||
it('does not supplement an authoritative EML group from a second work-item snapshot', async () => {
|
||||
const child = {
|
||||
workItemType: 'order_task', workItemNo: 'OT-FALLBACK-1', sourceType: 'eml', rootOrderTaskNo: 'OT-FALLBACK',
|
||||
shippingNoticeNo: null, runNo: 'SNER-FALLBACK', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-FALLBACK',
|
||||
@@ -145,7 +229,32 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
} } },
|
||||
});
|
||||
await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-FALLBACK"] button').trigger('click');
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('inside.eml.pdf');
|
||||
// 状态组出现后,子文件必须完全来自该组;不能用另一份 work_items 补数。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-eml-children"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('inside.eml.pdf');
|
||||
});
|
||||
|
||||
it('uses the conversation projection total instead of the message Run snapshot total', () => {
|
||||
const task = {
|
||||
user_task_no: 'INTAKE:SNI-TOTAL', title: 'mail-total.eml', file_count: 2,
|
||||
userGroup: 'waiting_human', group: 'needs_action', aggregateChildren: [],
|
||||
aggregateSummary: { intakeNo: 'SNI-TOTAL', total: 2, completed: 0, processing: 0, needsAction: 2, failed: 0, stages: ['order_review'], reasonCodes: [] },
|
||||
} as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({ summary: { ...buildState().summary, totalDocuments: 6 } }), runNo: 'SNER-TOTAL' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({
|
||||
summary: { total_files: 2, completed_files: 0, waiting_human_files: 2, failed_files: 0 },
|
||||
ui_state: { status: 'waiting_human' },
|
||||
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
|
||||
}),
|
||||
processingWorkItems: ref([{ sourceType: 'eml', intakeNo: 'SNI-TOTAL', aggregateChildren: [{ sourceSummary: { filename: 'stale.pdf' } }] }]),
|
||||
} } },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('共 2 个文件');
|
||||
expect(wrapper.text()).not.toContain('共 6 个文件');
|
||||
expect(wrapper.text()).not.toContain('stale.pdf');
|
||||
});
|
||||
|
||||
it('counts unique EML attachment children instead of task rows', async () => {
|
||||
@@ -481,7 +590,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('重试解析');
|
||||
});
|
||||
|
||||
it('shows continue CTA for review-required without retry', () => {
|
||||
it('keeps only the batch workbench CTA for review-required without retry', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -511,8 +620,9 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('继续处理');
|
||||
expect(wrapper.text()).not.toContain('重试解析');
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-view-details"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('does not render multi-OT ChatProgressSummary list', () => {
|
||||
@@ -576,10 +686,10 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
});
|
||||
expect(wrapper.findAll('[data-testid="chat-progress-summary-list"]').length).toBe(0);
|
||||
expect(wrapper.text()).not.toContain('PO.pdf');
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('继续处理');
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments via primary CTA', async () => {
|
||||
it('keeps retry actions out of the bottom action bar', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -599,13 +709,11 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const retryBtn = wrapper.find('[data-testid="shipping-order-extraction-primary-action"]');
|
||||
expect(retryBtn.text()).toContain('重试解析');
|
||||
await retryBtn.trigger('click');
|
||||
expect(wrapper.emitted('retry')?.length).toBe(1);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps view details as secondary text link only', () => {
|
||||
it('does not render the removed view details link', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -617,8 +725,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const details = wrapper.find('[data-testid="shipping-order-extraction-view-details"]');
|
||||
expect(details.exists()).toBe(true);
|
||||
expect(details.classes().join(' ')).toContain('underline-offset-2');
|
||||
expect(details.exists()).toBe(false);
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-primary-action"]').length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:聊天主区「订单识别任务」摘要卡——标题、文件数+状态、一行 handling 摘要、唯一主 CTA、查看详情。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、vue-router、vue-i18n。
|
||||
* 逻辑:对话区只做任务摘要;长进度/Gate/刷新取消由右侧栏承接;详情抽屉仅由次要「查看详情」打开。
|
||||
* 逻辑:对话区默认展示状态-EML 聚合;批次工作台打开后切换为紧凑摘要,长进度/Gate/刷新取消由工作台承接。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
@@ -38,12 +38,15 @@ const props = defineProps<{
|
||||
readonlyReason?: string | null;
|
||||
/** 可选统一投影;摘要卡不再渲染进度,仅保留 prop 兼容宿主。 */
|
||||
processingProjection?: ShippingProcessingProjection | null;
|
||||
/** 批次工作台打开时,左侧只保留摘要,避免与工作台重复展示文件明细。 */
|
||||
compactProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
refresh: [];
|
||||
cancel: [reason?: string];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -52,7 +55,14 @@ const router = useRouter();
|
||||
const shippingWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
|
||||
|
||||
type ConversationStatusGroups = NonNullable<import('../../types/shipping.api.types').ConversationProcessingProjection['status_groups']>;
|
||||
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => ((shippingWorkflow as { processing?: { value?: { status_groups?: ConversationStatusGroups | null } | null } } | null)?.processing?.value?.status_groups || null));
|
||||
type ConversationProcessing = import('../../types/shipping.api.types').ConversationProcessingProjection;
|
||||
const conversationProcessing = computed<ConversationProcessing | null>(() => (
|
||||
(shippingWorkflow as { processing?: { value?: ConversationProcessing | null } | null } | null)?.processing?.value || null
|
||||
));
|
||||
const conversationProjectionLoading = computed(() => Boolean(
|
||||
(shippingWorkflow as { initialLoading?: { value?: boolean } | null } | null)?.initialLoading?.value,
|
||||
));
|
||||
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => conversationProcessing.value?.status_groups || null);
|
||||
const hasConversationStatusGroups = computed(() => Boolean(conversationStatusGroups.value));
|
||||
const statusGroupDefs = [
|
||||
{ key: 'failed', label: 'chat.shippingProcessing.groupFailed' },
|
||||
@@ -83,6 +93,9 @@ function toggleEmlTask(taskNo: string) {
|
||||
}
|
||||
function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]; user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
|
||||
if (task.aggregateChildren?.length) return task.aggregateChildren;
|
||||
// [AUTHORITY] 新会话投影必须自带 EML 子文件;不能从 Run 快照或另一份 work_items 补齐,
|
||||
// 否则左右面板会出现不同文件数、不同状态的同一封邮件。
|
||||
if (hasConversationStatusGroups.value) return [];
|
||||
const projection = statusTaskProjection(task);
|
||||
if (!projection) return [];
|
||||
if (projection?.aggregateChildren?.length) return projection.aggregateChildren;
|
||||
@@ -147,36 +160,55 @@ function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]
|
||||
} as ShippingProcessingProjection));
|
||||
}
|
||||
function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[]; file_count?: number | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
|
||||
const children = taskChildren(task);
|
||||
// EML 是来源容器;统一只计其附件,避免聊天卡与批次中心相差一份 EML 本体。
|
||||
const children = taskChildren(task).filter((child) => !String(
|
||||
child.sourceSummary?.filename || '',
|
||||
).trim().toLowerCase().endsWith('.eml'));
|
||||
if (children.length) {
|
||||
const ids = new Set(children.map((child) => String(child.sourceSummary?.documentId || child.workItemNo || '').trim()).filter(Boolean));
|
||||
return ids.size || children.length;
|
||||
}
|
||||
if (hasConversationStatusGroups.value) return Math.max(0, Number(task.file_count || 0));
|
||||
const projection = statusTaskProjection(task);
|
||||
const sourceCount = Number(projection?.sourceSummary?.documentCount || 0);
|
||||
return sourceCount > 0 ? sourceCount : Math.max(0, Number(task.file_count || 0));
|
||||
}
|
||||
function childStatusLabel(child: ShippingProcessingProjection) {
|
||||
const status = String(child.userStatus || child.status || '').toLowerCase();
|
||||
const status = displayProjectionStatus(child);
|
||||
if (status === 'completed' && child.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
|
||||
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
|
||||
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
|
||||
}
|
||||
function userReasonLabel(code?: string | null) {
|
||||
const key = String(code || '').trim();
|
||||
const messages: Record<string, string> = {
|
||||
'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED': '识别结果需要人工确认,请进入订单处理继续。',
|
||||
'generic_extraction_disabled': '当前文件暂不支持自动解析,请人工处理或更换文件。',
|
||||
'SHIPPING_NOTICE.INTAKE_PARSE_FAILED': '邮件或附件解析失败,请检查文件后重试。',
|
||||
'upload_rpa_failed': '上传货代系统失败,请稍后重试。',
|
||||
};
|
||||
return messages[key] || (key ? '文件处理需要人工确认,请进入订单处理查看。' : '');
|
||||
function displayReason(
|
||||
reason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null,
|
||||
) {
|
||||
if (!reason) return '';
|
||||
const key = String(reason.i18nKey || '').trim();
|
||||
if (key && te(key)) return t(key);
|
||||
return String(reason.code || '').trim();
|
||||
}
|
||||
/** 新投影有 ui_state 时严格消费其状态;旧响应才回退 userStatus / status。 */
|
||||
function displayProjectionStatus(item: ShippingProcessingProjection): string {
|
||||
return String(item.uiState
|
||||
? item.uiState.status
|
||||
: (item.userStatus || item.status || '')).trim().toLowerCase();
|
||||
}
|
||||
function isFailedProjection(item: ShippingProcessingProjection): boolean {
|
||||
const status = displayProjectionStatus(item);
|
||||
return status === 'failed' || status === 'retryable';
|
||||
}
|
||||
function isWaitingProjection(item: ShippingProcessingProjection): boolean {
|
||||
return displayProjectionStatus(item) === 'waiting_human';
|
||||
}
|
||||
function isCompletedProjection(item: ShippingProcessingProjection): boolean {
|
||||
return displayProjectionStatus(item) === 'completed' && item.facts?.uploadState === 'succeeded';
|
||||
}
|
||||
function taskReason(task: { uiState?: { blocking_reason: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null }; blockingReason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null }) {
|
||||
return task.uiState ? task.uiState.blocking_reason : task.blockingReason;
|
||||
}
|
||||
function childStageLabel(child: ShippingProcessingProjection) {
|
||||
const stage = String(child.userStage || child.stage || '').trim();
|
||||
if (stage === 'review_required' || stage === 'waiting_review') return '等待人工复核';
|
||||
if (stage === 'failed' || stage === 'parse_failed') return '处理失败';
|
||||
const stage = String(child.uiState?.stage || child.userStage || child.stage || '').trim();
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
}
|
||||
@@ -229,16 +261,22 @@ const lastMatchedEmlAggregate = ref<ShippingProcessingProjection | null>(null);
|
||||
watch(matchedEmlAggregate, (item) => {
|
||||
if (item) lastMatchedEmlAggregate.value = item;
|
||||
}, { immediate: true });
|
||||
const emlAggregate = computed(() => matchedEmlAggregate.value || lastMatchedEmlAggregate.value);
|
||||
const emlAggregate = computed(() => (
|
||||
// [AUTHORITY] 切换会话时先等待该会话的统一投影,禁止旧聊天消息 Run 快照抢占首屏;
|
||||
// 请求完成后仍只消费后端 Projection,失败则保留既有兼容摘要。
|
||||
hasConversationStatusGroups.value || conversationProjectionLoading.value
|
||||
? null
|
||||
: (matchedEmlAggregate.value || lastMatchedEmlAggregate.value)
|
||||
));
|
||||
const emlAggregateChildren = computed(() => emlAggregate.value?.aggregateChildren || []);
|
||||
const emlAggregateExpanded = ref(false);
|
||||
function aggregateStageLabel(item: ShippingProcessingProjection): string {
|
||||
const stage = String(item.userStage || item.stage || '').trim();
|
||||
const stage = String(item.uiState ? item.uiState.stage : (item.userStage || item.stage || '')).trim();
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
}
|
||||
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
|
||||
const status = String(item.userStatus || item.status || '').trim().toLowerCase();
|
||||
const status = displayProjectionStatus(item);
|
||||
if (status === 'completed' && item.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
|
||||
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
|
||||
@@ -315,14 +353,30 @@ const failedRows = computed(() => fileRows.value.filter((row) => (
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const processedCount = computed(() => emlAggregate.value?.aggregateSummary?.completed
|
||||
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments));
|
||||
const processedCount = computed(() => {
|
||||
if (hasConversationStatusGroups.value) {
|
||||
const summary = conversationProcessing.value?.summary;
|
||||
return Math.max(0, Number(summary?.completed_files || 0))
|
||||
+ Math.max(0, Number(summary?.waiting_human_files || 0))
|
||||
+ Math.max(0, Number(summary?.failed_files || 0));
|
||||
}
|
||||
return emlAggregate.value?.aggregateSummary?.completed
|
||||
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments);
|
||||
});
|
||||
const progressPercent = computed(() => {
|
||||
const total = Math.max(0, props.state.summary.totalDocuments);
|
||||
const total = batchFileCount.value;
|
||||
return total > 0 ? Math.min(100, Math.round((processedCount.value / total) * 100)) : 0;
|
||||
});
|
||||
const completedExpanded = ref(false);
|
||||
|
||||
/** 新版会话批次的业务文件数由后端汇总;旧 Run 卡仍保留历史兼容计数。 */
|
||||
const batchFileCount = computed(() => {
|
||||
if (hasConversationStatusGroups.value) {
|
||||
return Math.max(0, Number(conversationProcessing.value?.summary.total_files || 0));
|
||||
}
|
||||
return Math.max(0, Number(emlAggregate.value?.sourceSummary.documentCount ?? props.state.summary.totalDocuments));
|
||||
});
|
||||
|
||||
/**
|
||||
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
|
||||
*/
|
||||
@@ -384,6 +438,13 @@ function handlingTitle(item: ShippingOrderExtractionHandlingItemState): string {
|
||||
* 状态短句:排队/处理中仅「系统处理中」;其余用过程通知,不含文件阶段耗时。
|
||||
*/
|
||||
const statusNotice = computed(() => {
|
||||
if (hasConversationStatusGroups.value) {
|
||||
const status = String(conversationProcessing.value?.ui_state?.status || '').trim().toLowerCase();
|
||||
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingSessionSummary.processNoticeFailed');
|
||||
if (status === 'waiting_human') return t('chat.shippingSessionSummary.processNoticeNeedsAction');
|
||||
return t('chat.shippingProcessing.systemProcessing');
|
||||
}
|
||||
if (emlAggregate.value) {
|
||||
const status = String(emlAggregate.value.userStatus || '').trim().toLowerCase();
|
||||
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
|
||||
@@ -612,19 +673,36 @@ async function onPrimaryChatAction() {
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="conversationProjectionLoading"
|
||||
class="mb-3 animate-pulse overflow-hidden rounded-xl border border-slate-200 bg-white/90 shadow-md dark:border-slate-700 dark:bg-slate-900/90"
|
||||
data-testid="shipping-order-extraction-projection-loading"
|
||||
>
|
||||
<!-- 读取权威 Projection 不是业务状态;只显示结构骨架,避免伪造“系统处理中”。 -->
|
||||
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
|
||||
<div class="h-6 w-36 rounded bg-slate-200 dark:bg-slate-700" />
|
||||
<div class="mt-3 h-4 w-2/3 rounded bg-slate-200 dark:bg-slate-700" />
|
||||
<div class="mt-5 h-2 w-full rounded bg-slate-200 dark:bg-slate-700" />
|
||||
</div>
|
||||
<div class="space-y-3 p-4">
|
||||
<div class="h-12 rounded-lg bg-slate-100 dark:bg-slate-800" />
|
||||
<div class="h-12 rounded-lg bg-slate-100 dark:bg-slate-800" />
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="mb-3 overflow-hidden rounded-xl border border-slate-200 bg-white/90 text-slate-900 shadow-md backdrop-blur-sm dark:border-slate-700 dark:bg-slate-900/90 dark:text-slate-100"
|
||||
data-testid="shipping-order-extraction-card"
|
||||
>
|
||||
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 text-lg font-semibold">
|
||||
<LoaderCircle v-if="emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
|
||||
<CheckCircle2 v-else-if="emlAggregate ? emlAggregate.userStatus === 'completed' && emlAggregate.facts?.uploadState === 'succeeded' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
|
||||
<LoaderCircle v-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'running' : emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
|
||||
<CheckCircle2 v-else-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'completed' : emlAggregate ? emlAggregate.userStatus === 'completed' && emlAggregate.facts?.uploadState === 'succeeded' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
|
||||
<TriangleAlert v-else class="h-5 w-5 text-amber-500" />
|
||||
<span>{{ t('chat.shippingProcessing.multiPdfTaskTitle') }}</span>
|
||||
</div>
|
||||
<span class="rounded-full bg-slate-200 px-3 py-1 text-xs font-medium text-slate-600 dark:bg-slate-700 dark:text-slate-200">
|
||||
{{ t('chat.shippingProcessing.batchFilesTotal', { count: emlAggregate?.sourceSummary.documentCount ?? state.summary.totalDocuments }) }}
|
||||
{{ t('chat.shippingProcessing.batchFilesTotal', { count: batchFileCount }) }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.batchStatusTitle') }} · {{ statusNotice }}</p>
|
||||
@@ -632,14 +710,14 @@ async function onPrimaryChatAction() {
|
||||
<div v-if="handlingSummaryLine" class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ handlingSummaryLine }}</div>
|
||||
<div class="mt-4 flex items-end justify-between">
|
||||
<span class="text-lg font-medium text-blue-600">{{ progressPercent }}% {{ t('chat.shippingProcessing.batchComplete') }}</span>
|
||||
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ emlAggregate?.sourceSummary.documentCount ?? state.summary.totalDocuments }} {{ t('chat.shippingProcessing.batchProcessed') }}</span>
|
||||
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ batchFileCount }} {{ t('chat.shippingProcessing.batchProcessed') }}</span>
|
||||
</div>
|
||||
<div class="mt-3 h-2 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700">
|
||||
<div class="h-full rounded-full bg-blue-600 transition-all" :style="{ width: `${progressPercent}%` }" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasConversationStatusGroups" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
|
||||
<div v-if="hasConversationStatusGroups && !compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
|
||||
<template v-for="group in statusGroupDefs" :key="group.key">
|
||||
<section v-if="statusGroupTasks(group.key).length" class="overflow-hidden rounded-lg border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
|
||||
<button type="button" class="flex w-full items-center justify-between px-3 py-3 text-left" @click="toggleStatusGroup(group.key)">
|
||||
@@ -652,19 +730,19 @@ async function onPrimaryChatAction() {
|
||||
<Mail class="mt-0.5 h-4 w-4 text-blue-600" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<button type="button" class="flex w-full items-center justify-between gap-2 text-left" @click="toggleEmlTask(task.user_task_no)">
|
||||
<span class="truncate text-sm font-medium">{{ statusTaskProjection(task)?.sourceSummary?.filename || task.title || task.user_task_no }}</span>
|
||||
<span class="truncate text-sm font-medium">{{ task.title || task.user_task_no }}</span>
|
||||
<ChevronDown class="h-4 w-4 shrink-0 transition-transform" :class="expandedEmlTasks.has(task.user_task_no) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div class="mt-1 text-xs text-slate-500">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
|
||||
<div v-if="task.blockingReason?.code" class="mt-1 text-xs text-rose-600">{{ userReasonLabel(task.blockingReason.code) }}</div>
|
||||
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
|
||||
<div v-if="expandedEmlTasks.has(task.user_task_no)" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
|
||||
<div v-for="child in taskChildren(task)" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
|
||||
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-medium">{{ child.sourceSummary.filename || child.workItemNo }}</div>
|
||||
<div class="text-[11px] text-slate-500">{{ childStageLabel(child) }}</div>
|
||||
<div v-if="child.blockingReason?.code || child.sourceSummary?.failureReasonCode" class="text-[11px] text-rose-600">{{ userReasonLabel(child.blockingReason?.code || child.sourceSummary?.failureReasonCode) }}</div>
|
||||
<div v-if="taskReason(child)" class="text-[11px] text-rose-600">{{ displayReason(taskReason(child)) }}</div>
|
||||
</div>
|
||||
<span class="shrink-0" :class="child.userStatus === 'failed' || child.userStatus === 'retryable' ? 'text-rose-600' : child.userStatus === 'waiting_human' ? 'text-amber-700' : child.userStatus === 'completed' && child.facts?.uploadState === 'succeeded' ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
|
||||
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -674,7 +752,7 @@ async function onPrimaryChatAction() {
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
<div v-else-if="emlAggregate" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
|
||||
<div v-else-if="!compactProgress && emlAggregate" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
|
||||
<article class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
|
||||
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
|
||||
@@ -686,7 +764,7 @@ async function onPrimaryChatAction() {
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ aggregateSummaryLabel(emlAggregate) }}</div>
|
||||
<div v-if="emlAggregate.blockingReason?.code" class="mt-1 text-xs text-rose-600">{{ userReasonLabel(emlAggregate.blockingReason.code) }}</div>
|
||||
<div v-if="taskReason(emlAggregate)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(emlAggregate)) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="flex w-full items-center justify-between px-3 py-2 text-left text-sm" @click="emlAggregateExpanded = !emlAggregateExpanded">
|
||||
@@ -696,12 +774,12 @@ async function onPrimaryChatAction() {
|
||||
<div v-if="emlAggregateExpanded" class="space-y-1 border-t border-slate-200 px-3 py-2 dark:border-slate-700">
|
||||
<div v-for="child in emlAggregateChildren" :key="child.workItemNo" class="flex items-center justify-between gap-3 py-1 text-sm">
|
||||
<span class="min-w-0 truncate">{{ child.sourceSummary.filename || child.workItemNo }}</span>
|
||||
<span class="shrink-0 text-xs" :class="child.userStatus === 'failed' || child.userStatus === 'retryable' ? 'text-rose-600' : child.userStatus === 'waiting_human' ? 'text-amber-700' : child.userStatus === 'completed' && child.facts?.uploadState === 'succeeded' ? 'text-emerald-600' : 'text-blue-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
|
||||
<span class="shrink-0 text-xs" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div v-else class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
|
||||
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
|
||||
<button type="button" class="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-3 text-left dark:border-slate-700 dark:bg-slate-900" @click="completedExpanded = !completedExpanded">
|
||||
<span class="flex items-center gap-3 text-base font-medium"><span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-100 text-blue-600"><CheckCircle2 class="h-4 w-4" /></span>{{ t('chat.shippingProcessing.candidateFiles', { count: candidateFileCount }) }}</span>
|
||||
<ChevronDown class="h-5 w-5 transition-transform" :class="completedExpanded ? 'rotate-180' : ''" />
|
||||
@@ -726,8 +804,16 @@ async function onPrimaryChatAction() {
|
||||
|
||||
<div class="flex justify-end border-t border-slate-200 bg-indigo-50/60 p-3 dark:border-slate-700 dark:bg-indigo-950/20">
|
||||
<div class="flex items-center gap-3">
|
||||
<button v-if="primaryChatAction" type="button" class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 disabled:opacity-50" data-testid="shipping-order-extraction-primary-action" :disabled="primaryChatAction.kind === 'retry' && retrying" @click="onPrimaryChatAction">{{ primaryChatAction.kind === 'retry' && retrying ? t('chat.shippingOrderExtractionRetrying') : primaryChatAction.label }}<ArrowRight class="h-4 w-4" /></button>
|
||||
<button v-if="String(props.runNo || '').trim()" type="button" class="text-sm font-medium text-blue-600 underline-offset-2 hover:underline" data-testid="shipping-order-extraction-view-details" @click="openDetailsDrawer">{{ t('chat.shippingProcessing.viewTaskDetails') }}</button>
|
||||
<button
|
||||
v-if="!compactProgress && (hasConversationStatusGroups || String(props.runNo || '').trim())"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700"
|
||||
data-testid="shipping-order-extraction-open-batch-workbench"
|
||||
@click="emit('open-batch-workbench')"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.openBatchWorkbench') }}
|
||||
<ArrowRight class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="false" class="flex items-start gap-3">
|
||||
|
||||
@@ -841,6 +841,63 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
});
|
||||
|
||||
it('renders localized four-stage labels without duplicating the header summary', async () => {
|
||||
const processing = processingFromDocuments([buildItem()], {
|
||||
status_groups: { failed: [], waiting_human: [], processing: [], completed: [] },
|
||||
four_stage_nodes: [
|
||||
{ code: 'intake_parse', status: 'passed' },
|
||||
{ code: 'order_review', status: 'running' },
|
||||
{ code: 'fulfillment_prep', status: 'pending' },
|
||||
{ code: 'upload_complete', status: 'pending' },
|
||||
],
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 断言:批次中心只在总览区呈现统计,标题栏不再重复任务/文件摘要。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-summary-totals"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-summary-detail"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="shipping-workflow-four-stage-progress"]').text()).toContain('接收解析');
|
||||
expect(wrapper.text()).not.toContain('chat.shippingNoticeUi.stage.intake_parse');
|
||||
});
|
||||
|
||||
it('opens review directly from a document leaf projection context', async () => {
|
||||
const processing = processingFromDocuments([buildItem()], {
|
||||
needs_action: [],
|
||||
processing: [],
|
||||
completed: [],
|
||||
});
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const card = wrapper.findComponent({ name: 'ShippingConversationProcessingCard' });
|
||||
await card.vm.$emit('projection-action', {
|
||||
projection: {
|
||||
workItemNo: 'DOCUMENT:191',
|
||||
rootOrderTaskNo: 'INTAKE:SNI-1',
|
||||
runNo: 'RUN-LEAF',
|
||||
caseNo: 'SNRC-LEAF',
|
||||
sourceSummary: { documentId: 191 },
|
||||
},
|
||||
item: { actionCode: 'open_order_review', intent: 'open_order_review' },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 断言:叶子不能按父任务号回查,必须直接使用后端下发的 Run/Case/文档上下文。
|
||||
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({
|
||||
query: expect.objectContaining({
|
||||
mode: 'order-review', run_no: 'RUN-LEAF', case_no: 'SNRC-LEAF', document_id: '191', focus_task_no: 'INTAKE:SNI-1',
|
||||
}),
|
||||
}));
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('expands all effective PDFs for one task even when they belong to different runs', async () => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
|
||||
* 用途:聊天页右侧「本次处理中」面板——OT 任务卡 + 按需展开的文件明细。
|
||||
* 用途:聊天页右侧「批次进度中心」——OT 任务卡 + 按需展开的文件明细。
|
||||
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
|
||||
* conversationProcessingProjection、DetailDrawer、ReasonDialog、ProcessGateRecoveryCard。
|
||||
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;面板摘要为双行「N 任务 · M 文件」+
|
||||
* 「待我处理 / 系统处理中」;截断时展示 has_more 提示;
|
||||
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
|
||||
* 文件总览和进度仅消费后端批次 summary;
|
||||
* mapUserTaskObjectsToFileRows 合成文件行;取消/重识别走 Run API;
|
||||
* 路由 focus_task_no / 服务端 focused_task_no 驱动本地选中卡;
|
||||
* 详情抽屉仅用列表投影,不再请求 WorkflowItem 详情 API。
|
||||
@@ -14,10 +14,12 @@ import { computed, inject, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ChevronDown, ChevronRight, Lock, RefreshCw } from 'lucide-vue-next';
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/chat/shipping/shippingDownload';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
|
||||
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
|
||||
import { useShippingProcessGateRecovery } from '@/features/shipping-process-gates/composables/useShippingProcessGateRecovery';
|
||||
import {
|
||||
cancelWorkspaceShippingOrderExtractionRun,
|
||||
reparseWorkspaceShippingOrderExtractionRun,
|
||||
@@ -54,6 +56,10 @@ const props = defineProps<{
|
||||
controller?: UseShippingNoticeWorkflowReturn | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const route = useRoute();
|
||||
@@ -64,6 +70,7 @@ const gateNavigationContext = computed(() => ({
|
||||
agentId: String(route.params.agentId || ''),
|
||||
conversationId: String(props.conversationId || route.query.conversation_id || ''),
|
||||
}));
|
||||
const { submitPrimaryAction: submitGatePrimaryAction } = useShippingProcessGateRecovery();
|
||||
|
||||
/**
|
||||
* Gate「确认客户」:打开对话叠层客户选择弹窗(非跳转复核)。
|
||||
@@ -115,14 +122,131 @@ const processingWorkItems = computed((): ShippingProcessingProjection[] => (
|
||||
? ctl.value.processingWorkItems.value
|
||||
: []
|
||||
));
|
||||
const batchArtifacts = computed(() => displayProcessing.value?.output_artifacts || []);
|
||||
const batchFourStageNodes = computed(() => displayProcessing.value?.four_stage_nodes || []);
|
||||
/** 四阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
|
||||
const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
|
||||
intake_parse: 'intakeParse',
|
||||
order_review: 'orderReview',
|
||||
fulfillment_prep: 'fulfillmentPrep',
|
||||
upload_complete: 'uploadComplete',
|
||||
};
|
||||
function batchFourStageLabelKey(code: string): string {
|
||||
return BATCH_FOUR_STAGE_I18N_KEYS[code] || code;
|
||||
}
|
||||
async function downloadBatchArtifact(taskNo: string) {
|
||||
if (!taskNo) return;
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(taskNo);
|
||||
} catch (err) {
|
||||
msg.error(err instanceof Error ? err.message : t('chat.shippingProcessing.batchWorkbench.artifacts.singleDownloadFailed'));
|
||||
}
|
||||
}
|
||||
/** 批量下载仅遍历后端标记为可下载的产物,单项失败不阻断其余产物。 */
|
||||
async function downloadAllBatchArtifacts() {
|
||||
const artifacts = batchArtifacts.value.filter((artifact) => artifact.action?.enabled);
|
||||
if (!artifacts.length) return;
|
||||
let failed = 0;
|
||||
for (const artifact of artifacts) {
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(artifact.order_task_no);
|
||||
} catch {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
if (failed) {
|
||||
msg.error(t('chat.shippingProcessing.batchWorkbench.artifacts.downloadFailed', { count: failed }));
|
||||
}
|
||||
}
|
||||
const processing = computed(() => ctl.value.processing?.value ?? null);
|
||||
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
|
||||
const displayProcessing = computed(() => processing.value);
|
||||
/**
|
||||
* 批次总览一律按文件计数。会话 summary 中 processing/needs_action 是任务数,
|
||||
* 不能直接填入原型的“处理中/需处理”文件统计卡。
|
||||
*/
|
||||
function taskFileKeys(task: ConversationProcessingUserTask): string[] {
|
||||
const keys = new Set<string>();
|
||||
const collect = (children: ShippingProcessingProjection[]) => {
|
||||
for (const child of children) {
|
||||
const nested = child.aggregateChildren || [];
|
||||
if (nested.length) collect(nested);
|
||||
const filename = String(child.sourceSummary?.filename || '').trim();
|
||||
// 聚合父项/邮件容器只提供来源信息,叶子附件才计入业务文件。
|
||||
if (nested.length || filename.toLowerCase().endsWith('.eml')) continue;
|
||||
const id = Number(child.sourceSummary?.documentId || 0);
|
||||
const key = id > 0 ? `document:${id}` : filename ? `filename:${filename}` : '';
|
||||
if (key) keys.add(key);
|
||||
}
|
||||
};
|
||||
const children = task.aggregateChildren || [];
|
||||
if (children.length) {
|
||||
collect(children);
|
||||
return [...keys];
|
||||
}
|
||||
for (const object of task.objects || []) {
|
||||
if (object.kind !== 'document') continue;
|
||||
const id = Number(object.document_id || 0);
|
||||
const filename = String(object.filename || object.label || '').trim();
|
||||
if (filename.toLowerCase().endsWith('.eml')) continue;
|
||||
const key = id > 0
|
||||
? `document:${id}`
|
||||
: String(object.filename || object.object_key || '').trim();
|
||||
if (key) keys.add(key);
|
||||
}
|
||||
if (keys.size) return [...keys];
|
||||
// 无 EML 子附件明细时,直接文件可按自身 file_count 回退;EML 不允许伪造附件数。
|
||||
const taskName = String(task.title || '').trim().toLowerCase();
|
||||
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
|
||||
const fallback = Math.max(0, Number(task.file_count || 0));
|
||||
return Array.from({ length: fallback }, (_, index) => `${task.user_task_no}:file:${index}`);
|
||||
}
|
||||
const batchOverview = computed(() => {
|
||||
const summary = displayProcessing.value?.summary;
|
||||
// [AUTHORITY] status_groups 表示新版批次投影。其 summary 是后端对完整批次
|
||||
// 一次裁决的文件事实,即使当前值为 0 也不得从局部展开行重算。
|
||||
if (displayProcessing.value?.status_groups && summary) {
|
||||
return {
|
||||
total: Number(summary.total_files || 0),
|
||||
processing: Number(summary.processing_files || 0),
|
||||
completed: Number(summary.completed_files || 0),
|
||||
needsAction: Number(summary.failed_files || 0) + Number(summary.waiting_human_files || 0),
|
||||
};
|
||||
}
|
||||
const groups = displayProcessing.value?.status_groups;
|
||||
const failed = groups?.failed || [];
|
||||
const waiting = groups?.waiting_human || [];
|
||||
const processingTasks = groups?.processing || displayProcessing.value?.processing || [];
|
||||
const completed = groups?.completed || displayProcessing.value?.completed || [];
|
||||
const seen = new Set<string>();
|
||||
const count = (tasks: ConversationProcessingUserTask[]) => tasks.reduce((total, task) => {
|
||||
let count = 0;
|
||||
for (const key of taskFileKeys(task)) {
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
count += 1;
|
||||
}
|
||||
return total + count;
|
||||
}, 0);
|
||||
const needsAction = count([...failed, ...waiting]);
|
||||
const processingCount = count(processingTasks);
|
||||
const completedCount = count(completed);
|
||||
const computedTotal = needsAction + processingCount + completedCount;
|
||||
const summaryTotal = Number(displayProcessing.value?.summary?.total_files || 0);
|
||||
return {
|
||||
// status_groups 的去重文件集合优先;旧 summary.total_files 只在没有可枚举文件时回退。
|
||||
total: computedTotal > 0 ? computedTotal : summaryTotal,
|
||||
processing: processingCount,
|
||||
completed: completedCount,
|
||||
needsAction,
|
||||
};
|
||||
});
|
||||
const loading = computed(() => ctl.value.loading.value);
|
||||
/** 初始加载:首次打开投影仍为空时显示摘要占位。 */
|
||||
const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
|
||||
/** 用户主动刷新(刷新按钮 / 重试 / 重解析等):驱动顶部刷新图标旋转。 */
|
||||
const manualRefreshing = computed(() => Boolean(ctl.value.manualRefreshing?.value));
|
||||
const isRefreshing = computed(() => Boolean(ctl.value.isRefreshing?.value));
|
||||
const error = computed(() => ctl.value.error.value);
|
||||
const routeFocusedTaskNo = computed(() => String(
|
||||
route.query.focus_task_no
|
||||
@@ -607,6 +731,22 @@ async function onTaskProjectionAction(payload: {
|
||||
if (task) void onProcessingTaskAction({ task, action: 'reparse' });
|
||||
return;
|
||||
}
|
||||
if (code === 'retry_inventory_preparation') {
|
||||
const gateSummary = projection.processGate;
|
||||
if (!gateSummary) {
|
||||
msg.warning(t('workspace.shippingNotice.processGate.noAction'));
|
||||
return;
|
||||
}
|
||||
// Gate 执行器统一处理 execution_no、乐观锁与幂等键;批次卡不自行组装写请求。
|
||||
const result = await submitGatePrimaryAction(gateSummary, {
|
||||
actionCode: code,
|
||||
navigationContext: gateNavigationContext.value,
|
||||
});
|
||||
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
|
||||
await ctl.value.refresh();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (code === 'retry_parse' || item.intent === 'retry') {
|
||||
void onProcessingIntakeAction({ item: projection, action: code || 'retry_parse' });
|
||||
return;
|
||||
@@ -615,7 +755,7 @@ async function onTaskProjectionAction(payload: {
|
||||
void onRefresh();
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_order_review') {
|
||||
if (item.intent === 'open_order_review' || code === 'open_order_review') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
@@ -623,7 +763,21 @@ async function onTaskProjectionAction(payload: {
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
void onProcessingTaskAction({ task, action: code || 'open_review' });
|
||||
return;
|
||||
}
|
||||
// 附件叶子的 workItemNo 为 DOCUMENT:<id>,不会等于 EML 父任务 INTAKE:<no>。
|
||||
// 此处直接消费叶子投影下发的 Run/Case/Document,禁止从父任务猜测复核上下文。
|
||||
const runNo = String(projection.runNo || '').trim();
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingOrderReview.caseRequired'));
|
||||
return;
|
||||
}
|
||||
await pushOrderReviewQuery({
|
||||
runNo,
|
||||
documentId: projection.sourceSummary?.documentId,
|
||||
caseNo: projection.caseNo,
|
||||
taskNo: projection.rootOrderTaskNo || taskNo,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'view_result' || code === 'focus_task') {
|
||||
@@ -696,11 +850,20 @@ watch(
|
||||
|
||||
<template>
|
||||
<aside
|
||||
class="flex w-full shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)] transition-[width] duration-200 md:w-[clamp(20rem,28vw,30rem)]"
|
||||
class="flex min-w-0 flex-1 shrink-0 flex-col border-l border-default bg-surface shadow-[-16px_0_40px_rgba(15,23,42,0.10)] transition-[width] duration-200"
|
||||
:class="collapsed ? '!w-14' : ''"
|
||||
data-testid="shipping-workflow-timeline"
|
||||
>
|
||||
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary"
|
||||
data-testid="shipping-workflow-close"
|
||||
:title="t('chat.shippingProcessing.closeWorkbench')"
|
||||
@click="emit('close')"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<component
|
||||
:is="hasPinnedProcessingTasks ? 'div' : 'button'"
|
||||
:type="hasPinnedProcessingTasks ? undefined : 'button'"
|
||||
@@ -733,18 +896,6 @@ watch(
|
||||
{{ t('chat.shippingProcessing.loading') }}
|
||||
</template>
|
||||
<template v-else-if="displayProcessing">
|
||||
<div data-testid="shipping-processing-summary-totals">
|
||||
{{ t('chat.shippingProcessing.summaryTasksAndFiles', {
|
||||
tasks: Number(displayProcessing.summary.total_tasks || 0),
|
||||
files: Number(displayProcessing.summary.total_files || 0),
|
||||
}) }}
|
||||
</div>
|
||||
<div data-testid="shipping-processing-summary-detail">
|
||||
{{ t('chat.shippingProcessing.summaryLineDetail', {
|
||||
needsAction: Number(displayProcessing.summary.needs_action || 0),
|
||||
processing: Number(displayProcessing.summary.processing || 0),
|
||||
}) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="displayProcessing.summary.has_more_active || displayProcessing.summary.has_more_history"
|
||||
class="text-[11px] text-muted"
|
||||
@@ -777,12 +928,84 @@ watch(
|
||||
>
|
||||
<RefreshCw
|
||||
class="h-3.5 w-3.5"
|
||||
:class="{ 'animate-spin': initialLoading || manualRefreshing }"
|
||||
:class="{ 'animate-spin': isRefreshing }"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="!collapsed" class="shrink-0 p-3 pb-0">
|
||||
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-y-auto p-5">
|
||||
<div
|
||||
v-if="displayProcessing"
|
||||
class="mb-4 grid grid-cols-2 gap-3 xl:grid-cols-4"
|
||||
data-testid="shipping-workflow-overview"
|
||||
>
|
||||
<div class="rounded-xl border border-default bg-surface p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.totalFiles') }}</div><div class="mt-1 text-2xl font-semibold text-primary">{{ batchOverview.total }}</div></div>
|
||||
<div class="rounded-xl border border-brand-200 bg-brand-50/60 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.processing') }}</div><div class="mt-1 text-2xl font-semibold text-brand-700">{{ batchOverview.processing }}</div></div>
|
||||
<div class="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.completed') }}</div><div class="mt-1 text-2xl font-semibold text-emerald-700">{{ batchOverview.completed }}</div></div>
|
||||
<div class="rounded-xl border border-rose-200 bg-rose-50/70 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.needsAction') }}</div><div class="mt-1 text-2xl font-semibold text-rose-700">{{ batchOverview.needsAction }}</div></div>
|
||||
</div>
|
||||
<div
|
||||
v-if="displayProcessing"
|
||||
class="mb-4 rounded-xl border border-default bg-surface-muted/60 p-3"
|
||||
data-testid="shipping-workflow-overview-progress"
|
||||
>
|
||||
<div class="mb-2 flex items-center justify-between text-xs font-medium text-secondary">
|
||||
<span>{{ t('chat.shippingProcessing.batchWorkbench.overview.completion', { percent: Math.min(100, Math.round((batchOverview.completed / Math.max(1, batchOverview.total)) * 100)) }) }}</span>
|
||||
<span>{{ t('chat.shippingProcessing.batchWorkbench.overview.processedOfTotal', { completed: batchOverview.completed, total: batchOverview.total }) }}</span>
|
||||
</div>
|
||||
<div class="h-3 overflow-hidden rounded-full bg-surface">
|
||||
<div
|
||||
class="h-full rounded-full bg-brand-600 shadow-[0_1px_2px_rgb(37_99_235_/_0.35)] transition-[width]"
|
||||
:style="{ width: `${Math.min(100, Math.round((batchOverview.completed / Math.max(1, batchOverview.total)) * 100))}%` }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<section v-if="batchFourStageNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-four-stage-progress">
|
||||
<div class="grid grid-cols-4 gap-2">
|
||||
<div v-for="node in batchFourStageNodes" :key="node.code" class="rounded-lg border px-2 py-2 text-center text-xs" :class="node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary'">
|
||||
{{ t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(node.code)}`) }}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
class="mb-4 rounded-xl border border-default bg-surface p-4"
|
||||
data-testid="shipping-workflow-batch-artifacts"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold text-primary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.title') }}</h3>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!batchArtifacts.some((artifact) => artifact.action.enabled)"
|
||||
data-testid="shipping-workflow-batch-artifact-download"
|
||||
@click="downloadAllBatchArtifacts"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadAll') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="batchArtifacts.length" class="mt-3 divide-y divide-default">
|
||||
<div v-for="artifact in batchArtifacts" :key="artifact.order_task_no" class="flex items-center justify-between gap-3 py-2 text-xs">
|
||||
<span class="truncate text-primary">{{ artifact.filename }}</span>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<span class="text-emerald-700">{{ artifact.status }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-2 py-1 font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50"
|
||||
:disabled="!artifact.action.enabled"
|
||||
:data-testid="`shipping-workflow-batch-artifact-download-${artifact.order_task_no}`"
|
||||
@click="downloadBatchArtifact(artifact.order_task_no)"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="mt-3 text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.empty') }}</p>
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="focusTaskBanner"
|
||||
class="mb-3 rounded-md border border-brand-200 bg-brand-50 px-2.5 py-2 text-[11px] text-brand-900 dark:border-brand-800 dark:bg-brand-950/40 dark:text-brand-100"
|
||||
@@ -796,6 +1019,7 @@ watch(
|
||||
:projection="displayProcessing"
|
||||
:work-items="processingWorkItems"
|
||||
:conversation-id="conversationId"
|
||||
:workbench-mode="true"
|
||||
:has-more-history="Boolean(displayProcessing?.summary?.has_more_history)"
|
||||
@expand-files="onExpandTaskFiles"
|
||||
@collapse-files="onCollapseTaskFiles"
|
||||
@@ -805,7 +1029,7 @@ watch(
|
||||
/>
|
||||
|
||||
<section
|
||||
v-if="showStandaloneCurrentStage"
|
||||
v-if="!displayProcessing && showStandaloneCurrentStage"
|
||||
class="mb-3 rounded-xl border border-brand-200 bg-brand-50/60 p-3 dark:border-brand-900/60 dark:bg-brand-950/20"
|
||||
data-testid="shipping-workflow-current-stage"
|
||||
>
|
||||
@@ -835,6 +1059,7 @@ watch(
|
||||
|
||||
<!-- 侧栏内直接展示阻断 Gate 与文件明细,避免重复弹层。 -->
|
||||
<div
|
||||
v-if="!displayProcessing"
|
||||
class="space-y-2"
|
||||
data-testid="shipping-workflow-compact-gates"
|
||||
>
|
||||
@@ -852,7 +1077,7 @@ watch(
|
||||
|
||||
<!-- 聚焦任务下的文件行列表:供跨 Run 合并与文件筛选断言。 -->
|
||||
<ul
|
||||
v-if="expandedTask && items.length"
|
||||
v-if="!displayProcessing && expandedTask && items.length"
|
||||
class="my-3 space-y-1.5"
|
||||
>
|
||||
<li
|
||||
|
||||
@@ -53,7 +53,7 @@ const buildBatchUiStateEvent = (
|
||||
task_no: taskNo,
|
||||
batch_no: batchNo,
|
||||
checkpoint,
|
||||
process_status: 'matched',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
pending_human_reason: null,
|
||||
match_status: 'fulfillable',
|
||||
@@ -92,7 +92,7 @@ describe('useChat shipping_ui_state SSE', () => {
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-UNIT-001');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toEqual([]);
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toBeUndefined();
|
||||
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
|
||||
});
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
|
||||
msg.shipping_ui_state = uiState;
|
||||
msg.shipping_actions = undefined;
|
||||
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object') {
|
||||
(msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons = [];
|
||||
delete (msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons;
|
||||
}
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* features/chat/composables/useChatRouteSync.spec.ts
|
||||
* 用途:验证聊天路由初始化的关键首屏请求调度。
|
||||
* 依赖:vitest、useChatRouteSync。
|
||||
* 逻辑:历史会话列表属于后台辅助数据,不能阻塞指定 conversation 的消息与进度加载。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('vue', () => ({
|
||||
onBeforeUnmount: vi.fn(),
|
||||
onMounted: vi.fn(),
|
||||
watch: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useChatRouteSync } from './useChatRouteSync';
|
||||
|
||||
describe('useChatRouteSync', () => {
|
||||
it('starts the requested conversation before the history list resolves', async () => {
|
||||
let resolveHistory!: () => void;
|
||||
const loadHistory = vi.fn(() => new Promise<void>((resolve) => {
|
||||
resolveHistory = resolve;
|
||||
}));
|
||||
const loadConversation = vi.fn(async () => undefined);
|
||||
const routeSync = useChatRouteSync({
|
||||
deps: {
|
||||
route: {
|
||||
params: { agentId: '24' },
|
||||
query: { conversation_id: 'conversation-b' },
|
||||
},
|
||||
router: { push: vi.fn() },
|
||||
} as never,
|
||||
currentAgentId: { value: 24 } as never,
|
||||
presetQuestion: { value: '' } as never,
|
||||
shippingTaskIdFromQuery: { value: null } as never,
|
||||
isShippingNoticeAgent: { value: true } as never,
|
||||
resetChatStateForAgentChange: vi.fn(),
|
||||
cancelVoiceInput: vi.fn(),
|
||||
syncCurrentUserProfile: vi.fn(async () => undefined),
|
||||
loadAgent: vi.fn(async () => undefined),
|
||||
loadUserAgents: vi.fn(async () => undefined),
|
||||
loadHistory,
|
||||
loadConversation,
|
||||
resumeShippingTaskFromQuery: vi.fn(async () => undefined),
|
||||
handleSend: vi.fn(async () => undefined),
|
||||
createNewChatView: vi.fn(),
|
||||
onAuthLogout: vi.fn(),
|
||||
onViewportResize: vi.fn(),
|
||||
disposePeripherals: vi.fn(),
|
||||
scheduleScrollToBottom: vi.fn(),
|
||||
input: { value: '' } as never,
|
||||
});
|
||||
|
||||
const pending = routeSync.syncChatStateForRoute();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(loadHistory).toHaveBeenCalledTimes(1);
|
||||
expect(loadConversation).toHaveBeenCalledWith('conversation-b', { force: true });
|
||||
});
|
||||
|
||||
resolveHistory();
|
||||
await pending;
|
||||
});
|
||||
});
|
||||
@@ -94,16 +94,23 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
await loadUserAgents();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
await loadHistory();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
const convId = route.query.conversation_id as string;
|
||||
// 历史列表是辅助内容;直达会话时不能阻塞消息/货代 Projection 的首屏读取。
|
||||
const historyPromise = loadHistory();
|
||||
if (convId) {
|
||||
await loadConversation(convId, { force: true });
|
||||
await Promise.all([
|
||||
historyPromise,
|
||||
loadConversation(convId, { force: true }),
|
||||
]);
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
} else if (shippingTaskIdFromQuery.value || shippingBatchNoFromQuery?.value) {
|
||||
await historyPromise;
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
await resumeShippingTaskFromQuery();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
} else {
|
||||
await historyPromise;
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
}
|
||||
|
||||
if (presetQuestion.value) {
|
||||
|
||||
@@ -103,7 +103,7 @@ describe('useChatShipping persisted batch snapshot', () => {
|
||||
shipping_batch_ui_state: {
|
||||
batch_no: 'SB-EXISTING',
|
||||
current_focus_task_no: 'SN-EXISTING',
|
||||
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', process_status: 'pending_review' }],
|
||||
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', review_status: 'parse_review' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -133,7 +133,7 @@ describe('useChatShipping message recovery payload', () => {
|
||||
shipping_ui_state: {
|
||||
task_no: 'SN-OPEN-EXISTING',
|
||||
batch_no: 'SB-OPEN-EXISTING',
|
||||
process_status: 'waiting_inventory',
|
||||
inventory_lines_json: [{ reservation_id: 'R-1' }],
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
|
||||
@@ -554,7 +554,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|
||||
const hasRunningShippingBatchTasks = () =>
|
||||
shippingBatchTasks.value.some(
|
||||
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
|
||||
(task) => String(task.ui_state?.stage?.code || '').trim() !== 'upload_complete',
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -591,10 +591,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isShippingActionBusy.value) return;
|
||||
const detail = activeShippingTaskDetail.value;
|
||||
// 任务详情接口当前不返回顶层 checkpoint,parse_review 需从详情状态字段回推。
|
||||
// 复核同步只消费后端统一 ui_state.checkpoint,不读取 review_status 等领域事实推导。
|
||||
const checkpoint = String(
|
||||
(detail?.step_payload as Record<string, unknown> | undefined)?.checkpoint
|
||||
|| detail?.review_status
|
||||
detail?.ui_state?.checkpoint?.code
|
||||
|| detail?.ui_state?.checkpoint_code
|
||||
|| '',
|
||||
).trim();
|
||||
if (checkpoint !== 'parse_review') return;
|
||||
|
||||
@@ -24,7 +24,7 @@ vi.mock('../api/chat.api', () => ({
|
||||
|
||||
const createConversationContext = () => {
|
||||
const conversationId = ref<string | null>('conv-a');
|
||||
const messages = ref([]);
|
||||
const messages = ref<any[]>([{ role: 'assistant', content: 'old-a' }]);
|
||||
const createNewChatView = vi.fn(() => {
|
||||
conversationId.value = null;
|
||||
messages.value = [];
|
||||
@@ -44,7 +44,10 @@ const createConversationContext = () => {
|
||||
activeRunId: ref(null),
|
||||
messages,
|
||||
isThinking: ref(false),
|
||||
loadConversationState: vi.fn(),
|
||||
loadConversationState: (id, loaded) => {
|
||||
conversationId.value = id;
|
||||
messages.value = loaded;
|
||||
},
|
||||
createNewChatView,
|
||||
clearPendingNoticeBatchRetry,
|
||||
onConversationIdChanging: vi.fn(),
|
||||
@@ -152,4 +155,62 @@ describe('useChatPageConversation', () => {
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('clears the previous conversation messages before an uncached history request resolves', async () => {
|
||||
let resolveMessages!: (value: any[]) => void;
|
||||
listChatMessages.mockImplementation(() => new Promise((resolve) => { resolveMessages = resolve; }));
|
||||
const { api, messages, conversationId } = createConversationContext();
|
||||
|
||||
const pending = api.loadConversation('conv-b', { force: true });
|
||||
|
||||
// 会话已切换但 B 尚无本地快照时,绝不能继续显示 A 的消息/订单卡。
|
||||
expect(conversationId.value).toBe('conv-b');
|
||||
expect(messages.value).toEqual([]);
|
||||
|
||||
resolveMessages([{ role: 'assistant', content: 'loaded-b' }]);
|
||||
await pending;
|
||||
expect(messages.value[0]?.content).toBe('loaded-b');
|
||||
});
|
||||
|
||||
it('restores cached messages immediately and discards a late response from an older selection', async () => {
|
||||
const pending = new Map<string, { resolve: (value: any[]) => void }>();
|
||||
listChatMessages.mockImplementation((id: string) => new Promise((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
}));
|
||||
const { api, messages, conversationId } = createConversationContext();
|
||||
|
||||
const firstB = api.loadConversation('conv-b', { force: true });
|
||||
pending.get('conv-b')!.resolve([{ role: 'assistant', content: 'cached-b' }]);
|
||||
await firstB;
|
||||
|
||||
const selectA = api.loadConversation('conv-a', { force: true });
|
||||
const returnB = api.loadConversation('conv-b', { force: true });
|
||||
expect(messages.value[0]?.content).toBe('cached-b');
|
||||
|
||||
pending.get('conv-a')!.resolve([{ role: 'assistant', content: 'late-a' }]);
|
||||
pending.get('conv-b')!.resolve([{ role: 'assistant', content: 'cached-b' }]);
|
||||
await Promise.all([selectA, returnB]);
|
||||
|
||||
expect(conversationId.value).toBe('conv-b');
|
||||
expect(messages.value[0]?.content).toBe('cached-b');
|
||||
});
|
||||
|
||||
it('keeps the rendered cached message array when revalidation is semantically unchanged', async () => {
|
||||
const pending = new Map<string, { resolve: (value: any[]) => void }>();
|
||||
listChatMessages.mockImplementation((id: string) => new Promise((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
}));
|
||||
const { api, messages } = createConversationContext();
|
||||
|
||||
const initial = api.loadConversation('conv-b', { force: true });
|
||||
pending.get('conv-b')!.resolve([{ chat_log_id: 91, role: 'assistant', content: 'stable-b' }]);
|
||||
await initial;
|
||||
|
||||
const revalidate = api.loadConversation('conv-b', { force: true });
|
||||
const renderedCache = messages.value;
|
||||
pending.get('conv-b')!.resolve([{ chat_log_id: 91, role: 'assistant', content: 'stable-b' }]);
|
||||
await revalidate;
|
||||
|
||||
expect(messages.value).toBe(renderedCache);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,30 @@ export interface ChatPageConversationContext {
|
||||
}
|
||||
|
||||
export function createChatPageConversationApi(ctx: ChatPageConversationContext) {
|
||||
// 会话消息与发货 Projection 使用相同的 SWR 原则:仅在内存保留最近成功快照;
|
||||
// 路由切换先原子显示目标会话快照(或空白),再后台读取,不能让旧会话占据新会话首帧。
|
||||
const messageSnapshots = new Map<string, ChatMessage[]>();
|
||||
let messageRequestGeneration = 0;
|
||||
|
||||
const touchMessageSnapshot = (id: string, messages: ChatMessage[]) => {
|
||||
messageSnapshots.delete(id);
|
||||
messageSnapshots.set(id, messages);
|
||||
while (messageSnapshots.size > 20) {
|
||||
const oldestId = messageSnapshots.keys().next().value as string | undefined;
|
||||
if (!oldestId) break;
|
||||
messageSnapshots.delete(oldestId);
|
||||
}
|
||||
};
|
||||
|
||||
const messageSemanticKey = (items: ChatMessage[]) => JSON.stringify(items.map((item) => ({
|
||||
id: item.chat_log_id ?? item.local_id ?? null,
|
||||
role: item.role,
|
||||
type: item.type,
|
||||
content: item.content,
|
||||
payload: item.payload ?? null,
|
||||
attachments: item.attachments ?? [],
|
||||
})));
|
||||
|
||||
const loadConversation = async (id: string, options?: { force?: boolean }) => {
|
||||
const force = options?.force ?? false;
|
||||
if (!force && ctx.conversationId.value === id && !ctx.activeRunId.value && ctx.messages.value.length > 0) {
|
||||
@@ -44,6 +68,8 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
}
|
||||
|
||||
const prevConversationId = ctx.conversationId.value;
|
||||
const generation = ++messageRequestGeneration;
|
||||
const cachedMessages = messageSnapshots.get(id);
|
||||
try {
|
||||
/**
|
||||
* 切换会话前先清空输入框草稿,避免 textarea DOM 里残留上一会话的可见文本,
|
||||
@@ -51,9 +77,19 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
*/
|
||||
ctx.input.value = '';
|
||||
ctx.onConversationIdChanging(id, prevConversationId);
|
||||
// [STEP 1] 先切换消息容器:未访问会话渲染空白而非上一会话;
|
||||
// 已访问会话复用自身快照,避免“缓存卡先出现后整页闪一下”。
|
||||
ctx.loadConversationState(id, cachedMessages ? [...cachedMessages] : []);
|
||||
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
|
||||
ctx.loadConversationState(id, Array.isArray(loaded) ? loaded : []);
|
||||
if (!loaded?.length) {
|
||||
if (generation !== messageRequestGeneration || ctx.conversationId.value !== id) return;
|
||||
const nextMessages = Array.isArray(loaded) ? loaded : [];
|
||||
const currentMessages = ctx.messages.value;
|
||||
touchMessageSnapshot(id, nextMessages);
|
||||
// 同一会话后台重验没有业务变化时,保留消息数组和子卡实例,避免缓存首帧后闪一下。
|
||||
if (messageSemanticKey(currentMessages) !== messageSemanticKey(nextMessages)) {
|
||||
ctx.loadConversationState(id, nextMessages);
|
||||
}
|
||||
if (!nextMessages.length) {
|
||||
await ctx.onConversationLoadedEmpty();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
getWorkspaceShippingOrderReviewCase,
|
||||
getWorkspaceShippingOrderReviewEvidence,
|
||||
getWorkspaceShippingOrderReviewPreview,
|
||||
getWorkspaceShippingOrderReviewEmailEvidencePreview,
|
||||
getShippingNoticeIntake,
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
@@ -386,6 +387,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const previewCaseNo = ref<string | null>(null);
|
||||
const previewLoading = ref(false);
|
||||
const previewLoadFailed = ref(false);
|
||||
const emailPreview = ref<{ document_id: number; document_type: 'email_body'; filename: string; text: string } | null>(null);
|
||||
let previewInflight: Promise<boolean> | null = null;
|
||||
/** Case 切换请求代次:快速切换时丢弃过期响应,禁止旧 Case 覆盖新 Case。 */
|
||||
let caseLoadGeneration = 0;
|
||||
@@ -862,6 +864,17 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
return previewInflight;
|
||||
};
|
||||
|
||||
/** 按当前证据 Document 读取邮件正文;PDF 证据仍使用受控 PDF Blob。 */
|
||||
const ensureEmailEvidenceLoaded = async (caseNo: string, documentId: number): Promise<boolean> => {
|
||||
try {
|
||||
emailPreview.value = await getWorkspaceShippingOrderReviewEmailEvidencePreview(caseNo, documentId);
|
||||
return true;
|
||||
} catch {
|
||||
emailPreview.value = null;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** ?? Run ??????? URL ?? Case??????? PDF? */
|
||||
const load = async (
|
||||
runNo: string,
|
||||
@@ -1580,6 +1593,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
previewLoading,
|
||||
previewLoadFailed,
|
||||
ensurePreviewLoaded,
|
||||
ensureEmailEvidenceLoaded,
|
||||
emailPreview,
|
||||
clearPreview,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
buildTaskSemanticKey,
|
||||
buildProcessingSemanticKey,
|
||||
stabilizeTaskObjects,
|
||||
flattenBusinessFileProjections,
|
||||
businessFileKeys,
|
||||
} from './conversationProcessingProjection';
|
||||
import type {
|
||||
ConversationProcessingProjection,
|
||||
@@ -29,6 +31,28 @@ import type {
|
||||
ShippingWorkflowItem,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
describe('EML business-file projection', () => {
|
||||
it('excludes the EML container and keeps its PDF/XLSX leaf attachments', () => {
|
||||
const eml = {
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml',
|
||||
sourceSummary: { filename: 'mail.eml', documentCount: 2 },
|
||||
aggregateChildren: [
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', sourceSummary: { filename: 'notice-a.pdf', documentId: 101, documentCount: 1 } },
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', sourceSummary: { filename: 'items.xlsx', documentId: 102, documentCount: 1 } },
|
||||
],
|
||||
} as ShippingProcessingProjection;
|
||||
const directPdf = {
|
||||
workItemType: 'order_task', workItemNo: 'OT-3', sourceType: 'direct_pdf',
|
||||
sourceSummary: { filename: 'direct.pdf', documentId: 103, documentCount: 1 },
|
||||
} as ShippingProcessingProjection;
|
||||
|
||||
// EML 仅为来源分组,3 个业务附件才是唯一文件集合。
|
||||
expect(flattenBusinessFileProjections([eml, directPdf]).map((row) => row.sourceSummary.filename))
|
||||
.toEqual(['notice-a.pdf', 'items.xlsx', 'direct.pdf']);
|
||||
expect(businessFileKeys([eml, directPdf])).toEqual(['document:101', 'document:102', 'document:103']);
|
||||
});
|
||||
});
|
||||
|
||||
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
|
||||
return {
|
||||
item_no: 'WI-1',
|
||||
@@ -891,6 +915,43 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
expect(t2.available_actions).toEqual(['open_order_review', 'view_details']);
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: ui_state 动作变化必须改变签名', () => {
|
||||
const shared = {
|
||||
user_task_no: 'INTAKE:SNI-UI', group: 'needs_action' as const,
|
||||
status_label: 'waiting_human', file_count: 1, can_append: false,
|
||||
available_actions: ['retry_parse'],
|
||||
};
|
||||
const before = {
|
||||
...shared,
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'order_review', blocking_reason: null,
|
||||
primary_action: { code: 'open_order_review', i18nKey: 'action.open_order_review', parameters: {} },
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
const after = {
|
||||
...before,
|
||||
uiState: {
|
||||
...before.uiState,
|
||||
primary_action: { code: 'retry_parse', i18nKey: 'action.retry_parse', parameters: {} },
|
||||
},
|
||||
};
|
||||
expect(buildTaskSemanticKey(before)).not.toBe(buildTaskSemanticKey(after));
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: authoritative ui_state without a primary action ignores stale legacy action', () => {
|
||||
const shared = {
|
||||
user_task_no: 'INTAKE:SNI-NO-ACTION', group: 'processing' as const,
|
||||
status_label: 'processing', file_count: 1, can_append: false,
|
||||
primary_action: 'retry_parse', available_actions: ['retry_parse'],
|
||||
uiState: { status: 'processing', stage: 'document_parsing', blocking_reason: null, primary_action: null, secondary_actions: [] },
|
||||
};
|
||||
const withoutLegacy = { ...shared, primary_action: null, available_actions: [] };
|
||||
|
||||
// 后端 ui_state 已明确“无动作”时,旧字段变动不能让状态卡语义闪烁或伪造 CTA。
|
||||
expect(buildTaskSemanticKey(shared)).toBe(buildTaskSemanticKey(withoutLegacy));
|
||||
});
|
||||
|
||||
it('stabilizeTaskObjects: 同一 user_task_no 且语义相同,优先复用旧对象引用(避免 DOM 重建)', () => {
|
||||
const baseTask = (no: string, updatedAt: string) => ({
|
||||
user_task_no: no,
|
||||
@@ -1063,6 +1124,55 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
expect(normalized.processing.length).toBe(0);
|
||||
});
|
||||
|
||||
it('normalizes backend status-group task UI state and EML children without recalculating batch facts', () => {
|
||||
const backendProjection = {
|
||||
// 统计是后端按完整批次裁决的事实,不能由当前返回的局部 EML/附件数组替代。
|
||||
summary: { total_tasks: 1, total_files: 7, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
focused_task_no: 'INTAKE:SNI-API',
|
||||
recent_task_no: 'INTAKE:SNI-API',
|
||||
needs_action: [], processing: [], completed: [], history: [],
|
||||
status_groups: {
|
||||
failed: [{
|
||||
user_task_no: 'INTAKE:SNI-API', title: 'source.eml', display_kind: 'multi_document_task',
|
||||
document_names: ['a.pdf', 'b.pdf'], group: 'needs_action', status_label: 'failed', file_count: 2,
|
||||
can_append: false, available_actions: [], primary_action: null,
|
||||
ui_state: {
|
||||
status: 'failed', stage: 'document_parsing',
|
||||
blocking_reason: { code: 'PARSE_FAILED', i18n_key: 'shipping.parse_failed', details: {} },
|
||||
primary_action: { code: 'retry', i18n_key: 'shipping.retry', parameters: {} }, secondary_actions: [],
|
||||
},
|
||||
aggregate_children: [{
|
||||
work_item_type: 'order_task', work_item_no: 'OT-API-1', source_type: 'direct_pdf',
|
||||
root_order_task_no: 'OT-API-1', shipping_notice_no: null, conversation_id: 'conv-api',
|
||||
submission_no: 'SUB-1', intake_no: 'SNI-API', status: 'failed', stage: 'document_parsing',
|
||||
progress_version: 1, last_activity_at: '2026-08-14T00:00:00Z', current_gate: null, available_actions: [],
|
||||
source_summary: { email_subject: 'Subject', filename: 'a.pdf', document_count: 1, parsed_document_count: 0, candidate_count: 0 },
|
||||
child_order_tasks: [], ui_state: {
|
||||
status: 'failed', stage: 'document_parsing', blocking_reason: { code: 'PARSE_FAILED', details: {} },
|
||||
primary_action: { code: 'retry', parameters: {} }, secondary_actions: [],
|
||||
},
|
||||
}],
|
||||
}],
|
||||
waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
four_stage_nodes: [{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }],
|
||||
output_artifacts: [{ order_task_no: 'OT-API-1', filename: 'shipping.xlsx', type: 'excel', status: 'ready', action: { code: 'download_excel', enabled: true } }],
|
||||
} as unknown as ConversationProcessingProjection;
|
||||
|
||||
const normalized = normalizeConversationProcessingProjection(backendProjection);
|
||||
const eml = normalized.status_groups!.failed[0]!;
|
||||
|
||||
// 后端裁决的状态/按钮必须在 EML 与附件层均可直接消费,前端不重新推导。
|
||||
expect(eml.uiState?.primary_action?.code).toBe('retry');
|
||||
expect(eml.uiState?.primary_action?.i18nKey).toBe('shipping.retry');
|
||||
expect(eml.aggregateChildren?.[0]?.uiState?.primary_action?.code).toBe('retry');
|
||||
expect(eml.aggregateChildren?.[0]?.sourceSummary.filename).toBe('a.pdf');
|
||||
// 批次统计、四阶段与产物均是后端事实,适配时不得从附件重算或丢失。
|
||||
expect(normalized.summary.total_files).toBe(7);
|
||||
expect(normalized.four_stage_nodes).toEqual([{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }]);
|
||||
expect(normalized.output_artifacts?.[0]?.action.enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified: work_items 为空时,embedded waiting_human 任务迁入 needs_action 且统一文案', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
|
||||
@@ -22,6 +22,46 @@ import type {
|
||||
ShippingWorkflowItem,
|
||||
WorkflowNodeStatus,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
|
||||
|
||||
/**
|
||||
* 展开工作项中的业务文件叶子。
|
||||
* EML 只是来源容器,不是可处理业务文件;只有其下真实附件(PDF/XLSX 等)
|
||||
* 以及 direct_pdf 自身进入文件计数和文件名列表。该函数不修改后端投影。
|
||||
*/
|
||||
export function flattenBusinessFileProjections(
|
||||
items: readonly ShippingProcessingProjection[] | null | undefined,
|
||||
): ShippingProcessingProjection[] {
|
||||
const rows: ShippingProcessingProjection[] = [];
|
||||
const visit = (item: ShippingProcessingProjection) => {
|
||||
const nested = Array.isArray(item.aggregateChildren) ? item.aggregateChildren : [];
|
||||
if (nested.length) {
|
||||
nested.forEach(visit);
|
||||
return;
|
||||
}
|
||||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||||
if (filename.toLowerCase().endsWith('.eml')) return;
|
||||
// 没有文件名的聚合容器不能伪造一个文件行。
|
||||
if (!filename && item.sourceType === 'eml') return;
|
||||
rows.push(item);
|
||||
};
|
||||
(items || []).forEach(visit);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 以文档 ID 优先、文件名兜底,对叶子业务文件稳定去重。 */
|
||||
export function businessFileKeys(
|
||||
items: readonly ShippingProcessingProjection[] | null | undefined,
|
||||
): string[] {
|
||||
const keys = new Set<string>();
|
||||
for (const item of flattenBusinessFileProjections(items)) {
|
||||
const id = Number(item.sourceSummary?.documentId || 0);
|
||||
const filename = String(item.sourceSummary?.filename || '').trim().toLowerCase();
|
||||
const key = id > 0 ? `document:${id}` : filename ? `filename:${filename}` : '';
|
||||
if (key) keys.add(key);
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
/**
|
||||
* 标准化动作码列表:去空白、小写、去重、字典序排序。
|
||||
@@ -67,9 +107,13 @@ export function buildTaskSemanticKey(
|
||||
displayKind: task.display_kind,
|
||||
fileCount: task.file_count,
|
||||
title: task.title,
|
||||
primaryAction: (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? null,
|
||||
// [AUTHORITY] 新会话批次的可操作动作由 ui_state 单独版本化;把它纳入语义键,
|
||||
// 避免状态未变但后端撤销/切换按钮时前端错误复用旧任务对象。
|
||||
primaryAction: task.uiState
|
||||
? (task.uiState.primary_action?.code ?? null)
|
||||
: ((task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? null),
|
||||
currentGate: (task as ConversationProcessingUserTask & {
|
||||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||||
blockingReason?: { code?: string } | null;
|
||||
@@ -90,7 +134,11 @@ export function buildTaskSemanticKey(
|
||||
?? null,
|
||||
}
|
||||
: null,
|
||||
availableActions: normalizeActionCodes(task.available_actions || []),
|
||||
availableActions: normalizeActionCodes(
|
||||
task.uiState
|
||||
? task.uiState.secondary_actions.filter((action) => action.enabled).map((action) => action.code)
|
||||
: (task.available_actions || []),
|
||||
),
|
||||
canAppend: task.can_append ?? null,
|
||||
aggregateChildren,
|
||||
});
|
||||
@@ -879,6 +927,11 @@ export function resolveConversationProcessingFromUnified(
|
||||
stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
// [AUTHORITY] 新版接口已经由后端完成「状态 → EML → 业务文件」聚合。
|
||||
// 会话卡与批次中心必须直接使用该结果;前端从 work_items 重建只保留给旧响应兼容。
|
||||
if (embedded && typeof embedded === 'object' && embedded.status_groups) {
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
// [TRANSITION] 只有统一投影里明确存在 order_task,才认为 OT 维度已经成形。
|
||||
// 仅 order_intake 存在时视为过渡阶段:
|
||||
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
|
||||
@@ -919,56 +972,150 @@ export function resolveConversationProcessingFromUnified(
|
||||
export function normalizeConversationProcessingProjection(
|
||||
projection: ConversationProcessingProjection,
|
||||
): ConversationProcessingProjection {
|
||||
const backendAuthoritative = Boolean(projection.status_groups);
|
||||
const normalizeUiState = (
|
||||
rawState: ConversationProcessingUserTask['uiState'] | undefined,
|
||||
): ConversationProcessingUserTask['uiState'] | undefined => {
|
||||
if (!rawState || typeof rawState !== 'object') return undefined;
|
||||
const state = rawState as ConversationProcessingUserTask['uiState'] & {
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
secondaryActions?: Array<{ code: string; enabled: boolean }>;
|
||||
};
|
||||
const normalizeAction = (action: ShippingProcessingPrimaryAction | null | undefined) => {
|
||||
if (!action || typeof action !== 'object') return null;
|
||||
const rawAction = action as ShippingProcessingPrimaryAction & { i18n_key?: string | null };
|
||||
return {
|
||||
...rawAction,
|
||||
i18nKey: rawAction.i18nKey ?? rawAction.i18n_key ?? null,
|
||||
};
|
||||
};
|
||||
const normalizeReason = (reason: ShippingProcessingBlockingReason | null | undefined) => {
|
||||
if (!reason || typeof reason !== 'object') return null;
|
||||
const rawReason = reason as ShippingProcessingBlockingReason & { i18n_key?: string | null };
|
||||
return {
|
||||
...rawReason,
|
||||
i18nKey: rawReason.i18nKey ?? rawReason.i18n_key ?? null,
|
||||
};
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
blocking_reason: normalizeReason(state.blocking_reason ?? state.blockingReason),
|
||||
primary_action: normalizeAction(state.primary_action ?? state.primaryAction),
|
||||
secondary_actions: state.secondary_actions ?? state.secondaryActions ?? [],
|
||||
};
|
||||
};
|
||||
const normalizeTask = (task: ConversationProcessingUserTask): ConversationProcessingUserTask => {
|
||||
const raw = task as ConversationProcessingUserTask & {
|
||||
user_status?: ConversationProcessingUserTask['userStatus'];
|
||||
user_stage?: ConversationProcessingUserTask['userStage'];
|
||||
user_group?: ConversationProcessingUserTask['userGroup'];
|
||||
blocking_reason?: ConversationProcessingUserTask['blockingReason'];
|
||||
primary_action?: ConversationProcessingUserTask['primaryAction'] | string | null;
|
||||
aggregate_summary?: ConversationProcessingUserTask['aggregateSummary'];
|
||||
aggregate_children?: unknown[];
|
||||
};
|
||||
const rawPrimaryAction = raw.primaryAction ?? raw.primary_action ?? null;
|
||||
const aggregateChildren = Array.isArray(raw.aggregateChildren)
|
||||
? raw.aggregateChildren
|
||||
: (Array.isArray(raw.aggregate_children)
|
||||
? raw.aggregate_children
|
||||
.map(normalizeShippingProcessingProjection)
|
||||
.filter((item): item is ShippingProcessingProjection => Boolean(item))
|
||||
: []);
|
||||
// 新批次投影的 group/user_group 已由后端裁决;旧 embedded 响应没有 status_groups,
|
||||
// 仅在该兼容分支维持历史规范化,避免旧服务端响应把待人工留在处理中。
|
||||
const rawStatus = task.userStatus ?? task.status_label;
|
||||
const normalizedStatus = normalizeLifecycleStatus(rawStatus);
|
||||
const availableActions = Array.isArray(task.available_actions) ? task.available_actions : [];
|
||||
const hasHumanAction = availableActions.some((value) => {
|
||||
const legacyActions = Array.isArray(task.available_actions) ? task.available_actions : [];
|
||||
const legacyHasHumanAction = legacyActions.some((value) => {
|
||||
const code = String(value || '').trim().toLowerCase();
|
||||
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
|
||||
});
|
||||
const recomputedGroup = classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
|
||||
needsCustomerConfirm: hasHumanAction,
|
||||
});
|
||||
const finalGroup: ConversationProcessingTaskGroup = (() => {
|
||||
// [LEGACY-UNIFY] waiting_human 旧投影若被归在 processing / history,强制迁入 needs_action。
|
||||
if (recomputedGroup === 'needs_action') return 'needs_action';
|
||||
if (normalizedStatus === 'waiting_review') return 'needs_action';
|
||||
return task.group || recomputedGroup;
|
||||
})();
|
||||
const finalGroup: ConversationProcessingTaskGroup = backendAuthoritative
|
||||
? task.group
|
||||
: classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
|
||||
needsCustomerConfirm: legacyHasHumanAction,
|
||||
});
|
||||
return {
|
||||
...task,
|
||||
status_label: normalizedStatus || (task.status_label ?? ''),
|
||||
// userStatus 保持原有强类型;会话侧展示统一走 status_label/group,避免放宽成 string 破坏类型契约。
|
||||
userStatus: task.userStatus ?? null,
|
||||
status_label: backendAuthoritative
|
||||
? task.status_label
|
||||
: (normalizedStatus || task.status_label),
|
||||
userStatus: raw.userStatus ?? raw.user_status ?? null,
|
||||
userStage: raw.userStage ?? raw.user_stage ?? null,
|
||||
userGroup: raw.userGroup ?? raw.user_group ?? null,
|
||||
blockingReason: raw.blockingReason ?? raw.blocking_reason ?? null,
|
||||
primaryAction: typeof rawPrimaryAction === 'object' ? rawPrimaryAction : null,
|
||||
primary_action: typeof rawPrimaryAction === 'string' ? rawPrimaryAction : task.primary_action,
|
||||
aggregateSummary: raw.aggregateSummary ?? raw.aggregate_summary ?? null,
|
||||
aggregateChildren,
|
||||
uiState: normalizeUiState(
|
||||
(raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).uiState
|
||||
?? (raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).ui_state,
|
||||
),
|
||||
group: finalGroup,
|
||||
};
|
||||
};
|
||||
const normalizedAll = [
|
||||
const normalizedLegacyTasks = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(projection.history || []),
|
||||
].map(normalizeTask);
|
||||
const needs_action = normalizedAll.filter((task) => task.group === 'needs_action');
|
||||
const processing = normalizedAll.filter((task) => task.group === 'processing');
|
||||
const completed = normalizedAll.filter((task) => task.group === 'completed');
|
||||
const history = normalizedAll.filter((task) => task.group === 'history');
|
||||
const normalizedGroups = projection.status_groups
|
||||
? {
|
||||
failed: (projection.status_groups.failed || []).map(normalizeTask),
|
||||
waiting_human: (projection.status_groups.waiting_human || []).map(normalizeTask),
|
||||
processing: (projection.status_groups.processing || []).map(normalizeTask),
|
||||
completed: (projection.status_groups.completed || []).map(normalizeTask),
|
||||
cancelled: (projection.status_groups.cancelled || []).map(normalizeTask),
|
||||
archived: (projection.status_groups.archived || []).map(normalizeTask),
|
||||
}
|
||||
: null;
|
||||
// status_groups 存在时,传统四组只是兼容镜像,可能为空;统计必须保留后端 summary,
|
||||
// 绝不能据空镜像重新裁决成 0。
|
||||
const normalizedAll = normalizedGroups
|
||||
? [
|
||||
...normalizedGroups.failed,
|
||||
...normalizedGroups.waiting_human,
|
||||
...normalizedGroups.processing,
|
||||
...normalizedGroups.completed,
|
||||
...normalizedGroups.cancelled,
|
||||
...normalizedGroups.archived,
|
||||
]
|
||||
: normalizedLegacyTasks;
|
||||
const needs_action = normalizedGroups
|
||||
? [...normalizedGroups.failed, ...normalizedGroups.waiting_human]
|
||||
: normalizedAll.filter((task) => task.group === 'needs_action');
|
||||
const processing = normalizedGroups?.processing || normalizedAll.filter((task) => task.group === 'processing');
|
||||
const completed = normalizedGroups?.completed || normalizedAll.filter((task) => task.group === 'completed');
|
||||
const history = normalizedGroups
|
||||
? [...normalizedGroups.cancelled, ...normalizedGroups.archived]
|
||||
: normalizedAll.filter((task) => task.group === 'history');
|
||||
return {
|
||||
...projection,
|
||||
summary: {
|
||||
...(projection.summary || {}),
|
||||
total_tasks: normalizedAll.length,
|
||||
total_files: normalizedAll.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
|
||||
needs_action: needs_action.length,
|
||||
processing: processing.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
},
|
||||
// [AUTHORITY] 新批次 status_groups + summary 同属一次后端裁决。summary 可能覆盖完整批次,
|
||||
// 而当前组只返回可见 EML;前端不得用局部行数覆盖后端文件/任务统计。
|
||||
summary: backendAuthoritative
|
||||
? projection.summary
|
||||
: {
|
||||
...(projection.summary || {}),
|
||||
total_tasks: normalizedAll.length,
|
||||
total_files: normalizedAll.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
|
||||
needs_action: needs_action.length,
|
||||
processing: processing.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
},
|
||||
needs_action,
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
status_groups: normalizedGroups || projection.status_groups,
|
||||
four_stage_nodes: projection.four_stage_nodes || [],
|
||||
ui_state: projection.ui_state || undefined,
|
||||
output_artifacts: projection.output_artifacts || [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -999,8 +1146,42 @@ export function projectConversationProcessingFromWorkItems(
|
||||
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
|
||||
if (!taskNo) continue;
|
||||
const group = mapShippingProcessingStatusToTaskGroup(item);
|
||||
const docCount = Number(item.sourceSummary?.documentCount || 0);
|
||||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||||
// EML 父项的 sourceSummary.filename 是邮件名,只能用于分组标题;
|
||||
// 文件行与数量必须来自其真实附件叶子。
|
||||
const leafFiles = flattenBusinessFileProjections([item]);
|
||||
const leafKeys = businessFileKeys([item]);
|
||||
const leafNames = [...new Set(leafFiles
|
||||
.map((child) => String(child.sourceSummary?.filename || '').trim())
|
||||
.filter(Boolean))];
|
||||
const leafObjects = leafFiles.map((child, index) => {
|
||||
const summary = child.sourceSummary || {};
|
||||
const documentId = Number(summary.documentId || 0) || undefined;
|
||||
const leafFilename = String(summary.filename || '').trim();
|
||||
return {
|
||||
kind: 'document' as const,
|
||||
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-leaf-${index}`,
|
||||
label: leafFilename || String(child.workItemNo || taskNo),
|
||||
filename: leafFilename || undefined,
|
||||
document_id: documentId,
|
||||
status_label: String(child.userStatus ?? child.status ?? ''),
|
||||
run_no: child.runNo || undefined,
|
||||
current_run_no: child.runNo || undefined,
|
||||
case_no: child.caseNo || undefined,
|
||||
task_no: child.rootOrderTaskNo || undefined,
|
||||
workflow_item_no: child.workItemNo || undefined,
|
||||
};
|
||||
});
|
||||
const isEmlContainer = item.sourceType === 'eml' && Array.isArray(item.aggregateChildren)
|
||||
&& item.aggregateChildren.length > 0;
|
||||
const sourceDocCount = Number(item.sourceSummary?.documentCount || 0);
|
||||
// 只有已展开的 EML 聚合以叶子集合覆盖后端摘要;普通/旧单项投影仍保留
|
||||
// sourceSummary.documentCount,避免稀疏投影把一个多文件任务错误压成 1 个文件。
|
||||
const docCount = isEmlContainer
|
||||
? leafKeys.length
|
||||
: (sourceDocCount || leafKeys.length);
|
||||
const filename = isEmlContainer
|
||||
? String(item.sourceSummary?.filename || '').trim()
|
||||
: (leafNames[0] || String(item.sourceSummary?.filename || '').trim());
|
||||
const normalizedActions = normalizeActionCodes(item.availableActions || []);
|
||||
const gateNextAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase() || null;
|
||||
const effectiveStatus = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim()) || null;
|
||||
@@ -1040,11 +1221,12 @@ export function projectConversationProcessingFromWorkItems(
|
||||
user_task_authoritative: true,
|
||||
title: filename || null,
|
||||
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
|
||||
document_names: filename ? [filename] : [],
|
||||
document_names: leafNames.length ? leafNames : (isEmlContainer ? [] : (filename ? [filename] : [])),
|
||||
group,
|
||||
status_label: effectiveStatus,
|
||||
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
|
||||
file_count: docCount > 0 ? docCount : (isEmlContainer ? 0 : (filename ? 1 : 0)),
|
||||
run_no: String(item.runNo || '').trim() || null,
|
||||
objects: leafObjects,
|
||||
can_append: false,
|
||||
last_activity_at: item.lastActivityAt || null,
|
||||
available_actions: normalizedActions,
|
||||
@@ -1132,8 +1314,11 @@ export function projectConversationProcessingFromWorkItems(
|
||||
? 'history'
|
||||
: 'processing';
|
||||
const representative = entries[0]!.task;
|
||||
const documentNames = [...new Set(entries.flatMap(({ task }) => task.document_names || []).filter(Boolean))];
|
||||
const fileCount = entries.reduce((sum, { task }) => sum + Number(task.file_count || 0), 0);
|
||||
const aggregateChildren = entries.flatMap(({ item }) => item.aggregateChildren || [item]);
|
||||
const documentNames = [...new Set(flattenBusinessFileProjections(aggregateChildren)
|
||||
.map((child) => String(child.sourceSummary?.filename || '').trim())
|
||||
.filter(Boolean))];
|
||||
const fileCount = businessFileKeys(aggregateChildren).length;
|
||||
rawTasks.push({
|
||||
...representative,
|
||||
title: representative.title || `EML ${intakeNo}`,
|
||||
@@ -1152,7 +1337,7 @@ export function projectConversationProcessingFromWorkItems(
|
||||
stages,
|
||||
reasonCodes,
|
||||
},
|
||||
aggregateChildren: entries.flatMap(({ item }) => item.aggregateChildren || [item]),
|
||||
aggregateChildren,
|
||||
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
|
||||
});
|
||||
}
|
||||
@@ -1172,14 +1357,11 @@ export function projectConversationProcessingFromWorkItems(
|
||||
const active = [...needs_action_raw, ...processing_raw, ...completed_raw];
|
||||
if (!active.length && !history_raw.length) return null;
|
||||
|
||||
const documentIds = new Set(
|
||||
orderTasks
|
||||
.map((item) => Number(item.sourceSummary?.documentId || 0))
|
||||
.filter((id) => id > 0),
|
||||
// 统计口径与卡片完全一致:递归叶子业务文件,排除 EML 容器。
|
||||
const totalFiles = businessFileKeys(orderTasks).length || active.reduce(
|
||||
(sum, task) => sum + Number(task.file_count || 0),
|
||||
0,
|
||||
);
|
||||
const totalFiles = documentIds.size > 0
|
||||
? documentIds.size
|
||||
: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
|
||||
|
||||
const stabilizedAll = stabilizeTaskObjects(
|
||||
previousProjection
|
||||
|
||||
@@ -31,7 +31,27 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
blocking_reason_code: 'pdf_preferred_critical_conflict',
|
||||
attempt_no: 1,
|
||||
},
|
||||
process_gate: {
|
||||
execution_no: 'EXE-1',
|
||||
status: 'blocked',
|
||||
current_gate_code: 'inventory_preparation',
|
||||
expected_gate_version: 3,
|
||||
current_blocking_gate: {
|
||||
gate_code: 'inventory_preparation',
|
||||
status: 'blocked_manual',
|
||||
evaluation_version: 3,
|
||||
},
|
||||
next_action_code: 'retry_inventory_preparation',
|
||||
allowed_actions: ['retry_inventory_preparation', 'upload_inventory_file'],
|
||||
},
|
||||
available_actions: ['open_review'],
|
||||
ui_state: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'pdf_preferred_critical_conflict' },
|
||||
primary_action: { code: 'resolve_field_conflicts', i18n_key: 'action.resolve_field_conflicts' },
|
||||
secondary_actions: [{ code: 'view_details', enabled: true }],
|
||||
},
|
||||
source_summary: {
|
||||
email_subject: null,
|
||||
filename: 'a.pdf',
|
||||
@@ -53,10 +73,23 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized!.status).toBe('waiting_review');
|
||||
expect(normalized!.currentGate?.gateCode).toBe('field_conflict_resolution');
|
||||
expect(normalized!.currentGate?.attemptNo).toBe(1);
|
||||
expect(normalized!.processGate).toMatchObject({
|
||||
execution_no: 'EXE-1',
|
||||
current_gate_code: 'inventory_preparation',
|
||||
expected_gate_version: 3,
|
||||
next_action_code: 'retry_inventory_preparation',
|
||||
});
|
||||
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
|
||||
expect(normalized!.sourceSummary.documentId).toBe(17);
|
||||
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
|
||||
expect(normalized!.availableActions).toEqual(['open_review']);
|
||||
expect(normalized!.uiState).toEqual({
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'pdf_preferred_critical_conflict', i18nKey: null, details: {} },
|
||||
primary_action: { code: 'resolve_field_conflicts', i18nKey: 'action.resolve_field_conflicts', parameters: {} },
|
||||
secondary_actions: [{ code: 'view_details', enabled: true }],
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes stage_nodes from backend', () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
ShippingProcessingStageNodeStatus,
|
||||
ShippingProcessingStatus,
|
||||
ShippingProcessingWorkItemType,
|
||||
ShippingProcessGateUserSummary,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
/**
|
||||
@@ -372,6 +373,7 @@ export function normalizeShippingProcessingProjection(
|
||||
lastActivityAt: readString(item, 'last_activity_at', 'lastActivityAt'),
|
||||
stageNodes: stageNodes?.length ? stageNodes : undefined,
|
||||
currentGate: normalizeGate(item.current_gate ?? item.currentGate),
|
||||
processGate: normalizeProcessGateSummary(item.process_gate ?? item.processGate),
|
||||
availableActions,
|
||||
sourceSummary: {
|
||||
emailSubject: readNullableString(summaryRaw, 'email_subject', 'emailSubject'),
|
||||
@@ -396,6 +398,7 @@ export function normalizeShippingProcessingProjection(
|
||||
retryable:
|
||||
(item.retryable as boolean | undefined) == null ? false : Boolean(item.retryable),
|
||||
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
|
||||
uiState: normalizeProcessingUiState(item.ui_state ?? item.uiState),
|
||||
facts: normalizeFacts(item.facts),
|
||||
userGroup: readNullableString(item, 'user_group', 'userGroup') as ShippingProcessingProjection['userGroup'],
|
||||
aggregateSummary: normalizeAggregateSummary(item.aggregate_summary ?? item.aggregateSummary),
|
||||
@@ -410,6 +413,38 @@ export function normalizeShippingProcessingProjection(
|
||||
};
|
||||
}
|
||||
|
||||
/** 保留后端 Gate 摘要原字段;写操作需要 execution_no 与 evaluation_version,不能降级为展示节点。 */
|
||||
function normalizeProcessGateSummary(raw: unknown): ShippingProcessGateUserSummary | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
return readString(item, 'execution_no', 'executionNo')
|
||||
? item as unknown as ShippingProcessGateUserSummary
|
||||
: null;
|
||||
}
|
||||
|
||||
/** 规范化单项后端 UI 裁决;缺失时返回 undefined 以保留旧响应兼容。 */
|
||||
function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection['uiState'] {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
const state = raw as Record<string, unknown>;
|
||||
const secondaryRaw = state.secondary_actions ?? state.secondaryActions;
|
||||
const secondaryActions = Array.isArray(secondaryRaw)
|
||||
? secondaryRaw
|
||||
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
|
||||
.map((item) => ({
|
||||
code: readString(item, 'code', 'code'),
|
||||
enabled: item.enabled !== false,
|
||||
}))
|
||||
.filter((item) => Boolean(item.code))
|
||||
: [];
|
||||
return {
|
||||
status: (readString(state, 'status', 'status') || 'running') as NonNullable<ShippingProcessingProjection['userStatus']>,
|
||||
stage: readString(state, 'stage', 'stage'),
|
||||
blocking_reason: normalizeBlockingReason(state.blocking_reason ?? state.blockingReason),
|
||||
primary_action: normalizePrimaryAction(state.primary_action ?? state.primaryAction),
|
||||
secondary_actions: secondaryActions,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将会话级统一投影响应中的 work_items 规范为数组。
|
||||
*/
|
||||
|
||||
@@ -17,6 +17,12 @@ describe('shippingProcessingLabels', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the localized waiting_human label instead of exposing the status code', () => {
|
||||
const te = (key: string) => key === 'chat.shippingProcessing.status.waiting_human';
|
||||
const t = (key: string) => key.endsWith('waiting_human') ? '待人工处理' : key;
|
||||
expect(resolveShippingProcessingStatusLabel('waiting_human', te, t)).toBe('待人工处理');
|
||||
});
|
||||
|
||||
it('falls back to shippingProcessing.taskStatus when unified status missing', () => {
|
||||
// 关键断言:旧 taskStatus 已合并进 shippingProcessing。
|
||||
const te = (key: string) => key === 'chat.shippingProcessing.taskStatus.queued';
|
||||
|
||||
@@ -12,6 +12,7 @@ const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
|
||||
processing: 'processing',
|
||||
pending_review: 'waiting_review',
|
||||
waiting_review: 'waiting_review',
|
||||
waiting_human: 'waiting_human',
|
||||
failed: 'failed',
|
||||
completed: 'completed',
|
||||
cancelled: 'cancelled',
|
||||
|
||||
@@ -1,50 +1,49 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingStepper.spec.ts
|
||||
* 用途:验证发货通知七步 Stepper 的本地兜底状态映射。
|
||||
* 用途:验证发货通知四阶段 Stepper 只消费后端 UI State 投影。
|
||||
* 依赖:shippingStepper 纯函数、vitest。
|
||||
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
applyShippingProcessingStageToSteps,
|
||||
buildShippingWorkflowSteps,
|
||||
normalizeShippingWorkflowSteps,
|
||||
resolveShippingWorkflowSteps,
|
||||
} from './shippingStepper';
|
||||
|
||||
describe('shippingStepper', () => {
|
||||
it('marks inventory step as blocked when RPA inventory is exhausted', () => {
|
||||
// 关键断言:库存 RPA 获取失败是业务阻断态,不能在步骤条里继续显示为普通 current。
|
||||
const steps = buildShippingWorkflowSteps({
|
||||
process_status: 'waiting_inventory',
|
||||
pending_human_reason: 'rpa_exhausted',
|
||||
current_step: 'step3_inventory_prepare',
|
||||
it('renders exactly four stages from backend ui_state', () => {
|
||||
const steps = resolveShippingWorkflowSteps({
|
||||
ui_state: {
|
||||
steps: [
|
||||
{ id: 'shipping-stage-1', code: 'intake_parse', label: '接收解析', status: 'completed' },
|
||||
{ id: 'shipping-stage-2', code: 'order_review', label: '订单复核', status: 'completed' },
|
||||
{ id: 'shipping-stage-3', code: 'fulfillment_prep', label: '发货准备', status: 'blocked' },
|
||||
{ id: 'shipping-stage-4', code: 'upload_complete', label: '上传完成', status: 'pending' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(steps).toHaveLength(4);
|
||||
expect(steps[2]?.status).toBe('blocked');
|
||||
});
|
||||
|
||||
it('marks inventory step as blocked when inventory source is unavailable', () => {
|
||||
// 关键断言:库存触发失败需要用户上传库存或重试,同样应在第 3 步显示异常。
|
||||
const steps = buildShippingWorkflowSteps({
|
||||
process_status: 'waiting_inventory',
|
||||
pending_human_reason: 'inv_unavail',
|
||||
current_step: 'step3_inventory_prepare',
|
||||
});
|
||||
|
||||
expect(steps[2]?.status).toBe('blocked');
|
||||
it('fails closed when backend ui_state is missing', () => {
|
||||
expect(resolveShippingWorkflowSteps({ review_status: 'parse_review' } as never)).toEqual([]);
|
||||
expect(normalizeShippingWorkflowSteps(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it('overlays unified processing stage onto base stepper steps', () => {
|
||||
const base = buildShippingWorkflowSteps({
|
||||
process_status: 'parsed',
|
||||
current_step: 'step2_parse_confirm',
|
||||
it('maps technical processing stages into the four business stages', () => {
|
||||
const base = normalizeShippingWorkflowSteps([
|
||||
{ code: 'intake_parse', status: 'pending' },
|
||||
{ code: 'order_review', status: 'pending' },
|
||||
{ code: 'fulfillment_prep', status: 'pending' },
|
||||
{ code: 'upload_complete', status: 'pending' },
|
||||
]);
|
||||
const steps = applyShippingProcessingStageToSteps(base, {
|
||||
stage: 'inventory_matching',
|
||||
status: 'running',
|
||||
});
|
||||
const overlaid = applyShippingProcessingStageToSteps(base, {
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
currentGate: { status: 'blocked' },
|
||||
});
|
||||
// 关键断言:统一投影 waiting_review 应把第 2 步标为 blocked,而非沿用旧 process_status。
|
||||
expect(overlaid[1]?.status).toBe('blocked');
|
||||
expect(overlaid[0]?.status).toBe('completed');
|
||||
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending']);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,8 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingStepper.ts
|
||||
* 用途:基于 shipping task 状态推导前端 Stepper 展示数据(七步 legacy / 四步履约)。
|
||||
* 用途:基于后端 ui_state 投影渲染四阶段业务 Stepper。
|
||||
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
|
||||
* 逻辑:任务台优先 buildFulfillmentWorkflowSteps(四节点);无投影时不回退旧 ui_state;
|
||||
* resolveShippingWorkflowSteps 仍供对话等未切流页面作 legacy 回退。
|
||||
* 逻辑:只消费后端 ui_state.steps 四阶段投影;缺失投影时 fail-closed。
|
||||
*/
|
||||
import {
|
||||
FULFILLMENT_PROGRESS_NODES,
|
||||
@@ -11,12 +10,9 @@ import {
|
||||
type FulfillmentProgressNodeKey,
|
||||
} from './shippingProcessingFulfillment';
|
||||
export interface ShippingTaskStepperSource {
|
||||
process_status?: string | null;
|
||||
review_status?: string | null;
|
||||
pending_human_reason?: string | null;
|
||||
match_status?: string | null;
|
||||
export_file_name?: string | null;
|
||||
current_step?: string | null;
|
||||
ui_state?: {
|
||||
steps?: ShippingWorkflowStepSource[] | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface ShippingWorkflowStepItem {
|
||||
@@ -33,32 +29,12 @@ type ShippingWorkflowStepSource = {
|
||||
};
|
||||
|
||||
export const SHIPPING_WORKFLOW_STEP_LABELS = [
|
||||
'chat.shippingNoticeUi.stepper.noticeSubmit',
|
||||
'chat.shippingNoticeUi.stepper.parseConfirm',
|
||||
'chat.shippingNoticeUi.stepper.inventoryPrepare',
|
||||
'chat.shippingNoticeUi.stepper.alignConfirm',
|
||||
'chat.shippingNoticeUi.stepper.matchInventory',
|
||||
'chat.shippingNoticeUi.stepper.generateFile',
|
||||
'chat.shippingNoticeUi.stepper.uploadFreight',
|
||||
'chat.shippingNoticeUi.stage.intakeParse',
|
||||
'chat.shippingNoticeUi.stage.orderReview',
|
||||
'chat.shippingNoticeUi.stage.fulfillmentPrep',
|
||||
'chat.shippingNoticeUi.stage.uploadComplete',
|
||||
] as const;
|
||||
|
||||
const CURRENT_STEP_INDEX_MAP: Record<string, number> = {
|
||||
step1_notice_submit: 0,
|
||||
step2_parse_confirm: 1,
|
||||
step3_inventory_prepare: 2,
|
||||
step2_inventory_prepare: 2,
|
||||
step4_align_confirm: 3,
|
||||
step5_match_inventory: 4,
|
||||
step3_inventory_match: 4,
|
||||
step4_shortage_review: 4,
|
||||
step6_generate_file: 5,
|
||||
step5_export_excel: 5,
|
||||
step7_upload_freight: 6,
|
||||
step6_upload_freight: 6,
|
||||
step7_finish: 6,
|
||||
};
|
||||
|
||||
const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
|
||||
const WORKFLOW_STEP_STATUSES = new Set<ShippingWorkflowStepItem['status']>([
|
||||
'completed',
|
||||
'current',
|
||||
@@ -80,7 +56,7 @@ export function normalizeShippingWorkflowSteps(
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: String(step?.id || step?.code || `shipping-step-${index + 1}`),
|
||||
id: String(step?.id || step?.code || `shipping-stage-${index + 1}`),
|
||||
label: String(step?.label || SHIPPING_WORKFLOW_STEP_LABELS[index] || ''),
|
||||
status: status as ShippingWorkflowStepItem['status'],
|
||||
};
|
||||
@@ -89,76 +65,32 @@ export function normalizeShippingWorkflowSteps(
|
||||
}
|
||||
|
||||
/**
|
||||
* 优先消费后端状态机 UI State steps;没有时按 task 状态本地推导。
|
||||
* 只消费后端状态机 UI State steps;没有投影时返回空数组,禁止本地猜测阶段。
|
||||
*/
|
||||
export function resolveShippingWorkflowSteps(
|
||||
task: (ShippingTaskStepperSource & { ui_state?: { steps?: ShippingWorkflowStepSource[] | null } | null }) | null | undefined,
|
||||
task: ShippingTaskStepperSource | null | undefined,
|
||||
): ShippingWorkflowStepItem[] {
|
||||
const uiStateSteps = normalizeShippingWorkflowSteps(task?.ui_state?.steps);
|
||||
return uiStateSteps.length ? uiStateSteps : buildShippingWorkflowSteps(task);
|
||||
}
|
||||
|
||||
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
|
||||
const currentStep = String(task?.current_step || '').trim();
|
||||
const processStatus = String(task?.process_status || '').trim();
|
||||
const reviewStatus = String(task?.review_status || '').trim();
|
||||
const pendingReason = String(task?.pending_human_reason || '').trim();
|
||||
const matchStatus = String(task?.match_status || '').trim();
|
||||
const hasExport = !!String(task?.export_file_name || '').trim();
|
||||
|
||||
if (currentStep) {
|
||||
const currentStepIndex = CURRENT_STEP_INDEX_MAP[currentStep];
|
||||
if (currentStepIndex !== undefined) {
|
||||
return currentStepIndex;
|
||||
}
|
||||
}
|
||||
|
||||
if (TERMINAL_PROCESS_STATUSES.has(processStatus)) return 6;
|
||||
if (processStatus === 'waiting_upload' || processStatus === 'upload_failed' || hasExport) return 5;
|
||||
if (processStatus === 'matched') return 4;
|
||||
if (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage') return 4;
|
||||
if (processStatus === 'inventory_ready' || matchStatus) return 4;
|
||||
if (
|
||||
processStatus === 'waiting_inventory'
|
||||
|| pendingReason === 'rpa_pending'
|
||||
|| pendingReason === 'inv_unavail'
|
||||
|| pendingReason === 'rpa_exhausted'
|
||||
) {
|
||||
return 2;
|
||||
}
|
||||
if (
|
||||
processStatus === 'parsed'
|
||||
|| processStatus === 'pending_review'
|
||||
|| reviewStatus === 'pending_confirm'
|
||||
|| reviewStatus === 'parse_review'
|
||||
|| reviewStatus === 'rsv_required'
|
||||
|| pendingReason === 'low_confidence'
|
||||
|| pendingReason === 'rsv_required'
|
||||
|| pendingReason === 'inventory_source_unresolved'
|
||||
) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
return uiStateSteps;
|
||||
}
|
||||
|
||||
/** 统一 ShippingProcessingStage → 粗粒度 Stepper 下标(过渡期;阶段 2 换 UnifiedProgressTrack)。 */
|
||||
const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
|
||||
upload_received: 0,
|
||||
email_parsing: 1,
|
||||
document_parsing: 1,
|
||||
email_parsing: 0,
|
||||
document_parsing: 0,
|
||||
email_adjudicating: 1,
|
||||
candidate_creating: 1,
|
||||
customer_resolving: 1,
|
||||
duplicate_checking: 1,
|
||||
// 业务 15 阶中库存源在复核前;七步 legacy 仍映射到「库存准备」步。
|
||||
inventory_source_resolving: 2,
|
||||
waiting_review: 1,
|
||||
order_creating: 1,
|
||||
inventory_source_resolving: 2,
|
||||
inventory_fetching: 2,
|
||||
inventory_matching: 4,
|
||||
excel_generating: 5,
|
||||
freight_uploading: 6,
|
||||
completed: 6,
|
||||
inventory_matching: 2,
|
||||
excel_generating: 2,
|
||||
freight_uploading: 3,
|
||||
completed: 3,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -167,7 +99,7 @@ const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
|
||||
* 核心逻辑:有投影时按 stage 重算 completed/current/pending;blocked/failed 标当前步 blocked;
|
||||
* 无投影或无法映射时原样返回 baseSteps。
|
||||
*
|
||||
* @param baseSteps - ui_state / process_status 推导的步骤
|
||||
* @param baseSteps - ui_state 推导的步骤
|
||||
* @param projection - 统一 order_task 投影
|
||||
*/
|
||||
export function applyShippingProcessingStageToSteps(
|
||||
@@ -200,47 +132,12 @@ export function applyShippingProcessingStageToSteps(
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 task 状态映射为七步 Stepper 项(id / label / done / active)。
|
||||
* 缺少后端投影时 fail-closed,不根据 review/match/upload 等领域事实猜测阶段。
|
||||
*/
|
||||
export function buildShippingWorkflowSteps(
|
||||
task: ShippingTaskStepperSource | null | undefined,
|
||||
_task: ShippingTaskStepperSource | null | undefined,
|
||||
): ShippingWorkflowStepItem[] {
|
||||
const currentIndex = deriveCurrentIndex(task);
|
||||
const reviewStatus = String(task?.review_status || '').trim();
|
||||
const pendingReason = String(task?.pending_human_reason || '').trim();
|
||||
const processStatus = String(task?.process_status || '').trim();
|
||||
|
||||
return SHIPPING_WORKFLOW_STEP_LABELS.map((label, index) => {
|
||||
let status: ShippingWorkflowStepItem['status'] = 'pending';
|
||||
// [STEP 1] uploaded/closed 是整票已完成的终态,不能再被 current_step 渲染成“第 7 步进行中”。
|
||||
if (TERMINAL_PROCESS_STATUSES.has(processStatus)) {
|
||||
status = 'completed';
|
||||
} else if (index < currentIndex) {
|
||||
status = 'completed';
|
||||
} else if (index === currentIndex) {
|
||||
status = 'current';
|
||||
}
|
||||
|
||||
if (
|
||||
(index === 1 && (
|
||||
reviewStatus === 'parse_review'
|
||||
|| pendingReason === 'low_confidence'
|
||||
|| pendingReason === 'rsv_required'
|
||||
|| pendingReason === 'inventory_source_unresolved'
|
||||
))
|
||||
|| (index === 2 && (pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted'))
|
||||
|| (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage'))
|
||||
|| (index === 6 && processStatus === 'upload_failed')
|
||||
) {
|
||||
status = 'blocked';
|
||||
}
|
||||
|
||||
return {
|
||||
id: `shipping-step-${index + 1}`,
|
||||
label,
|
||||
status,
|
||||
};
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -275,7 +275,7 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
|
||||
.replace(/\braw_text\b/gi, '通知原文');
|
||||
result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
|
||||
result = result.replace(
|
||||
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
|
||||
/\b(pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[^\s,;]+[「"'`]?/gi,
|
||||
'',
|
||||
);
|
||||
for (const token of SHIPPING_INTERNAL_STATUS_TOKENS) {
|
||||
|
||||
@@ -44,7 +44,7 @@ describe('useChatShippingRefresh', () => {
|
||||
task_no: 'SN-FOCUS-B',
|
||||
batch_no: 'SB-FOCUS-001',
|
||||
checkpoint: 'ready_export',
|
||||
process_status: 'matched',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
pending_human_reason: null,
|
||||
match_status: 'fulfillable',
|
||||
@@ -105,7 +105,7 @@ describe('useChatShippingRefresh', () => {
|
||||
task_no: 'SN-SOURCE-001',
|
||||
batch_no: 'SB-SOURCE-001',
|
||||
checkpoint: 'ready_export',
|
||||
process_status: 'matched',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
pending_human_reason: null,
|
||||
match_status: 'fulfillable',
|
||||
|
||||
@@ -116,7 +116,11 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
// keep existing SSE-delivered ui_state if present
|
||||
}
|
||||
}
|
||||
const apiCheckpoint = apiState?.checkpoint ? String(apiState.checkpoint) : null;
|
||||
const apiCheckpoint = String(
|
||||
apiState?.checkpoint?.code
|
||||
|| apiState?.checkpoint_code
|
||||
|| '',
|
||||
).trim() || null;
|
||||
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
|
||||
msgs.forEach((rawMsg) => {
|
||||
const m = rawMsg as ChatMessage;
|
||||
@@ -140,20 +144,36 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
let cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
if (index === targetAssistantIndex && apiState) {
|
||||
chatMsg.shipping_ui_state = apiState;
|
||||
if (apiState.action_buttons?.length) {
|
||||
cleanedText = stripShippingActionListByButtons(cleanedText, apiState.action_buttons);
|
||||
const projectedActions = [apiState.actions?.primary, ...(apiState.actions?.secondary || [])]
|
||||
.filter(Boolean)
|
||||
.map((action) => ({
|
||||
id: String(action?.code || ''),
|
||||
label: String(action?.label || ''),
|
||||
message: String(action?.disabled_reason || ''),
|
||||
variant: action?.kind === 'terminate' ? 'danger' : 'primary',
|
||||
}));
|
||||
if (projectedActions.length) {
|
||||
cleanedText = stripShippingActionListByButtons(cleanedText, projectedActions);
|
||||
}
|
||||
} else if (!apiResolved && chatMsg.shipping_ui_state?.action_buttons?.length) {
|
||||
} else if (!apiResolved && chatMsg.shipping_ui_state?.actions) {
|
||||
const projectedActions = [chatMsg.shipping_ui_state.actions.primary, ...(chatMsg.shipping_ui_state.actions.secondary || [])]
|
||||
.filter(Boolean)
|
||||
.map((action) => ({
|
||||
id: String(action?.code || ''),
|
||||
label: String(action?.label || ''),
|
||||
message: String(action?.disabled_reason || ''),
|
||||
variant: action?.kind === 'terminate' ? 'danger' : 'primary',
|
||||
}));
|
||||
cleanedText = stripShippingActionListByButtons(
|
||||
cleanedText,
|
||||
chatMsg.shipping_ui_state.action_buttons,
|
||||
projectedActions,
|
||||
);
|
||||
}
|
||||
if (cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = cleanedText;
|
||||
}
|
||||
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
|
||||
(chatMsg.payload as { action_buttons?: unknown[] }).action_buttons = [];
|
||||
delete (chatMsg.payload as { action_buttons?: unknown[] }).action_buttons;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
|
||||
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
@@ -232,7 +233,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
return false;
|
||||
}
|
||||
const query = ctx.input.value.trim();
|
||||
const ok = await ctx.startOrderExtractionRun(query, intakeNos, []);
|
||||
// 已解析的通知附件仍要固化到用户消息;此前传空数组会使发送后对话区丢失附件卡片。
|
||||
const attachmentSnapshots = createChatMessageAttachmentSnapshots(
|
||||
ctx.attachments.value.filter((attachment) => attachment.kind === 'shipping_notice'),
|
||||
);
|
||||
const ok = await ctx.startOrderExtractionRun(query, intakeNos, attachmentSnapshots);
|
||||
if (ok) {
|
||||
ctx.clearConsumedNoticeAttachments?.();
|
||||
void ctx.refreshShippingActions();
|
||||
|
||||
@@ -136,7 +136,7 @@ function mapServerDuplicate(remote: ShippingNoticeIntakeResponse): {
|
||||
fingerprintStrength: dup.fingerprint_strength,
|
||||
matches: (dup.matches || []).map((item) => ({
|
||||
taskNo: item.task_no,
|
||||
processStatus: item.process_status,
|
||||
processStatus: item.lifecycle || 'active',
|
||||
documentVersion: Number(item.document_version || 1),
|
||||
matchType: item.match_type,
|
||||
matchedFields: listSafe(item.matched_fields),
|
||||
@@ -170,7 +170,7 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
|
||||
fingerprintStrength: remote.duplicate.fingerprint_strength,
|
||||
matches: (remote.duplicate.matches || []).map((item) => ({
|
||||
taskNo: item.task_no,
|
||||
processStatus: item.process_status,
|
||||
processStatus: item.lifecycle || 'active',
|
||||
documentVersion: Number(item.document_version || 1),
|
||||
matchType: item.match_type,
|
||||
matchedFields: listSafe(item.matched_fields),
|
||||
@@ -198,7 +198,6 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
|
||||
candidateStatus: remote.candidate_status || 'provisional',
|
||||
acceptanceMode: remote.acceptance_mode || undefined,
|
||||
extractionSource: remote.extraction_source || undefined,
|
||||
actionButtons: Array.isArray(remote.action_buttons) ? remote.action_buttons : [],
|
||||
selected: Boolean(remote.selected),
|
||||
conflicts: remote.conflicts || [],
|
||||
missingFields: Array.isArray(remote.missing_fields) ? remote.missing_fields.map((item) => String(item)) : [],
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { nextTick, ref } from 'vue';
|
||||
import {
|
||||
resolveProcessingPollIntervalMs,
|
||||
resolveProcessingPollBackoffMs,
|
||||
shouldContinueProcessingPolling,
|
||||
useShippingNoticeWorkflow,
|
||||
@@ -31,6 +32,12 @@ vi.mock('../api/shipping.api', () => ({
|
||||
* 构造历史会话右侧任务投影。
|
||||
*/
|
||||
function buildProcessing(conversationId = 'conv-1'): ConversationProcessingProjection {
|
||||
const needsAction = {
|
||||
user_task_no: `OT-${conversationId}`,
|
||||
group: 'needs_action' as const,
|
||||
can_append: false,
|
||||
file_count: 2,
|
||||
};
|
||||
return {
|
||||
conversation_id: conversationId,
|
||||
summary: {
|
||||
@@ -42,14 +49,12 @@ function buildProcessing(conversationId = 'conv-1'): ConversationProcessingProje
|
||||
history: 0,
|
||||
},
|
||||
processing: [],
|
||||
needs_action: [{
|
||||
user_task_no: `OT-${conversationId}`,
|
||||
group: 'needs_action',
|
||||
can_append: false,
|
||||
file_count: 2,
|
||||
}],
|
||||
needs_action: [needsAction],
|
||||
completed: [],
|
||||
history: [],
|
||||
status_groups: {
|
||||
failed: [], waiting_human: [needsAction], processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -111,11 +116,19 @@ function deferred<T>() {
|
||||
}
|
||||
|
||||
describe('useShippingNoticeWorkflow helpers', () => {
|
||||
it('caps failure backoff at 8s', () => {
|
||||
expect(resolveProcessingPollBackoffMs(1)).toBe(2000);
|
||||
expect(resolveProcessingPollBackoffMs(2)).toBe(4000);
|
||||
expect(resolveProcessingPollBackoffMs(3)).toBe(8000);
|
||||
expect(resolveProcessingPollBackoffMs(10)).toBe(8000);
|
||||
it('uses the specified 10s, 20s, 30s failure backoff', () => {
|
||||
expect(resolveProcessingPollBackoffMs(1)).toBe(10000);
|
||||
expect(resolveProcessingPollBackoffMs(2)).toBe(20000);
|
||||
expect(resolveProcessingPollBackoffMs(3)).toBe(30000);
|
||||
expect(resolveProcessingPollBackoffMs(10)).toBe(30000);
|
||||
});
|
||||
|
||||
it('tiers active polling by elapsed time and page visibility', () => {
|
||||
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(2000);
|
||||
expect(resolveProcessingPollIntervalMs({ elapsedMs: 15000, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(5000);
|
||||
expect(resolveProcessingPollIntervalMs({ elapsedMs: 60000, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(10000);
|
||||
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'hidden', hasProcessing: true, failureCount: 0 })).toBe(30000);
|
||||
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'visible', hasProcessing: false, failureCount: 0 })).toBeNull();
|
||||
});
|
||||
|
||||
it('stops when processing idle', () => {
|
||||
@@ -269,7 +282,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
work_items: [{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'email',
|
||||
sourceType: 'eml',
|
||||
conversationId: 'conv-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
@@ -418,7 +431,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await nextTick();
|
||||
expect(ctl.error.value).toBe('network_recoverable');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await vi.advanceTimersByTimeAsync(10000);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
@@ -450,4 +463,62 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
expect(ctl.processing.value?.conversation_id).toBe('conv-new');
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('immediately restores a cached conversation projection while it revalidates', async () => {
|
||||
const revalidate = deferred<ReturnType<typeof buildUnifiedProcessing>>();
|
||||
api.getShippingProcessing
|
||||
.mockResolvedValueOnce(buildUnifiedProcessing('conv-a'))
|
||||
.mockResolvedValueOnce(buildUnifiedProcessing('conv-b'))
|
||||
.mockImplementationOnce(() => revalidate.promise);
|
||||
const conversationId = ref('conv-a');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
conversationId.value = 'conv-b';
|
||||
await nextTick();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
conversationId.value = 'conv-a';
|
||||
await nextTick();
|
||||
|
||||
// 已访问会话首帧使用本会话最后成功 Projection,不会退回骨架或 B 的数据。
|
||||
expect(ctl.processing.value?.conversation_id).toBe('conv-a');
|
||||
expect(ctl.initialLoading.value).toBe(false);
|
||||
expect(ctl.isRefreshing.value).toBe(true);
|
||||
revalidate.resolve(buildUnifiedProcessing('conv-a'));
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('drops a response whose server conversation id differs from the request target', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing('wrong-conversation'));
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-a') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('marks the restored conversation as initial loading after aborting an old poll', async () => {
|
||||
const oldPoll = deferred<ReturnType<typeof buildUnifiedProcessing>>();
|
||||
const newInitial = deferred<ReturnType<typeof buildUnifiedProcessing>>();
|
||||
api.getShippingProcessing
|
||||
.mockImplementationOnce(() => oldPoll.promise)
|
||||
.mockImplementationOnce(() => newInitial.promise);
|
||||
|
||||
const conversationId = ref('conv-old');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
conversationId.value = 'conv-new';
|
||||
await nextTick();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(ctl.initialLoading.value).toBe(true);
|
||||
expect(ctl.manualRefreshing.value).toBe(false);
|
||||
expect(ctl.polling.value).toBe(false);
|
||||
|
||||
newInitial.resolve(buildUnifiedProcessing('conv-new'));
|
||||
await Promise.resolve();
|
||||
ctl.stop();
|
||||
});
|
||||
});
|
||||
@@ -36,10 +36,30 @@ import {
|
||||
resolveConversationProcessingFromUnified,
|
||||
} from './conversationProcessingProjection';
|
||||
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
const FIRST_ACTIVE_POLL_MS = 2000;
|
||||
const MID_ACTIVE_POLL_MS = 5000;
|
||||
const LONG_ACTIVE_POLL_MS = 10000;
|
||||
const BACKGROUND_POLL_MS = 30000;
|
||||
const REQUEST_TIMEOUT_MS = 10000;
|
||||
const MAX_BACKOFF_MS = 8000;
|
||||
const MAX_BACKOFF_MS = 30000;
|
||||
const SNAPSHOT_CACHE_LIMIT = 20;
|
||||
|
||||
type ProjectionSnapshot = {
|
||||
conversationId: string;
|
||||
processing: ConversationProcessingProjection;
|
||||
workItems: ShippingProcessingProjection[];
|
||||
semanticKey: string;
|
||||
receivedAt: number;
|
||||
lastAccessedAt: number;
|
||||
processingStartedAt: number | null;
|
||||
};
|
||||
|
||||
export type ProcessingPollContext = {
|
||||
elapsedMs: number;
|
||||
visibility: DocumentVisibilityState | 'visible' | 'hidden';
|
||||
hasProcessing: boolean;
|
||||
failureCount: number;
|
||||
};
|
||||
|
||||
export type UseShippingNoticeWorkflowOptions = {
|
||||
/** 当前会话 ID;空则停轮询并清空。 */
|
||||
@@ -61,6 +81,12 @@ export type UseShippingNoticeWorkflowReturn = {
|
||||
manualRefreshing: Ref<boolean>;
|
||||
/** 后台静默轮询中(不显示 loading,不禁用按钮)。 */
|
||||
polling: Ref<boolean>;
|
||||
/** 当前会话任意 Projection GET 在途;不得作为整卡遮罩条件。 */
|
||||
isFetching: Ref<boolean>;
|
||||
/** 当前会话已有成功 Projection 时的刷新状态。 */
|
||||
isRefreshing: Ref<boolean>;
|
||||
/** 当前会话最后一次成功 Projection 接收时间。 */
|
||||
snapshotUpdatedAt: Ref<number | null>;
|
||||
error: Ref<string | null>;
|
||||
refresh: () => Promise<void>;
|
||||
focusConversationTask: (taskNo: string) => Promise<void>;
|
||||
@@ -84,26 +110,22 @@ function readOption<T>(source: MaybeRefOrGetter<T>): T {
|
||||
* 按页面可见性 + 业务状态选择轮询间隔。
|
||||
* 分层策略:系统处理中 2s;待人工复核 30s;后台标签页 8s(若仍需轮询)。
|
||||
*/
|
||||
function resolvePollMs(
|
||||
processing?: ConversationProcessingProjection | null,
|
||||
): number {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
||||
return BACKGROUND_POLL_MS;
|
||||
}
|
||||
const processingCount = Number(
|
||||
processing?.summary?.processing || processing?.processing?.length || 0,
|
||||
);
|
||||
if (processingCount > 0) return FOREGROUND_POLL_MS;
|
||||
return FOREGROUND_POLL_MS;
|
||||
export function resolveProcessingPollIntervalMs(context: ProcessingPollContext): number | null {
|
||||
if (!context.hasProcessing) return null;
|
||||
if (context.failureCount > 0) return resolveProcessingPollBackoffMs(context.failureCount);
|
||||
if (context.visibility === 'hidden') return BACKGROUND_POLL_MS;
|
||||
if (context.elapsedMs < 15000) return FIRST_ACTIVE_POLL_MS;
|
||||
if (context.elapsedMs < 60000) return MID_ACTIVE_POLL_MS;
|
||||
return LONG_ACTIVE_POLL_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败退避:2s → 4s → 8s(封顶)。
|
||||
* 失败退避:10s → 20s → 30s(封顶)。
|
||||
* @param failureCount - 连续失败次数(≥1)
|
||||
*/
|
||||
export function resolveProcessingPollBackoffMs(failureCount: number): number {
|
||||
const n = Math.max(1, Math.floor(failureCount));
|
||||
return Math.min(FOREGROUND_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS);
|
||||
return Math.min(LONG_ACTIVE_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -136,20 +158,84 @@ export function useShippingNoticeWorkflow(
|
||||
const manualRefreshing = ref(false);
|
||||
const polling = ref(false);
|
||||
const error = ref<string | null>(null);
|
||||
const snapshotUpdatedAt = ref<number | null>(null);
|
||||
const isFetching = ref(false);
|
||||
const snapshots = new Map<string, ProjectionSnapshot>();
|
||||
const loading = computed(() => (
|
||||
initialLoading.value || manualRefreshing.value || polling.value
|
||||
));
|
||||
const isRefreshing = computed(() => isFetching.value && processing.value !== null);
|
||||
|
||||
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollGeneration = 0;
|
||||
let requestController: AbortController | null = null;
|
||||
let requestGeneration = 0;
|
||||
const requestGenerations = new Map<string, number>();
|
||||
let inFlightRefresh: { conversationId: string; promise: Promise<void> } | null = null;
|
||||
let failureCount = 0;
|
||||
let pollingStopped = false;
|
||||
let lastSemanticKey = '';
|
||||
const intakeOtStabilizer = createIntakeOtStabilizer();
|
||||
|
||||
function touchSnapshot(snapshot: ProjectionSnapshot): ProjectionSnapshot {
|
||||
snapshot.lastAccessedAt = Date.now();
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
function readSnapshot(conversationId: string): ProjectionSnapshot | null {
|
||||
const snapshot = snapshots.get(conversationId);
|
||||
return snapshot ? touchSnapshot(snapshot) : null;
|
||||
}
|
||||
|
||||
function pruneSnapshots(): void {
|
||||
while (snapshots.size > SNAPSHOT_CACHE_LIMIT) {
|
||||
const oldest = [...snapshots.values()]
|
||||
.sort((left, right) => left.lastAccessedAt - right.lastAccessedAt)[0];
|
||||
if (!oldest) return;
|
||||
snapshots.delete(oldest.conversationId);
|
||||
}
|
||||
}
|
||||
|
||||
function workItemsSemanticKey(items: ShippingProcessingProjection[]): string {
|
||||
return JSON.stringify(items.map((item) => ({
|
||||
no: item.workItemNo,
|
||||
type: item.workItemType,
|
||||
status: item.uiState?.status ?? item.userStatus ?? item.status,
|
||||
stage: item.uiState?.stage ?? item.userStage ?? item.stage,
|
||||
gate: item.uiState?.blocking_reason?.code ?? item.blockingReason?.code ?? null,
|
||||
action: item.uiState?.primary_action?.code ?? item.primaryAction?.code ?? null,
|
||||
version: item.progressVersion,
|
||||
files: (item.aggregateChildren || []).map((child) => ({
|
||||
no: child.workItemNo,
|
||||
status: child.uiState?.status ?? child.userStatus ?? child.status,
|
||||
stage: child.uiState?.stage ?? child.userStage ?? child.stage,
|
||||
file: child.sourceSummary?.filename ?? null,
|
||||
})),
|
||||
})));
|
||||
}
|
||||
|
||||
function applySnapshot(snapshot: ProjectionSnapshot | null): void {
|
||||
processing.value = snapshot?.processing ?? null;
|
||||
processingWorkItems.value = snapshot?.workItems ?? [];
|
||||
snapshotUpdatedAt.value = snapshot?.receivedAt ?? null;
|
||||
}
|
||||
|
||||
function currentPollElapsedMs(): number {
|
||||
const snapshot = readSnapshot(normalizedConversationId.value);
|
||||
return snapshot?.processingStartedAt === null || snapshot?.processingStartedAt === undefined
|
||||
? 0
|
||||
: Math.max(0, Date.now() - snapshot.processingStartedAt);
|
||||
}
|
||||
|
||||
function resolveCurrentPollInterval(): number | null {
|
||||
return resolveProcessingPollIntervalMs({
|
||||
elapsedMs: currentPollElapsedMs(),
|
||||
visibility: typeof document === 'undefined' ? 'visible' : document.visibilityState,
|
||||
hasProcessing: shouldContinueProcessingPolling(processing.value),
|
||||
failureCount,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 Intake→OT 过渡窗里,若 projection 被稳定器保留为上一轮 OT 视图,
|
||||
* 则 work_items 也必须同步保留上一轮 order_task;否则卡片正文与侧边进度条
|
||||
@@ -183,6 +269,12 @@ export function useShippingNoticeWorkflow(
|
||||
pollTimer = null;
|
||||
requestController?.abort();
|
||||
requestController = null;
|
||||
// 请求属于上一会话代际时 finally 会因 generation 不匹配而跳过清理;
|
||||
// 必须在此同步清空,才能让新会话首个 GET 固定进入 initialLoading。
|
||||
initialLoading.value = false;
|
||||
manualRefreshing.value = false;
|
||||
polling.value = false;
|
||||
isFetching.value = false;
|
||||
requestGeneration += 1;
|
||||
pollGeneration += 1;
|
||||
}
|
||||
@@ -214,22 +306,31 @@ export function useShippingNoticeWorkflow(
|
||||
mode: 'initial' | 'manual' | 'poll',
|
||||
): Promise<void> {
|
||||
const generation = ++requestGeneration;
|
||||
if (mode === 'initial') initialLoading.value = true;
|
||||
requestGenerations.set(conversationId, generation);
|
||||
const existingSnapshot = readSnapshot(conversationId);
|
||||
if (mode === 'initial' && !existingSnapshot) initialLoading.value = true;
|
||||
else if (mode === 'manual') manualRefreshing.value = true;
|
||||
else polling.value = true;
|
||||
isFetching.value = true;
|
||||
const controller = createRequestController();
|
||||
try {
|
||||
// [STEP 1] 统一投影为唯一读源。
|
||||
const unified = await getWorkspaceShippingProcessing(conversationId, controller.signal);
|
||||
if (
|
||||
controller.signal.aborted
|
||||
|| generation !== requestGeneration
|
||||
|| requestGenerations.get(conversationId) !== generation
|
||||
|| conversationId !== normalizedConversationId.value
|
||||
|| String(unified?.conversation_id || '').trim() !== conversationId
|
||||
) return;
|
||||
|
||||
const workItems = Array.isArray(unified?.work_items) ? unified.work_items : [];
|
||||
// 记录该会话已见过 OT,供下一轮 Intake 稀疏响应在稳定窗口内保留上一投影。
|
||||
if (workItems.some((item) => item.workItemType === 'order_task')) {
|
||||
intakeOtStabilizer.markSeen(conversationId);
|
||||
}
|
||||
const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined;
|
||||
const prevProjection = processing.value;
|
||||
const previousSnapshot = readSnapshot(conversationId);
|
||||
const prevProjection = previousSnapshot?.processing ?? null;
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems,
|
||||
embedded,
|
||||
@@ -241,23 +342,55 @@ export function useShippingNoticeWorkflow(
|
||||
reset: (cId) => intakeOtStabilizer.reset(cId),
|
||||
},
|
||||
);
|
||||
const nextSemanticKey = buildProcessingSemanticKey(nextProjection);
|
||||
|
||||
processingWorkItems.value = resolveStableWorkItems(
|
||||
if (!nextProjection) {
|
||||
// 空投影同样是本次后端裁决,但不作为“成功 Projection”缓存;
|
||||
// 保留已有 Snapshot 可避免短暂稀疏响应把业务卡卸载。
|
||||
if (!previousSnapshot) applySnapshot(null);
|
||||
error.value = null;
|
||||
failureCount = 0;
|
||||
return;
|
||||
}
|
||||
const nextSemanticKey = `${buildProcessingSemanticKey(nextProjection)}:${workItemsSemanticKey(workItems)}`;
|
||||
const nextWorkItems = resolveStableWorkItems(
|
||||
workItems,
|
||||
prevProjection,
|
||||
nextProjection,
|
||||
);
|
||||
if (nextSemanticKey !== lastSemanticKey) {
|
||||
processing.value = nextProjection;
|
||||
// Intake→OT 的短暂稀疏响应由稳定器明确裁决为上一版 Projection;
|
||||
// 此时 work_items 也必须维持同一 Snapshot,不能因原始项差异替换。
|
||||
const keepPreviousSnapshot = Boolean(
|
||||
previousSnapshot
|
||||
&& !workItems.some((item) => item.workItemType === 'order_task')
|
||||
&& intakeOtStabilizer.hasSeenOrderTaskBefore(conversationId),
|
||||
);
|
||||
if (!previousSnapshot || (!keepPreviousSnapshot && nextSemanticKey !== previousSnapshot.semanticKey)) {
|
||||
const now = Date.now();
|
||||
const processingStartedAt = shouldContinueProcessingPolling(nextProjection)
|
||||
? (previousSnapshot?.processingStartedAt ?? now)
|
||||
: null;
|
||||
const snapshot: ProjectionSnapshot = {
|
||||
conversationId,
|
||||
processing: nextProjection,
|
||||
workItems: nextWorkItems,
|
||||
semanticKey: nextSemanticKey,
|
||||
receivedAt: now,
|
||||
lastAccessedAt: now,
|
||||
processingStartedAt,
|
||||
};
|
||||
snapshots.set(conversationId, snapshot);
|
||||
pruneSnapshots();
|
||||
applySnapshot(snapshot);
|
||||
lastSemanticKey = nextSemanticKey;
|
||||
} else {
|
||||
touchSnapshot(previousSnapshot);
|
||||
applySnapshot(previousSnapshot);
|
||||
}
|
||||
error.value = null;
|
||||
failureCount = 0;
|
||||
} catch (reason) {
|
||||
if (
|
||||
controller.signal.aborted
|
||||
|| generation !== requestGeneration
|
||||
|| requestGenerations.get(conversationId) !== generation
|
||||
|| conversationId !== normalizedConversationId.value
|
||||
) return;
|
||||
failureCount += 1;
|
||||
@@ -266,10 +399,14 @@ export function useShippingNoticeWorkflow(
|
||||
: 'network_recoverable';
|
||||
} finally {
|
||||
if (requestController === controller) requestController = null;
|
||||
if (generation === requestGeneration) {
|
||||
if (
|
||||
requestGenerations.get(conversationId) === generation
|
||||
&& requestGeneration === generation
|
||||
) {
|
||||
if (mode === 'initial') initialLoading.value = false;
|
||||
else if (mode === 'manual') manualRefreshing.value = false;
|
||||
else polling.value = false;
|
||||
isFetching.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -281,8 +418,7 @@ export function useShippingNoticeWorkflow(
|
||||
function refresh(): Promise<void> {
|
||||
const conversationId = normalizedConversationId.value;
|
||||
if (!conversationId) {
|
||||
processing.value = null;
|
||||
processingWorkItems.value = [];
|
||||
applySnapshot(null);
|
||||
error.value = null;
|
||||
lastSemanticKey = '';
|
||||
return Promise.resolve();
|
||||
@@ -291,7 +427,7 @@ export function useShippingNoticeWorkflow(
|
||||
if (inFlightRefresh?.conversationId === conversationId) {
|
||||
return inFlightRefresh.promise;
|
||||
}
|
||||
const isFirstLoad = processing.value === null && !initialLoading.value && !manualRefreshing.value && !polling.value;
|
||||
const isFirstLoad = !readSnapshot(conversationId) && !initialLoading.value && !manualRefreshing.value && !polling.value;
|
||||
const mode: 'initial' | 'manual' = isFirstLoad ? 'initial' : 'manual';
|
||||
const promise = executeRefresh(conversationId, mode).finally(() => {
|
||||
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
|
||||
@@ -400,10 +536,8 @@ export function useShippingNoticeWorkflow(
|
||||
if (!shouldContinueProcessingPolling(processing.value)) {
|
||||
return;
|
||||
}
|
||||
const nextDelay = failureCount > 0
|
||||
? resolveProcessingPollBackoffMs(failureCount)
|
||||
: resolvePollMs(processing.value);
|
||||
schedulePoll(generation, nextDelay);
|
||||
const nextDelay = resolveCurrentPollInterval();
|
||||
if (nextDelay !== null) schedulePoll(generation, nextDelay);
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
@@ -426,7 +560,8 @@ export function useShippingNoticeWorkflow(
|
||||
return;
|
||||
}
|
||||
if (!shouldContinueProcessingPolling(processing.value)) return;
|
||||
schedulePoll(generation, resolvePollMs(processing.value));
|
||||
const nextDelay = resolveCurrentPollInterval();
|
||||
if (nextDelay !== null) schedulePoll(generation, nextDelay);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -438,10 +573,9 @@ export function useShippingNoticeWorkflow(
|
||||
|
||||
watch(normalizedConversationId, (nextConversationId, previousConversationId) => {
|
||||
if (nextConversationId !== previousConversationId) {
|
||||
processing.value = null;
|
||||
processingWorkItems.value = [];
|
||||
applySnapshot(readSnapshot(nextConversationId));
|
||||
error.value = null;
|
||||
lastSemanticKey = '';
|
||||
lastSemanticKey = readSnapshot(nextConversationId)?.semanticKey || '';
|
||||
}
|
||||
restartPolling();
|
||||
}, { immediate: true });
|
||||
@@ -477,6 +611,9 @@ export function useShippingNoticeWorkflow(
|
||||
initialLoading,
|
||||
manualRefreshing,
|
||||
polling,
|
||||
isFetching,
|
||||
isRefreshing,
|
||||
snapshotUpdatedAt,
|
||||
error,
|
||||
refresh,
|
||||
focusConversationTask,
|
||||
|
||||
@@ -341,6 +341,13 @@ export interface ShippingProcessingProjection {
|
||||
retryable?: boolean;
|
||||
/** 唯一主入口按钮建议:{code, i18nKey, parameters};前端只渲染不新建动作码。 */
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
/**
|
||||
* 单项后端展示裁决;存在时状态、阶段、原因和动作必须只消费此对象。
|
||||
* primaryAction / availableActions 仅保留给尚未升级该契约的旧服务端响应。
|
||||
*/
|
||||
uiState?: ConversationProcessingUiState;
|
||||
/** 文件关联的正式 Gate 用户摘要;仅用于执行后端已裁决的 primary_action。 */
|
||||
processGate?: ShippingProcessGateUserSummary | null;
|
||||
/** 子状态事实字典(inventorySourceStatus / candidateSourceCodes / preparedSourceCodes / pendingSourceCodes / lineResolutions / exportState / uploadState / switchState)。 */
|
||||
facts?: ShippingProcessingFacts;
|
||||
/** EML Intake 的用户可见全局分组;由后端按子附件最高关注级别裁决。 */
|
||||
@@ -604,6 +611,8 @@ export interface ConversationProcessingUserTask {
|
||||
} | null;
|
||||
/** EML 聚合内的真实邮件/附件子项;仅用于展开明细展示。 */
|
||||
aggregateChildren?: ShippingProcessingProjection[];
|
||||
/** 后端已裁决的节点级用户态;状态、原因及按钮均以此为准。 */
|
||||
uiState?: ConversationProcessingUiState;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -613,6 +622,10 @@ export interface ConversationProcessingSummary {
|
||||
total_tasks: number;
|
||||
/** 当前会话正式任务覆盖的文件总数(含处理记录,不含 order_intake) */
|
||||
total_files?: number;
|
||||
failed_files?: number;
|
||||
waiting_human_files?: number;
|
||||
processing_files?: number;
|
||||
completed_files?: number;
|
||||
processing: number;
|
||||
needs_action: number;
|
||||
/** 识别完成且尚未查看的成功通知数 */
|
||||
@@ -655,6 +668,31 @@ export interface ConversationProcessingProjection {
|
||||
cancelled: ConversationProcessingUserTask[];
|
||||
archived: ConversationProcessingUserTask[];
|
||||
};
|
||||
/** 会话批次主进度;后端已将技术阶段折叠为四个业务节点。 */
|
||||
four_stage_nodes?: Array<{
|
||||
code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
label_key: string;
|
||||
status: 'passed' | 'running' | 'blocked' | 'pending';
|
||||
}>;
|
||||
/** 批次级用户态:状态、问题与可操作动作必须来自同一次后端裁决。 */
|
||||
ui_state?: ConversationProcessingUiState;
|
||||
/** 本次已准备的正式产出物;下载资格由后端 action 决定。 */
|
||||
output_artifacts?: Array<{
|
||||
order_task_no: string;
|
||||
filename: string;
|
||||
type: string;
|
||||
status: 'ready';
|
||||
action: { code: 'download_excel'; enabled: boolean };
|
||||
}>;
|
||||
}
|
||||
|
||||
/** 批次/EML/文件节点共用的用户展示状态,前端不得由 status 或 Gate 重新裁决。 */
|
||||
export interface ConversationProcessingUiState {
|
||||
status: ShippingUserProcessingStatus;
|
||||
stage: string;
|
||||
blocking_reason: ShippingProcessingBlockingReason | null;
|
||||
primary_action: ShippingProcessingPrimaryAction | null;
|
||||
secondary_actions: Array<{ code: string; enabled: boolean }>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -761,7 +799,6 @@ export interface ShippingTaskSummary {
|
||||
customer_short_code_snapshot?: string | null;
|
||||
po_number?: string | null;
|
||||
current_step?: string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
match_status?: string | null;
|
||||
upload_status?: string | null;
|
||||
@@ -996,7 +1033,8 @@ export type ShippingProcessGateActionCode =
|
||||
| 'regenerate_excel_artifact'
|
||||
| 'poll_freight_upload_rpa'
|
||||
| 'retry_freight_upload_rpa'
|
||||
| 'regenerate_manual_upload_todo';
|
||||
| 'regenerate_manual_upload_todo'
|
||||
| 'mark_manual_uploaded';
|
||||
|
||||
/** 门禁责任方(与 PROCESS_GATE_RESPONSIBLE_PARTIES 对齐)。 */
|
||||
export type ShippingProcessGateResponsibleParty =
|
||||
@@ -1059,6 +1097,9 @@ export type ShippingProcessGateImplementationStatus =
|
||||
export interface ShippingProcessGateUserSummary {
|
||||
execution_no: string;
|
||||
status: string;
|
||||
current_gate_code?: string | null;
|
||||
gate_status?: string | null;
|
||||
expected_gate_version?: number | null;
|
||||
current_blocking_gate?: ShippingProcessGateProjection | null;
|
||||
blocking_reason_code?: string | null;
|
||||
blocking_message?: string | null;
|
||||
@@ -1340,12 +1381,48 @@ export interface ShippingProgressNode {
|
||||
status: WorkflowNodeStatus | string;
|
||||
}
|
||||
|
||||
export type ShippingBusinessStage =
|
||||
| 'intake_parse'
|
||||
| 'order_review'
|
||||
| 'fulfillment_prep'
|
||||
| 'upload_complete';
|
||||
|
||||
export type ShippingActionKind = 'forward' | 'recovery' | 'view' | 'terminate';
|
||||
|
||||
export interface ShippingTaskUiState {
|
||||
task_no: string;
|
||||
batch_no?: string | null;
|
||||
checkpoint?: string | null;
|
||||
stage?: {
|
||||
code: ShippingBusinessStage | string;
|
||||
label: string;
|
||||
index: number;
|
||||
total: number;
|
||||
} | null;
|
||||
checkpoint?: {
|
||||
code?: string | null;
|
||||
kind?: string | null;
|
||||
label?: string | null;
|
||||
} | null;
|
||||
checkpoint_view?: {
|
||||
code?: string | null;
|
||||
kind?: string | null;
|
||||
label?: string | null;
|
||||
} | null;
|
||||
checkpoint_code?: string | null;
|
||||
todo?: {
|
||||
title?: string | null;
|
||||
message?: string | null;
|
||||
} | null;
|
||||
actions?: {
|
||||
primary?: ShippingUnifiedAction | null;
|
||||
secondary?: ShippingUnifiedAction[];
|
||||
};
|
||||
reason?: {
|
||||
code?: string | null;
|
||||
message?: string | null;
|
||||
} | null;
|
||||
lifecycle_status?: 'active' | 'voided' | 'archived' | string | null;
|
||||
checkpoint_kind?: 'auto_continue' | 'must_human' | 'wait_manual_upload' | 'complete' | string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
pending_human_reason?: string | null;
|
||||
match_status?: string | null;
|
||||
@@ -1373,15 +1450,25 @@ export interface ShippingTaskUiState {
|
||||
* 前端只渲染 status,禁止自行计算进度百分比。
|
||||
*/
|
||||
progress_nodes?: ShippingProgressNode[] | null;
|
||||
/** 统一 Gate 用户摘要(优先于 legacy action_buttons) */
|
||||
/** 统一 Gate 用户摘要(后端统一动作投影的诊断信息) */
|
||||
process_gate?: ShippingProcessGateUserSummary | null;
|
||||
};
|
||||
action_buttons: ShippingChatAction[];
|
||||
/** 顶层 Gate 摘要;与 summary.process_gate 同源 */
|
||||
process_gate?: ShippingProcessGateUserSummary | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingUnifiedAction {
|
||||
code: string;
|
||||
label?: string | null;
|
||||
kind: ShippingActionKind | string;
|
||||
enabled: boolean;
|
||||
requires_confirmation: boolean;
|
||||
target_surface?: string | null;
|
||||
disabled_reason?: string | null;
|
||||
expected_gate_version?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `shipping_ui_state` SSE 与历史回放共用的恢复契约。
|
||||
* 核心逻辑:任务锚点 `task_no` 是 open_existing 场景恢复聊天工作台的最小必需字段;
|
||||
@@ -2342,7 +2429,6 @@ export interface ShippingOrderReviewCase {
|
||||
label_key?: string | null;
|
||||
source?: string | null;
|
||||
inconsistent?: boolean;
|
||||
process_status?: string | null;
|
||||
current_step?: string | null;
|
||||
stage_node?: Record<string, unknown> | null;
|
||||
} | null;
|
||||
@@ -2376,7 +2462,6 @@ export interface ShippingOrderReviewCase {
|
||||
needs_retry?: boolean;
|
||||
status?: string | null;
|
||||
message?: string | null;
|
||||
task_process_status?: string | null;
|
||||
} | null;
|
||||
/** 用户可见自动建单/推进态;waiting_to_start ≠ running。 */
|
||||
automation?: ShippingOrderReviewAutomation | null;
|
||||
@@ -2515,6 +2600,9 @@ export interface ShippingOrderReviewEvidence {
|
||||
field_id: string;
|
||||
line_index?: number | null;
|
||||
machine_value?: unknown;
|
||||
document_id?: number | null;
|
||||
document_type?: string | null;
|
||||
source_type?: string | null;
|
||||
quote?: string | null;
|
||||
page_no?: number | null;
|
||||
table_id?: string | null;
|
||||
@@ -2635,7 +2723,6 @@ export interface ShippingNoticeCandidateResponse {
|
||||
candidate_status?: 'provisional' | 'accepted' | 'rejected' | 'expired';
|
||||
acceptance_mode?: 'automatic' | 'manual' | 'legacy' | null;
|
||||
extraction_source?: string | null;
|
||||
action_buttons?: string[];
|
||||
selected: boolean;
|
||||
conflicts?: Array<Record<string, unknown>>;
|
||||
missing_fields?: string[];
|
||||
@@ -2670,7 +2757,6 @@ export type ShippingDuplicateFingerprintStrength = 'strong' | 'medium' | 'weak'
|
||||
|
||||
export interface ShippingDuplicateMatch {
|
||||
task_no: string;
|
||||
process_status: string;
|
||||
document_version: number;
|
||||
match_type: string;
|
||||
matched_fields: string[];
|
||||
|
||||
@@ -81,7 +81,6 @@ export interface ShippingNoticeCandidate {
|
||||
candidateStatus: 'provisional' | 'accepted' | 'rejected' | 'expired';
|
||||
acceptanceMode?: 'automatic' | 'manual' | 'legacy';
|
||||
extractionSource?: string;
|
||||
actionButtons: string[];
|
||||
selected: boolean;
|
||||
conflicts: Array<Record<string, unknown>>;
|
||||
missingFields?: string[];
|
||||
@@ -259,13 +258,10 @@ export interface ShippingMatchResultPayload {
|
||||
shortage_qty: number;
|
||||
line_status: 'ok' | 'partial' | 'shortage' | string;
|
||||
}>;
|
||||
action_buttons?: Array<{
|
||||
id: string;
|
||||
label: string;
|
||||
message: string;
|
||||
variant: 'primary' | 'secondary' | 'danger';
|
||||
source_code?: string;
|
||||
}>;
|
||||
actions?: {
|
||||
primary?: import('./shipping.api.types').ShippingUnifiedAction | null;
|
||||
secondary?: import('./shipping.api.types').ShippingUnifiedAction[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface ShippingActionButton {
|
||||
|
||||
@@ -693,6 +693,34 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.find('[data-testid="mock-process-gate"]').attributes('data-actions')).toBe('hidden');
|
||||
});
|
||||
|
||||
it('does not revive a Case Gate action when the formal OT ui_state explicitly has no action', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', has_formal_ot: true, task_missing: false,
|
||||
confirmed_task_id: 89, confirmed_task_no: 'SN-NO-ACTION-1',
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-NO-ACTION-1', status: 'blocked', owner_type: 'human', technical_auto_only: false,
|
||||
current_blocking_gate: { gate_code: 'customer_confirmation', status: 'blocked' },
|
||||
primary_action: { code: 'confirm_customer', label_key: 'chat.shippingNotice.processGate.actionCodes.confirm_customer' },
|
||||
},
|
||||
automation: { status: 'running', can_auto_create: false, can_build: true },
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
workItemType: 'order_task', workItemNo: 'SN-NO-ACTION-1', sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'SN-NO-ACTION-1', shippingNoticeNo: 'SN-NO-ACTION-1', conversationId: 'conv-1',
|
||||
submissionNo: 'SUB-NO-ACTION', intakeNo: 'SNI-NO-ACTION', status: 'processing', stage: 'order_creating',
|
||||
progressVersion: 1, lastActivityAt: '2026-08-14T00:00:00Z', currentGate: null, availableActions: ['confirm_customer'],
|
||||
sourceSummary: { emailSubject: null, filename: 'no-action.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
childOrderTasks: [], uiState: { status: 'processing', stage: 'order_creating', blocking_reason: null, primary_action: null, secondary_actions: [] },
|
||||
};
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
|
||||
// 正式 OT 已有后端 ui_state,Case Gate 只是诊断/建单前兼容来源,不能复活按钮。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows restored version as current and latest version only as failed attempt', async () => {
|
||||
reviewProgressContext.value = {
|
||||
item_no: 'WFI-1',
|
||||
@@ -766,7 +794,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValueOnce({
|
||||
task_no: 'SN-MOCK',
|
||||
status: 'completed',
|
||||
process_status: 'uploaded',
|
||||
upload_status: 'uploaded',
|
||||
upload_status: 'uploaded',
|
||||
lines: [],
|
||||
line_results: [{
|
||||
|
||||
@@ -140,6 +140,8 @@ const {
|
||||
focusedLineKey,
|
||||
previewUrl,
|
||||
ensurePreviewLoaded,
|
||||
ensureEmailEvidenceLoaded,
|
||||
emailPreview,
|
||||
load,
|
||||
selectCase,
|
||||
requestedCaseNo,
|
||||
@@ -374,12 +376,19 @@ const caseContentSkeleton = computed(() => caseSwitchFailed.value && !activeCase
|
||||
const showObjectRetryOnRail = computed(() => showStpRetry.value && mountCurrentProcessingCard.value);
|
||||
const showObjectRetryOnFooter = computed(() => showStpRetry.value && !mountCurrentProcessingCard.value);
|
||||
|
||||
/** 当前任务卡是复核页唯一 Gate 写入口;Gate 主动作优先于泛化自动重试。 */
|
||||
/**
|
||||
* 当前任务卡的动作来源。
|
||||
* 正式 OT 已有 processing.ui_state 时必须直接消费该后端裁决;Case Gate 只服务于
|
||||
* 尚未形成 OT 投影的建单前复核,避免同一任务在复核页和批次中心出现不同主按钮。
|
||||
*/
|
||||
const currentTaskPrimaryAction = computed(() => (
|
||||
displayCase.value?.process_gate?.primary_action
|
||||
?? shippingProcessingProjection.value?.primaryAction
|
||||
?? displayCase.value?.primary_action
|
||||
?? null
|
||||
shippingProcessingProjection.value
|
||||
? (shippingProcessingProjection.value.uiState
|
||||
? shippingProcessingProjection.value.uiState.primary_action
|
||||
: shippingProcessingProjection.value.primaryAction)
|
||||
: (displayCase.value?.process_gate?.primary_action
|
||||
?? displayCase.value?.primary_action
|
||||
?? null)
|
||||
));
|
||||
const currentTaskRetryable = computed(() => (
|
||||
showObjectRetryOnRail.value
|
||||
@@ -649,15 +658,6 @@ watch(
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** PDF 打开且 Case 切换时按需拉取预览,避免导航时预取。 */
|
||||
watch(
|
||||
() => [activeCase.value?.case_no, panelState.value.pdfOpen] as const,
|
||||
([caseNo, pdfOpen]) => {
|
||||
if (!pdfOpen || !caseNo) return;
|
||||
void ensurePreviewLoaded(caseNo);
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 当前用于 PDF 证据高亮的条目:明细同时按字段与行号匹配,避免多行同字段定位错位。
|
||||
*/
|
||||
@@ -673,6 +673,25 @@ const selectedEvidence = computed((): ShippingOrderReviewEvidence | null => {
|
||||
return items.find((item) => item.highlight_bbox || item.bbox) || items[0] || null;
|
||||
});
|
||||
|
||||
const selectedEvidenceIsEmail = computed(() => String(selectedEvidence.value?.document_type || '') === 'email_body');
|
||||
|
||||
/**
|
||||
* 证据面板打开、Case 或当前证据变化时按 Document 类型读取受控预览。
|
||||
* 邮件正文绝不回退到 Case 主 PDF,避免证据载体与弹窗内容不一致。
|
||||
*/
|
||||
watch(
|
||||
() => [activeCase.value?.case_no, panelState.value.pdfOpen, selectedEvidence.value?.document_id, selectedEvidenceIsEmail.value] as const,
|
||||
([caseNo, pdfOpen, documentId, isEmail]) => {
|
||||
if (!pdfOpen || !caseNo) return;
|
||||
if (isEmail && documentId) {
|
||||
void ensureEmailEvidenceLoaded(caseNo, Number(documentId));
|
||||
return;
|
||||
}
|
||||
emailPreview.value = null;
|
||||
void ensurePreviewLoaded(caseNo);
|
||||
},
|
||||
);
|
||||
|
||||
/** 多 evidence 优选顺序:verified > candidate > unavailable > invalid;同级优先有 highlight_bbox。 */
|
||||
const HIGHLIGHT_QUALITY_RANK: Record<string, number> = {
|
||||
verified: 0,
|
||||
@@ -911,11 +930,15 @@ const focusFieldEvidence = (fieldId: string, lineIndex?: number) => {
|
||||
// 定位证据默认浮窗;保留用户已选的 docked/expanded/side。
|
||||
scrollRestoreKey: typeof lineKey === 'string' ? `${fieldId}:${lineKey}` : normalizedFieldId,
|
||||
};
|
||||
void ensurePreviewLoaded();
|
||||
const caseNo = String(activeCase.value?.case_no || '').trim();
|
||||
if (selectedEvidenceIsEmail.value && caseNo && selectedEvidence.value?.document_id) {
|
||||
void ensureEmailEvidenceLoaded(caseNo, Number(selectedEvidence.value.document_id));
|
||||
} else {
|
||||
void ensurePreviewLoaded();
|
||||
}
|
||||
// [STEP] 所有定位点击写 locate 审计(含无 evidence);有 evidence_id 再写 focus/诊断。
|
||||
auditFieldLocateAttempt(normalizedFieldId, lineIndex, matched);
|
||||
const quality = String(matched?.highlight_quality || fieldHighlightQuality(fieldId, lineIndex));
|
||||
const caseNo = String(activeCase.value?.case_no || '').trim();
|
||||
if (caseNo && matched?.evidence_id) {
|
||||
void getWorkspaceShippingOrderReviewEvidenceItem(caseNo, matched.evidence_id)
|
||||
.catch(() => undefined);
|
||||
@@ -1532,9 +1555,16 @@ const duplicatePanelRef = ref<{ focusAdjudication: () => void } | null>(null);
|
||||
/** 系统自动推进中:仅当存在确认 Job 时隐藏主写按钮;资格达标不算 automating。 */
|
||||
const isProcessingAutomating = computed(() => {
|
||||
if (!hasConfirmedAutomationJob.value) return false;
|
||||
const status = String(shippingProcessingProjection.value?.status || '').trim().toLowerCase();
|
||||
return ['processing', 'automating', 'queued'].includes(status)
|
||||
&& !shippingProcessingProjection.value?.currentGate?.nextActionCode;
|
||||
const status = String(
|
||||
shippingProcessingProjection.value?.uiState?.status
|
||||
|| shippingProcessingProjection.value?.status
|
||||
|| '',
|
||||
).trim().toLowerCase();
|
||||
const projection = shippingProcessingProjection.value;
|
||||
const hasPrimaryAction = projection?.uiState
|
||||
? Boolean(projection.uiState.primary_action)
|
||||
: Boolean(projection?.primaryAction);
|
||||
return ['processing', 'automating', 'queued'].includes(status) && !hasPrimaryAction;
|
||||
});
|
||||
|
||||
/** OT 导航侧栏模式(≥5)时主区并排。 */
|
||||
@@ -1642,9 +1672,8 @@ const formalResultCompletedAt = computed(() => (
|
||||
|| null
|
||||
));
|
||||
const formalResultIsCompleted = computed(() => {
|
||||
const status = String(formalTaskDetail.value?.process_status || '').toLowerCase();
|
||||
return ['completed', 'uploaded', 'closed'].includes(status)
|
||||
|| String(formalTaskDetail.value?.upload_status || '').toLowerCase() === 'uploaded';
|
||||
return String(formalTaskDetail.value?.upload_status || '').toLowerCase() === 'uploaded'
|
||||
|| formalTaskDetail.value?.ui_state?.stage?.code === 'upload_complete';
|
||||
});
|
||||
|
||||
/** 直接在订单复核页打开人工上传登记,避免依赖仅在 formal_task 模式挂载的 TaskTodoPanel ref。 */
|
||||
@@ -3314,7 +3343,7 @@ watch(
|
||||
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
|
||||
:automation="displayCase?.automation"
|
||||
:show-retry="showObjectRetryOnRail"
|
||||
:user-status="shippingProcessingProjection?.userStatus ?? displayCase?.user_status"
|
||||
:user-status="shippingProcessingProjection?.uiState?.status ?? shippingProcessingProjection?.userStatus ?? displayCase?.user_status"
|
||||
:retryable="currentTaskRetryable"
|
||||
:blocking-reason="shippingProcessingProjection?.blockingReason ?? displayCase?.blocking_reason"
|
||||
:primary-action="currentTaskPrimaryAction"
|
||||
@@ -3380,6 +3409,7 @@ watch(
|
||||
:docked="true"
|
||||
:float-side="panelState.pdfFloatSide"
|
||||
:src="previewUrl"
|
||||
:email-preview="selectedEvidenceIsEmail ? emailPreview : null"
|
||||
:evidence="selectedEvidence"
|
||||
:evidence-list="evidence || []"
|
||||
:field-label="evidenceFieldLabel"
|
||||
@@ -3797,7 +3827,7 @@ watch(
|
||||
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
|
||||
:has-formal-ot="shippingProcessingProjection?.hasFormalOt ?? hasFormalOt"
|
||||
:shipping-notice-no="shippingProcessingProjection?.shippingNoticeNo ?? confirmedNoticeTaskNo"
|
||||
:user-status="shippingProcessingProjection?.userStatus ?? displayCase?.user_status"
|
||||
:user-status="shippingProcessingProjection?.uiState?.status ?? shippingProcessingProjection?.userStatus ?? displayCase?.user_status"
|
||||
:retryable="currentTaskRetryable"
|
||||
:blocking-reason="shippingProcessingProjection?.blockingReason ?? displayCase?.blocking_reason"
|
||||
:primary-action="currentTaskPrimaryAction"
|
||||
@@ -3844,6 +3874,7 @@ watch(
|
||||
:docked="false"
|
||||
:float-side="panelState.pdfFloatSide"
|
||||
:src="previewUrl"
|
||||
:email-preview="selectedEvidenceIsEmail ? emailPreview : null"
|
||||
:evidence="selectedEvidence"
|
||||
:evidence-list="evidence || []"
|
||||
:field-label="evidenceFieldLabel"
|
||||
|
||||
+24
@@ -226,4 +226,28 @@ describe('ProcessGateRecoveryCard', () => {
|
||||
expect(wrapper.emitted('manualUpload')).toHaveLength(1);
|
||||
expect(wrapper.emitted('navigate')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('opens evidence registration for the manual-upload confirmation primary action', async () => {
|
||||
const wrapper = mount(ProcessGateRecoveryCard, {
|
||||
props: {
|
||||
summary: baseSummary({
|
||||
current_blocking_gate: {
|
||||
...baseSummary().current_blocking_gate!,
|
||||
gate_code: 'manual_upload_handoff',
|
||||
next_action_code: 'mark_manual_uploaded',
|
||||
},
|
||||
next_action_code: 'mark_manual_uploaded',
|
||||
allowed_actions: ['mark_manual_uploaded'],
|
||||
task_no: 'SN-TEST-001',
|
||||
} as ShippingProcessGateUserSummary),
|
||||
canHandle: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="process-gate-recovery-primary"]').trigger('click');
|
||||
|
||||
expect(wrapper.emitted('manualUpload')).toHaveLength(1);
|
||||
expect(postActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+7
-14
@@ -4,7 +4,7 @@
|
||||
* 依赖:useShippingProcessGateRecovery、processGateNavigation、process-gates.api、
|
||||
* ShippingProcessGateUserSummary / ShippingExplainabilityReason。
|
||||
* 逻辑:仅 owner_type=human(且非 technical_auto_only)时渲染;系统 Worker 等待整卡隐藏;
|
||||
* 导航类动作 router.push;confirm_customer 发射 confirmCustomer 由父级开弹窗;
|
||||
* 导航类动作 router.push;confirm_customer / mark_manual_uploaded 发射本地事件由父级开弹窗;
|
||||
* POST 类动作调 Workspace API;409 触发 refreshed;
|
||||
* 下一步文案独立于按钮;canHandle=false 时不渲染恢复主按钮,提示用 Footer;
|
||||
* 禁止堆栈/路径/SQL。
|
||||
@@ -49,10 +49,6 @@ const nextActionCode = computed(() =>
|
||||
String(props.summary?.next_action_code || blockingGate.value?.next_action_code || '').trim(),
|
||||
);
|
||||
const hasRecoveryAction = computed(() => Boolean(blockingGate.value && nextActionCode.value));
|
||||
const showManualUploadAction = computed(() => (
|
||||
String(blockingGate.value?.gate_code || '').trim().toLowerCase() === 'manual_upload_handoff'
|
||||
&& nextActionCode.value === 'retry_freight_upload_rpa'
|
||||
));
|
||||
const showInventoryUploadAction = computed(() => (
|
||||
String(blockingGate.value?.gate_code || '').trim().toLowerCase() === 'inventory_preparation'
|
||||
&& nextActionCode.value === 'retry_inventory_preparation'
|
||||
@@ -132,6 +128,12 @@ const failureDetail = computed(() => safeBusinessText(props.summary?.failure_det
|
||||
*/
|
||||
async function runPrimaryAction() {
|
||||
if (!props.summary || !props.canHandle || busy.value) return;
|
||||
// Gate 20 的“确认已人工上传”必须先收集截图/PDF 与货代回执号;
|
||||
// 该动作只打开既有凭据弹窗,禁止普通 Gate POST 绕过证据门槛。
|
||||
if (nextActionCode.value === 'mark_manual_uploaded') {
|
||||
emit('manualUpload');
|
||||
return;
|
||||
}
|
||||
const result = await submitPrimaryAction(props.summary, {
|
||||
navigationContext: props.navigationContext,
|
||||
});
|
||||
@@ -215,15 +217,6 @@ async function runInventoryUpload() {
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.processGate.actionCodes.upload_inventory_file') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showManualUploadAction && canHandle"
|
||||
type="button"
|
||||
class="inline-flex min-h-8 items-center rounded-md border border-default bg-surface px-3 py-1.5 text-xs font-semibold text-secondary shadow-sm transition hover:bg-surface-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2"
|
||||
data-testid="process-gate-manual-upload"
|
||||
@click="emit('manualUpload')"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded') }}
|
||||
</button>
|
||||
<span
|
||||
v-if="!canHandle && hasRecoveryAction"
|
||||
class="text-xs text-muted"
|
||||
|
||||
@@ -40,7 +40,7 @@ function projection(
|
||||
}
|
||||
|
||||
describe('resolveProcessingActionPresentation', () => {
|
||||
it('prefers gate nextActionCode as primary', () => {
|
||||
it('does not turn diagnostic gate nextActionCode into a user action', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
currentGate: {
|
||||
gateCode: 'inventory_source_routing',
|
||||
@@ -51,9 +51,46 @@ describe('resolveProcessingActionPresentation', () => {
|
||||
},
|
||||
availableActions: ['refresh', 'retry'],
|
||||
}));
|
||||
expect(result.primary?.intent).toBe('open_inventory_source_review');
|
||||
expect(result.secondary?.intent).toBe('refresh');
|
||||
expect(result.overflow.map((i) => i.intent)).toContain('retry');
|
||||
expect(result.primary?.intent).toBe('refresh');
|
||||
expect(result.secondary?.intent).toBe('retry');
|
||||
expect(result.overflow).toEqual([]);
|
||||
});
|
||||
|
||||
it('uses ui_state actions as the only source when the backend supplies it', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
status: 'processing',
|
||||
currentGate: {
|
||||
gateCode: 'inventory_source_routing', status: 'blocked', nextActionCode: 'retry',
|
||||
blockingReasonCode: null, attemptNo: 1,
|
||||
},
|
||||
primaryAction: { code: 'retry_parse', i18nKey: 'action.retry_parse', parameters: {} },
|
||||
availableActions: ['retry_parse', 'view_result'],
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'fulfillment_prep', blocking_reason: null,
|
||||
primary_action: { code: 'open_inventory_source_review', i18nKey: 'action.open_inventory_source_review', parameters: {} },
|
||||
secondary_actions: [
|
||||
{ code: 'view_details', enabled: true },
|
||||
{ code: 'retry_parse', enabled: false },
|
||||
],
|
||||
},
|
||||
}));
|
||||
expect(result.primary?.actionCode).toBe('open_inventory_source_review');
|
||||
expect(result.secondary?.actionCode).toBe('view_details');
|
||||
expect(result.overflow).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not revive a legacy primary action when authoritative ui_state explicitly has none', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
primaryAction: { code: 'retry_parse', i18nKey: 'action.retry_parse', parameters: {} },
|
||||
availableActions: ['retry_parse'],
|
||||
uiState: {
|
||||
status: 'processing', stage: 'document_parsing', blocking_reason: null,
|
||||
primary_action: null, secondary_actions: [],
|
||||
},
|
||||
}));
|
||||
|
||||
// ui_state 表达的“无可操作动作”是后端裁决,旧字段不得让按钮复活。
|
||||
expect(result).toEqual({ primary: null, secondary: null, overflow: [] });
|
||||
});
|
||||
|
||||
it('hides primary while automating without gate', () => {
|
||||
@@ -75,6 +112,28 @@ describe('resolveProcessingActionPresentation', () => {
|
||||
expect(result.primary?.actionCode).toBe('retry_parse');
|
||||
});
|
||||
|
||||
it('keeps inventory preparation retry as the batch-card primary action', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
status: 'waiting_human',
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'inventory_fetching', blocking_reason: null,
|
||||
primary_action: {
|
||||
code: 'retry_inventory_preparation',
|
||||
i18nKey: 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
parameters: {},
|
||||
},
|
||||
// Gate 工作台可保留受控上传入口;批次卡只消费 primary_action。
|
||||
secondary_actions: [],
|
||||
},
|
||||
}), { surface: 'right' });
|
||||
|
||||
expect(result.primary).toMatchObject({
|
||||
actionCode: 'retry_inventory_preparation',
|
||||
labelKey: 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
});
|
||||
expect(result.secondary).toBeNull();
|
||||
});
|
||||
|
||||
it('filters open_order_review and refresh on review surface', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
availableActions: ['open_order_review', 'refresh', 'view_result'],
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/shipping-progress/actionPresentation.ts
|
||||
* 用途:从统一投影 / 会话 OT 任务解析四页面共用的 ActionPresentation(主/次/溢出)。
|
||||
* 依赖:ShippingProcessingProjection、ConversationProcessingUserTask、workbenchActionRegistry、types。
|
||||
* 逻辑:优先级 Gate.nextActionCode → availableActions → 终态查看 → none;
|
||||
* 逻辑:新版优先 ui_state.primary_action / secondary_actions;旧响应才兼容 primaryAction / availableActions;
|
||||
* cancel_* 与 view_details 永不作主 CTA;无业务入口时 focus_task 兜底并映射「查看进度」;
|
||||
* 自动处理中(processing/automating)主按钮为空;review 面经注册表 fail-closed 过滤。
|
||||
*/
|
||||
@@ -41,6 +41,7 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
|
||||
match_inventory: 'open_inventory_match_review',
|
||||
open_shortage_review: 'open_shortage_review',
|
||||
upload_inventory_file: 'upload_inventory_file',
|
||||
retry_inventory_preparation: 'retry',
|
||||
retry: 'retry',
|
||||
retry_parse: 'retry',
|
||||
retry_failed_documents: 'retry',
|
||||
@@ -105,6 +106,8 @@ function toItem(
|
||||
const chatOrRight = surface === 'chat' || surface === 'right';
|
||||
if (intent === 'open_order_review' && chatOrRight) {
|
||||
labelKey = 'chat.shippingProcessing.action.open_order_processing';
|
||||
} else if (normalized === 'retry_inventory_preparation') {
|
||||
labelKey = 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation';
|
||||
} else if (normalized === 'retry_freight_upload_rpa' || normalized === 'retry_upload') {
|
||||
labelKey = 'chat.shippingNoticeRetryUploadAction';
|
||||
} else if (intent === 'retry' && chatOrRight) {
|
||||
@@ -160,9 +163,9 @@ export interface ResolveProcessingActionPresentationOptions {
|
||||
* 解析统一动作投影。
|
||||
*
|
||||
* 核心逻辑:
|
||||
* 1. processing/automating/queued → 主按钮为空(自动推进中);
|
||||
* 2. currentGate.nextActionCode 优先;
|
||||
* 3. availableActions 依次填主/次/溢出;
|
||||
* 1. 有 ui_state 时只渲染其已授权主/次动作;
|
||||
* 2. 旧响应 processing/automating/queued → 主按钮为空(自动推进中);
|
||||
* 3. 旧响应由 primaryAction / availableActions 填主/次/溢出;
|
||||
* 4. completed/failed/cancelled → view_result / view_record 兜底;
|
||||
* 5. surface=review 时经注册表 fail-closed(未知隐藏 + 告警;隐藏 refresh/自跳转);
|
||||
* 6. cancel / view_details 强制降为次要或溢出。
|
||||
@@ -180,8 +183,9 @@ export function resolveProcessingActionPresentation(
|
||||
const surface = options?.surface;
|
||||
const actionsExecutable = options?.actionsExecutable !== false;
|
||||
const panels = options?.panels ?? null;
|
||||
const status = String(projection.status || '').trim().toLowerCase();
|
||||
if (AUTOMATING_STATUSES.has(status) && !projection.currentGate?.nextActionCode) {
|
||||
const authoritativeUiState = projection.uiState;
|
||||
const status = String(authoritativeUiState?.status || projection.userStatus || projection.status || '').trim().toLowerCase();
|
||||
if (!authoritativeUiState && AUTOMATING_STATUSES.has(status) && !projection.currentGate?.nextActionCode) {
|
||||
return empty;
|
||||
}
|
||||
|
||||
@@ -231,41 +235,18 @@ export function resolveProcessingActionPresentation(
|
||||
items.push(toItem(code, intent, surface));
|
||||
};
|
||||
|
||||
pushCode(projection.primaryAction?.code || projection.currentGate?.nextActionCode);
|
||||
// Gate 20 同时保留两条用户路径:主动重试 RPA 与人工上传登记。
|
||||
// 该动作由正式任务面板打开登记弹窗,不走 Gate API。
|
||||
if (
|
||||
String(projection.currentGate?.gateCode || '').trim().toLowerCase() === 'manual_upload_handoff'
|
||||
&& items.some((item) => String(item.actionCode).toLowerCase() === 'retry_freight_upload_rpa')
|
||||
) {
|
||||
pushCode('mark_manual_uploaded');
|
||||
}
|
||||
// [ORDER-STABLE] 对 availableActions 标准化(去重 + 字典序排序),确保后端返回顺序不影响前端按钮顺序。
|
||||
const normalizedAvailableActions = normalizeActionCodes(projection.availableActions || []);
|
||||
for (const action of normalizedAvailableActions) {
|
||||
// [AUTHORITY] 新版只消费同一份 ui_state;currentGate 只保留诊断,禁止产生或替换按钮。
|
||||
// 旧服务端未下发 ui_state 时才兼容 primaryAction / availableActions。
|
||||
pushCode(authoritativeUiState
|
||||
? authoritativeUiState.primary_action?.code
|
||||
: projection.primaryAction?.code);
|
||||
const actionCodes = authoritativeUiState
|
||||
? authoritativeUiState.secondary_actions.filter((action) => action.enabled).map((action) => action.code)
|
||||
: normalizeActionCodes(projection.availableActions || []);
|
||||
for (const action of actionCodes) {
|
||||
pushCode(action);
|
||||
}
|
||||
// Gate 19 RPA 失败时,人工登记作为任务级替代路径展示,避免与 RPA 重试并列。
|
||||
if (
|
||||
String(projection.currentGate?.gateCode || '').trim().toLowerCase() === 'freight_upload_rpa'
|
||||
&& items.some((item) => String(item.actionCode).toLowerCase() === 'retry_freight_upload_rpa')
|
||||
) {
|
||||
for (let index = items.length - 1; index >= 0; index -= 1) {
|
||||
const code = String(items[index]?.actionCode || '').toLowerCase();
|
||||
if (code === 'mark_manual_uploaded' || code === 'open_manual_upload' || code === 'wait_manual_upload') {
|
||||
items.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (items.length === 0 && (status === 'completed' || status === 'failed' || status === 'cancelled')) {
|
||||
pushCode('view_result');
|
||||
}
|
||||
|
||||
if (AUTOMATING_STATUSES.has(status) && items.length === 0) {
|
||||
return empty;
|
||||
}
|
||||
|
||||
return partitionActionItems(items);
|
||||
}
|
||||
|
||||
@@ -284,7 +265,7 @@ export function resolveConversationTaskActionPresentation(
|
||||
if (!task) return empty;
|
||||
|
||||
const surface = options?.surface || 'right';
|
||||
const userStatus = String(task.userStatus ?? '').trim().toLowerCase();
|
||||
const userStatus = String(task.uiState?.status ?? task.userStatus ?? '').trim().toLowerCase();
|
||||
const legacyStatus = String(task.status_label ?? '').trim().toLowerCase();
|
||||
const status = userStatus || legacyStatus;
|
||||
const isNeedsAction = task.group === 'needs_action' || NEEDS_ACTION_STATUSES.has(status);
|
||||
@@ -308,19 +289,19 @@ export function resolveConversationTaskActionPresentation(
|
||||
items.push(toItem(code, intent, surface));
|
||||
};
|
||||
|
||||
pushCode(task.primaryAction?.code || task.primary_action);
|
||||
pushCode(task.uiState
|
||||
? task.uiState.primary_action?.code
|
||||
: (task.primaryAction?.code || task.primary_action));
|
||||
// [ORDER-STABLE] 对 available_actions 标准化排序,确保后端顺序变化不影响按钮渲染顺序。
|
||||
const normalizedTaskActions = normalizeActionCodes(task.available_actions || []);
|
||||
const normalizedTaskActions = normalizeActionCodes(
|
||||
task.uiState?.secondary_actions?.filter((item) => item.enabled).map((item) => item.code)
|
||||
|| task.available_actions
|
||||
|| [],
|
||||
);
|
||||
for (const action of normalizedTaskActions) {
|
||||
pushCode(action);
|
||||
}
|
||||
|
||||
// 人工待办禁止伪造查看进度;无明确动作时进入订单处理作为安全兜底。
|
||||
if (isNeedsAction && !items.some((item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()))) {
|
||||
pushCode('open_order_processing');
|
||||
}
|
||||
// 只有系统处理中才允许显示查看进度,且只能作为次要文字链。
|
||||
if (isProcessing && !items.length) pushCode('focus_task');
|
||||
const hasPrimaryCandidate = items.some(
|
||||
(item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()),
|
||||
);
|
||||
|
||||
@@ -43,13 +43,19 @@ const SYSTEM_TECH_ACTION_PREFIXES = ['retry_', 'poll_'];
|
||||
const stageNodes = computed(() => readAuthoritativeStageNodes(props.projection));
|
||||
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
|
||||
/** 新投影存在时,状态、阶段、阻断和动作只能消费同一次后端 ui_state 裁决。 */
|
||||
const authoritativeUiState = computed(() => props.projection.uiState || null);
|
||||
|
||||
/**
|
||||
* 人工阻断优先于遗留 processing/automating 投影,避免已中断任务仍显示系统处理中并持续轮询。
|
||||
*/
|
||||
const isWaitingHuman = computed(() => (
|
||||
props.projection.userStatus === 'waiting_human'
|
||||
|| String(props.projection.currentGate?.status || '').trim().toLowerCase() === 'blocked_manual'
|
||||
authoritativeUiState.value
|
||||
? authoritativeUiState.value.status === 'waiting_human'
|
||||
: (
|
||||
props.projection.userStatus === 'waiting_human'
|
||||
|| String(props.projection.currentGate?.status || '').trim().toLowerCase() === 'blocked_manual'
|
||||
)
|
||||
));
|
||||
|
||||
/**
|
||||
@@ -57,8 +63,11 @@ const isWaitingHuman = computed(() => (
|
||||
*/
|
||||
const isAutomating = computed(() => {
|
||||
if (isWaitingHuman.value) return false;
|
||||
const status = String(props.projection.status || '').trim().toLowerCase();
|
||||
const status = String(
|
||||
authoritativeUiState.value?.status || props.projection.status || '',
|
||||
).trim().toLowerCase();
|
||||
if (!AUTOMATING_STATUSES.has(status)) return false;
|
||||
if (authoritativeUiState.value) return true;
|
||||
const next = String(props.projection.currentGate?.nextActionCode || '').trim().toLowerCase();
|
||||
if (!next) return true;
|
||||
if (SYSTEM_TECH_ACTION_PREFIXES.some((prefix) => next.startsWith(prefix))) return true;
|
||||
@@ -97,6 +106,12 @@ const titleLine = computed(() => {
|
||||
const currentNeedLabel = computed<string | null>(() => {
|
||||
if (props.hasFormalOt) return null;
|
||||
if (isAutomating.value) return null;
|
||||
const uiState = authoritativeUiState.value;
|
||||
if (uiState) {
|
||||
const key = String(uiState.blocking_reason?.i18nKey || '').trim();
|
||||
if (key && te(key)) return t(key);
|
||||
return String(uiState.blocking_reason?.code || '').trim() || null;
|
||||
}
|
||||
const gate = props.projection.currentGate;
|
||||
if (!gate) return null;
|
||||
const reasonCode = String(gate.blockingReasonCode || '').trim();
|
||||
@@ -118,7 +133,7 @@ const currentNeedLabel = computed<string | null>(() => {
|
||||
* 窄屏当前阶段名:只用 stage code → 阶段 i18n,不用 waiting_system_start 等自动化 label_key。
|
||||
*/
|
||||
const currentStageName = computed(() => {
|
||||
const stage = String(props.projection.stage || '').trim();
|
||||
const stage = String(authoritativeUiState.value?.stage || props.projection.stage || '').trim();
|
||||
if (!stage) return '—';
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { buildProgressRangeHint, stageAbsoluteIndex } from '../progressWindow';
|
||||
import { resolveShippingProcessingStatusLabel, shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { useProcessingActionPresentation } from '../composables/useProcessingActionPresentation';
|
||||
import type { ActionPresentationItem } from '../types';
|
||||
import { resolveGateReasonLabel } from '../gateReasonLabel';
|
||||
@@ -32,26 +31,32 @@ const { t, te } = useI18n();
|
||||
|
||||
const projectionRef = computed(() => props.projection);
|
||||
const actionPresentation = useProcessingActionPresentation(projectionRef, { surface: 'right' });
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'right'));
|
||||
|
||||
/**
|
||||
* 紧凑单行:● 阶段名 · 第 x/total。
|
||||
*/
|
||||
const inlineLine = computed(() => {
|
||||
const hint = rangeHint.value;
|
||||
const stageKey = hint?.currentLabelKey || shippingProcessingStageKey(props.projection.stage);
|
||||
const stageLabel = te(stageKey) ? t(stageKey) : props.projection.stage;
|
||||
const index = stageAbsoluteIndex(props.projection.stage) + 1;
|
||||
return `● ${stageLabel} · ${t('chat.shippingProcessing.progress.positionOfTotal', { current: index, total: 15 })}`;
|
||||
const stage = props.projection.uiState?.stage || props.projection.userStage || props.projection.stage;
|
||||
const stageKey = shippingProcessingStageKey(stage);
|
||||
const stageLabel = te(stageKey) ? t(stageKey) : stage;
|
||||
return `● ${stageLabel}`;
|
||||
});
|
||||
|
||||
/**
|
||||
* Gate 阻断原因(禁止展示内部码)。
|
||||
*/
|
||||
const gateReason = computed(() => resolveGateReasonLabel(
|
||||
props.projection.currentGate?.blockingReasonCode,
|
||||
props.projection.uiState
|
||||
? props.projection.uiState.blocking_reason?.code
|
||||
: (props.projection.blockingReason?.code || props.projection.currentGate?.blockingReasonCode),
|
||||
{ t, te },
|
||||
));
|
||||
|
||||
/** 单一状态标签:阶段行只描述位置,状态标签只描述当前可操作状态。 */
|
||||
const statusLabel = computed(() => resolveShippingProcessingStatusLabel(
|
||||
props.projection.uiState?.status || props.projection.userStatus || props.projection.status,
|
||||
te,
|
||||
t,
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -66,6 +71,13 @@ const gateReason = computed(() => resolveGateReasonLabel(
|
||||
>
|
||||
{{ inlineLine }}
|
||||
</div>
|
||||
<span
|
||||
v-if="statusLabel"
|
||||
class="inline-flex rounded-full border border-default bg-surface-muted px-2 py-0.5 text-[10px] font-semibold text-secondary"
|
||||
data-testid="sidebar-progress-status"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
<template v-if="!compact">
|
||||
<p
|
||||
v-if="gateReason"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!--
|
||||
features/shipping-progress/components/WorkbenchProgressGrouped.vue
|
||||
用途:任务台分组进度——解析 1–10 / 库存 11–12 / 履约 13–15 三域 + 当前阶段;可选动作栏。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、UnifiedProgressTrack、UnifiedActionBar。
|
||||
用途:任务台四阶段进度——接收解析 / 订单复核 / 发货准备 / 上传完成;可选动作栏。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、UnifiedProgressTrack、UnifiedActionBar。
|
||||
逻辑:由 ShippingTaskWorkbench 挂载;任务台履约动作归 TaskTodoPanel,默认关闭本组件动作栏(UI-05)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -9,7 +9,6 @@ import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { buildProgressRangeHint, stageAbsoluteIndex } from '../progressWindow';
|
||||
import { useProcessingActionPresentation } from '../composables/useProcessingActionPresentation';
|
||||
import type { ActionPresentationItem } from '../types';
|
||||
import UnifiedActionBar from './UnifiedActionBar.vue';
|
||||
@@ -19,8 +18,11 @@ const props = withDefaults(defineProps<{
|
||||
projection: ShippingProcessingProjection;
|
||||
/** 是否渲染投影动作栏;任务台内嵌时应为 false,避免与 TaskTodoPanel 双入口。 */
|
||||
showActions?: boolean;
|
||||
/** 是否允许展开技术 15 节点;批次中心只展示业务四阶段。 */
|
||||
showTechnicalDetail?: boolean;
|
||||
}>(), {
|
||||
showActions: true,
|
||||
showTechnicalDetail: true,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -32,24 +34,25 @@ const showDetailTrack = ref(false);
|
||||
|
||||
const projectionRef = computed(() => props.projection);
|
||||
const actionPresentation = useProcessingActionPresentation(projectionRef, { surface: 'workbench' });
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
|
||||
|
||||
/** 三域阶段下标区间(0-based,含端点)。 */
|
||||
const DOMAIN_RANGES = [
|
||||
{ key: 'intake', labelKey: 'chat.shippingProcessing.progress.domainIntake', start: 0, end: 9 },
|
||||
{ key: 'inventory', labelKey: 'chat.shippingProcessing.progress.domainInventory', start: 10, end: 11 },
|
||||
{ key: 'fulfillment', labelKey: 'chat.shippingProcessing.progress.domainFulfillment', start: 12, end: 14 },
|
||||
{ key: 'intake_parse', label: '接收解析', stages: ['upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'] },
|
||||
{ key: 'order_review', label: '订单复核', stages: ['order_creating', 'review_required', 'waiting_review'] },
|
||||
{ key: 'fulfillment_prep', label: '发货准备', stages: ['inventory_fetching', 'inventory_matching', 'excel_generating'] },
|
||||
{ key: 'upload_complete', label: '上传完成', stages: ['freight_uploading', 'completed'] },
|
||||
] as const;
|
||||
|
||||
const currentIndex = computed(() => stageAbsoluteIndex(props.projection.stage));
|
||||
|
||||
/**
|
||||
* 判断某域是否为当前/已过/未到。
|
||||
*/
|
||||
function domainState(start: number, end: number): 'passed' | 'current' | 'pending' {
|
||||
const idx = currentIndex.value;
|
||||
if (idx > end) return 'passed';
|
||||
if (idx >= start && idx <= end) return 'current';
|
||||
function domainState(index: number): 'passed' | 'current' | 'pending' {
|
||||
const currentStage = String(
|
||||
props.projection.uiState?.stage || props.projection.userStage || props.projection.stage || '',
|
||||
).trim();
|
||||
const currentIndex = DOMAIN_RANGES.findIndex((domain) => (
|
||||
(domain.stages as readonly string[]).includes(currentStage)
|
||||
));
|
||||
if (index < currentIndex) return 'passed';
|
||||
if (index === currentIndex || (currentIndex < 0 && index === 0)) return 'current';
|
||||
return 'pending';
|
||||
}
|
||||
|
||||
@@ -66,8 +69,9 @@ function domainClass(state: 'passed' | 'current' | 'pending'): string {
|
||||
* 当前阶段中性名称。
|
||||
*/
|
||||
const currentStageLabel = computed(() => {
|
||||
const key = rangeHint.value?.currentLabelKey || shippingProcessingStageKey(props.projection.stage);
|
||||
return te(key) ? t(key) : props.projection.stage;
|
||||
const stage = props.projection.uiState?.stage || props.projection.userStage || props.projection.stage;
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -76,29 +80,20 @@ const currentStageLabel = computed(() => {
|
||||
class="space-y-3"
|
||||
data-testid="workbench-progress-grouped"
|
||||
>
|
||||
<div
|
||||
v-if="rangeHint"
|
||||
class="text-xs text-secondary"
|
||||
data-testid="workbench-progress-range"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.progress.completedOfTotal', {
|
||||
done: rangeHint.done,
|
||||
total: rangeHint.total,
|
||||
}) }}
|
||||
·
|
||||
{{ t('chat.shippingProcessing.progress.currentStage', { stage: currentStageLabel }) }}
|
||||
<div class="text-xs text-secondary" data-testid="workbench-progress-current-stage">
|
||||
当前阶段:{{ currentStageLabel }}
|
||||
</div>
|
||||
|
||||
<div class="grid gap-2 sm:grid-cols-3">
|
||||
<div class="grid gap-2 sm:grid-cols-4" data-testid="workbench-four-stage-track">
|
||||
<div
|
||||
v-for="domain in DOMAIN_RANGES"
|
||||
v-for="(domain, index) in DOMAIN_RANGES"
|
||||
:key="domain.key"
|
||||
class="rounded-xl border px-3 py-2 text-xs font-semibold"
|
||||
:class="domainClass(domainState(domain.start, domain.end))"
|
||||
:class="domainClass(domainState(index))"
|
||||
:data-domain="domain.key"
|
||||
:data-state="domainState(domain.start, domain.end)"
|
||||
:data-state="domainState(index)"
|
||||
>
|
||||
{{ te(domain.labelKey) ? t(domain.labelKey) : domain.key }}
|
||||
{{ domain.label }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -110,6 +105,7 @@ const currentStageLabel = computed(() => {
|
||||
/>
|
||||
|
||||
<button
|
||||
v-if="showTechnicalDetail"
|
||||
type="button"
|
||||
class="text-xs font-medium text-brand-700 underline-offset-2 hover:underline dark:text-brand-300"
|
||||
data-testid="workbench-progress-toggle-detail"
|
||||
@@ -121,7 +117,7 @@ const currentStageLabel = computed(() => {
|
||||
</button>
|
||||
|
||||
<UnifiedProgressTrack
|
||||
v-if="showDetailTrack"
|
||||
v-if="showTechnicalDetail && showDetailTrack"
|
||||
:projection="projection"
|
||||
density="workbench"
|
||||
/>
|
||||
|
||||
@@ -141,6 +141,7 @@ describe('shipping progress presenters', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="sidebar-progress-inline"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="sidebar-progress-line"]').text()).not.toContain('/ 15');
|
||||
});
|
||||
|
||||
it('mounts ReviewProgressStrip as compressed 15-stage readonly strip', () => {
|
||||
@@ -181,6 +182,6 @@ describe('shipping progress presenters', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="workbench-progress-grouped"]').exists()).toBe(true);
|
||||
expect(wrapper.findAll('[data-domain]').length).toBe(3);
|
||||
expect(wrapper.findAll('[data-domain]').length).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -5,8 +5,8 @@
|
||||
* useShippingTodoBadge、useMessage、shippingProcessingLabels。
|
||||
* 逻辑:选中项展示入口卡 + 统一进度紧凑摘要(UI-03);主按钮深链「订单处理工作台」;
|
||||
* review_case 在 failed/manual_fallback 时提供「重试自动推进」(与底栏同一 API/幂等键);
|
||||
* 不内嵌 ShippingTaskWorkbench;轮询依据 shipping_processing_status /
|
||||
* process_status / Intake parse_status。
|
||||
* 不内嵌 ShippingTaskWorkbench;业务阶段和主进度只依据 ui_state.stage/steps,
|
||||
* Intake parse_status 仅用于解析任务轮询。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
@@ -33,14 +33,8 @@ import {
|
||||
IN_PROGRESS_PROCESSING_STATUSES,
|
||||
TERMINAL_PROCESSING_STATUSES,
|
||||
} from '@/features/chat/shipping/shippingProcessingFulfillment';
|
||||
import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { stageAbsoluteIndex } from '@/features/shipping-progress/progressWindow';
|
||||
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
|
||||
import {
|
||||
IN_PROGRESS_PROCESS,
|
||||
isShippingTodoListItemInProgress,
|
||||
} from './shippingTaskCenterPolling';
|
||||
import ShippingRunProgressTable from './ShippingRunProgressTable.vue';
|
||||
@@ -54,18 +48,18 @@ const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/**
|
||||
* 判断详情是否仍处于进行中。
|
||||
* 核心逻辑:与列表同源——优先 shipping_processing_status;缺失时回退 process_status;
|
||||
* 不回退 WorkflowItem lifecycle(UI-03)。
|
||||
* 核心逻辑:优先统一 ui_state.stage;技术 processing status 仅用于轮询,不用于业务阶段展示。
|
||||
*/
|
||||
function isDetailInProgress(task: ShippingTaskDetail | null): boolean {
|
||||
if (!task) return false;
|
||||
const stage = String(task.ui_state?.stage?.code || '').trim();
|
||||
if (stage) return stage !== 'upload_complete';
|
||||
const unified = String(task.shipping_processing_status || '').trim().toLowerCase();
|
||||
if (unified) {
|
||||
if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false;
|
||||
return IN_PROGRESS_PROCESSING_STATUSES.has(unified);
|
||||
}
|
||||
const process = String(task.process_status || '').trim();
|
||||
return IN_PROGRESS_PROCESS.has(process);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -140,31 +134,20 @@ const entryItem = computed((): ShippingTaskSummary | ShippingTaskDetail | null =
|
||||
});
|
||||
|
||||
/**
|
||||
* 任务中心选中项的统一进度紧凑摘要(UI-03):阶段 · n/15 + 阻断文案。
|
||||
* 任务中心选中项的统一进度紧凑摘要:只展示后端阶段与阻断原因。
|
||||
* 15 节点只属于订单详情进度条,任务中心不得重复显示。
|
||||
*/
|
||||
const entryProgressSummary = computed(() => {
|
||||
const item = entryItem.value;
|
||||
if (!item) return null;
|
||||
const stage = String(
|
||||
('shipping_processing_stage' in item ? item.shipping_processing_stage : null)
|
||||
|| '',
|
||||
).trim();
|
||||
const status = String(item.shipping_processing_status || '').trim();
|
||||
if (!stage && !status) return null;
|
||||
const stageKey = shippingProcessingStageKey(stage || '');
|
||||
const stageLabel = stage && te(stageKey) ? t(stageKey) : (stage || resolveShippingProcessingStatusLabel(status, te, t));
|
||||
const index = stage ? stageAbsoluteIndex(stage) + 1 : 0;
|
||||
const gateCode = String(
|
||||
item.ui_state?.process_gate?.current_blocking_gate?.blocking_reason_code
|
||||
|| item.ui_state?.process_gate?.blocking_reason_code
|
||||
|| '',
|
||||
).trim();
|
||||
const blocker = resolveGateReasonLabel(gateCode, { t, te });
|
||||
const stageCode = String(item.ui_state?.stage?.code || '').trim();
|
||||
const stageLabel = String(item.ui_state?.stage?.label || '').trim();
|
||||
if (!stageCode && !stageLabel) return null;
|
||||
const reason = item.ui_state?.reason;
|
||||
const blocker = String(reason?.message || '').trim()
|
||||
|| resolveGateReasonLabel(String(reason?.code || '').trim(), { t, te });
|
||||
return {
|
||||
stageLabel,
|
||||
index,
|
||||
total: 15,
|
||||
statusLabel: resolveShippingProcessingStatusLabel(status, te, t),
|
||||
stageLabel: stageLabel || stageCode,
|
||||
blocker,
|
||||
poNumber: String(item.po_number || '').trim() || null,
|
||||
customerName: String(item.customer_name || '').trim() || null,
|
||||
@@ -198,7 +181,7 @@ function todoDisplayNo(item: ShippingTaskSummary): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否应继续自动轮询:processing 桶、进行中直链详情,或 runs 面;列表项按统一投影 / process_status。
|
||||
* 是否应继续自动轮询:processing 桶、进行中直链详情,或 runs 面;列表项按统一投影。
|
||||
*/
|
||||
const shouldAutoRefresh = computed(() => {
|
||||
if (surface.value === 'runs') return true;
|
||||
@@ -397,8 +380,10 @@ function canRetryStpAutoCreate(item: ShippingTaskSummary | ShippingTaskDetail |
|
||||
const caseNo = String(item.review_case_no || '').trim();
|
||||
if (!caseNo) return false;
|
||||
const summaryActions = item.ui_state?.summary?.allowed_actions || [];
|
||||
const buttons = (item.ui_state?.action_buttons || []).map((action) => String(action));
|
||||
return summaryActions.includes('retry_stp_auto_create') || buttons.includes('retry_stp_auto_create');
|
||||
const actions = [item.ui_state?.actions?.primary, ...(item.ui_state?.actions?.secondary || [])]
|
||||
.filter(Boolean)
|
||||
.map((action) => String(action?.code || ''));
|
||||
return summaryActions.includes('retry_stp_auto_create') || actions.includes('retry_stp_auto_create');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -730,7 +715,7 @@ onBeforeUnmount(() => {
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 truncate text-sm text-secondary">
|
||||
{{ item.ui_state?.summary?.current_todo || item.ui_state?.summary?.title || item.process_status }}
|
||||
{{ item.ui_state?.todo?.title || item.ui_state?.summary?.current_todo || item.ui_state?.summary?.title || item.ui_state?.stage?.label || '—' }}
|
||||
</div>
|
||||
<div class="mt-1 truncate text-xs text-muted">
|
||||
{{ item.customer_name || item.source_file_name || item.review_run_no || '—' }}
|
||||
@@ -838,8 +823,6 @@ onBeforeUnmount(() => {
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.progressSummary', {
|
||||
stage: entryProgressSummary.stageLabel,
|
||||
current: entryProgressSummary.index || '—',
|
||||
total: entryProgressSummary.total,
|
||||
}) }}
|
||||
</p>
|
||||
<p
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingTaskWorkbench.vue
|
||||
* 用途:发货任务处理主区——当前待办栏、统一 15 阶进度、最后活动/终止原因、STP 事实、订单概览、时间线。
|
||||
* 用途:发货任务处理主区——当前待办栏、四阶段进度、最后活动/终止原因、STP 事实、订单概览、时间线。
|
||||
* 依赖:TaskTodoPanel、StpProgressFactsPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、
|
||||
* useShippingProcessingWorkItem、WorkbenchProgressGrouped、listWorkspaceShippingTaskAuditTimeline。
|
||||
* useShippingProcessingWorkItem、ShippingWorkflowStepper、listWorkspaceShippingTaskAuditTimeline。
|
||||
* 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;OT 身份取 detail.order_task_no(禁止 WorkflowItem);
|
||||
* 进度仅来自 ShippingProcessingProjection(showActions=false,动作归 TaskTodoPanel,UI-05);
|
||||
* 业务进度仅来自 detail.ui_state.steps(动作归 TaskTodoPanel,UI-05);
|
||||
* 时间线仅消费统一 ShippingAuditEvent。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
@@ -12,16 +12,12 @@ import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue';
|
||||
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
|
||||
import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping/shippingStepper';
|
||||
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
|
||||
import { useShippingProcessingWorkItem } from '@/features/chat/shipping/useShippingProcessingWorkItem';
|
||||
import type { ShippingTaskAuditTimelineItem, ShippingTaskDetail } from '@/features/chat/types/shipping.api.types';
|
||||
import { listWorkspaceShippingTaskAuditTimeline } from '@/features/chat/api/shipping.api';
|
||||
import WorkbenchProgressGrouped from '@/features/shipping-progress/components/WorkbenchProgressGrouped.vue';
|
||||
import { resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import type { ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import TaskTodoPanel from './TaskTodoPanel.vue';
|
||||
import StpProgressFactsPanel from './StpProgressFactsPanel.vue';
|
||||
@@ -92,34 +88,18 @@ const lastActivityAt = computed(() =>
|
||||
);
|
||||
const terminateReason = computed(() => {
|
||||
const code = String(
|
||||
shippingProcessingProjection.value?.currentGate?.blockingReasonCode || '',
|
||||
shippingProcessingProjection.value?.uiState
|
||||
? shippingProcessingProjection.value.uiState.blocking_reason?.code
|
||||
: shippingProcessingProjection.value?.currentGate?.blockingReasonCode || '',
|
||||
).trim();
|
||||
if (!code) return null;
|
||||
const key = `workspace.shippingNotice.workflowReasons.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
});
|
||||
|
||||
/** 统一投影是否可用。 */
|
||||
const hasFulfillmentProjection = computed(() => Boolean(shippingProcessingProjection.value));
|
||||
const workflowSteps = computed(() => resolveShippingWorkflowSteps(props.detail));
|
||||
|
||||
const unifiedProcessingLabel = computed(() => {
|
||||
const projection = shippingProcessingProjection.value;
|
||||
if (!projection) return '';
|
||||
const status = resolveShippingProcessingStatusLabel(projection.status, te, t);
|
||||
const stageKey = shippingProcessingStageKey(projection.stage);
|
||||
const stage = te(stageKey) ? t(stageKey) : projection.stage;
|
||||
return [status, stage].filter(Boolean).join(' · ');
|
||||
});
|
||||
|
||||
/** 将内部状态映射为业务文案,未知值不回显原始状态码。 */
|
||||
function workflowStatusLabel(value: unknown): string {
|
||||
const code = String(value || '').trim();
|
||||
if (!code) return t('workspace.shippingNotice.status.unknown');
|
||||
const key = `workspace.shippingNotice.workflowStatus.${code}`;
|
||||
return te(key) ? t(key) : t('workspace.shippingNotice.status.unknown');
|
||||
}
|
||||
|
||||
const taskStatusLabel = computed(() => workflowStatusLabel(props.detail.process_status));
|
||||
const taskStatusLabel = computed(() => props.detail.ui_state?.stage?.label || t('workspace.shippingNotice.status.unknown'));
|
||||
const taskMatchStatusLabel = computed(() => {
|
||||
const code = String(props.detail.match_status || '').trim();
|
||||
if (!code) return t('workspace.shippingNotice.matchStatus.unknown');
|
||||
@@ -127,24 +107,6 @@ const taskMatchStatusLabel = computed(() => {
|
||||
return te(key) ? t(key) : t('workspace.shippingNotice.matchStatus.unknown');
|
||||
});
|
||||
|
||||
/**
|
||||
* 任务台统一动作栏:刷新投影;其余 intent 由 TaskTodoPanel 承载。
|
||||
*/
|
||||
function onTaskUnifiedAction(item: ActionPresentationItem) {
|
||||
if (item.intent === 'refresh') {
|
||||
emit('refreshed');
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'download_excel') {
|
||||
void downloadExcel();
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_manual_upload') {
|
||||
// 已在任务台,无需跳转。
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取任务统一审计时间线(ShippingAuditEvent 单源)。
|
||||
*/
|
||||
@@ -202,26 +164,10 @@ async function downloadExcel() {
|
||||
<div class="mb-3 text-xs font-semibold uppercase tracking-wide text-muted">
|
||||
{{ $t('workspace.shippingNotice.todo.workflow') }}
|
||||
</div>
|
||||
<p
|
||||
v-if="unifiedProcessingLabel"
|
||||
class="mb-2 text-xs text-secondary"
|
||||
data-testid="task-shipping-processing-summary"
|
||||
>
|
||||
{{ unifiedProcessingLabel }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="!hasFulfillmentProjection"
|
||||
class="mb-2 text-xs text-amber-700 dark:text-amber-300"
|
||||
data-testid="task-workbench-progress-unavailable"
|
||||
>
|
||||
<ShippingWorkflowStepper v-if="workflowSteps.length" :steps="workflowSteps" compact />
|
||||
<p v-else class="mb-2 text-xs text-amber-700 dark:text-amber-300" data-testid="task-workbench-progress-unavailable">
|
||||
{{ $t('workspace.shippingNotice.todo.progressUnavailable') }}
|
||||
</p>
|
||||
<WorkbenchProgressGrouped
|
||||
v-if="shippingProcessingProjection"
|
||||
:projection="shippingProcessingProjection"
|
||||
:show-actions="false"
|
||||
@action="onTaskUnifiedAction"
|
||||
/>
|
||||
<dl class="mt-3 grid gap-2 text-xs sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.todo.lastActivity') }}</dt>
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* features/workspace/shipping-task-center/TaskTodoPanel.vue
|
||||
* 用途:渲染统一 Gate 恢复卡片与 STP 履约待办说明(表单/弹窗入口)。
|
||||
* 依赖:ProcessGateRecoveryCard、shipping.api、shipping-tasks.api、ManualUploadEvidenceDialog。
|
||||
* 逻辑:gateCanHandle 控制 Gate 卡写按钮;actionsExecutable 控制 invokeActionByCode / 对话框写;
|
||||
* hidePrimaryActions=true 时不渲染 action_buttons(订单处理工作台写入口仅 Footer);
|
||||
* 逻辑:gateCanHandle 控制 Gate 卡写按钮;actionsExecutable 控制统一 action.code 写操作;
|
||||
* hidePrimaryActions=true 时隐藏本卡按钮(订单处理工作台写入口仅 Footer);
|
||||
* 系统 Worker / technical_auto_only 不计入人工阻断,避免「待处理事项」冒充系统等待。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
@@ -35,7 +35,6 @@ import ManualUploadEvidenceDialog from './ManualUploadEvidenceDialog.vue';
|
||||
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
|
||||
import { postWorkspaceProcessGateAction } from '@/features/shipping-process-gates/api/process-gates.api';
|
||||
import type { ShippingProcessGateUserSummary } from '@/features/chat/types/shipping.api.types';
|
||||
import { gateSummaryIndicatesManualUpload } from '@/features/chat/shipping/shippingProcessingFulfillment';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
detail: ShippingTaskDetail;
|
||||
@@ -45,7 +44,7 @@ const props = withDefaults(defineProps<{
|
||||
gateCanHandle?: boolean;
|
||||
/** Footer/Resolver 委托的 invokeActionByCode 是否可执行写。 */
|
||||
actionsExecutable?: boolean;
|
||||
/** 为 true 时隐藏全部 action_buttons(订单处理工作台写入口仅 Footer)。 */
|
||||
/** 为 true 时隐藏本卡全部后端 actions(订单处理工作台写入口仅 Footer)。 */
|
||||
hidePrimaryActions?: boolean;
|
||||
/** 订单处理工作台将 Gate 卡提升到右侧展示时隐藏此处重复卡。 */
|
||||
hideGateCard?: boolean;
|
||||
@@ -92,16 +91,9 @@ const processGateSummary = computed((): ShippingProcessGateUserSummary | null =>
|
||||
|| (summary.value.process_gate as ShippingProcessGateUserSummary | null | undefined)
|
||||
|| null,
|
||||
);
|
||||
const actionButtons = computed(() => props.detail.ui_state?.action_buttons || []);
|
||||
const checkpointKind = computed(() => String(props.detail.ui_state?.checkpoint_kind || ''));
|
||||
/** 统一 Gate 投影中的主要恢复动作;用于去重旧 action_buttons。 */
|
||||
const processGateNextAction = computed(() =>
|
||||
String(
|
||||
processGateSummary.value?.next_action_code
|
||||
|| processGateSummary.value?.current_blocking_gate?.next_action_code
|
||||
|| '',
|
||||
).trim(),
|
||||
);
|
||||
const unifiedActions = computed(() => props.detail.ui_state?.actions || { primary: null, secondary: [] });
|
||||
const backendPrimaryAction = computed(() => unifiedActions.value.primary || null);
|
||||
const backendSecondaryActions = computed(() => unifiedActions.value.secondary || []);
|
||||
/** 有 Gate 阻断时优先展示统一投影文案。 */
|
||||
const displayTodoTitle = computed(() =>
|
||||
processGateSummary.value?.current_blocking_gate?.label
|
||||
@@ -115,31 +107,6 @@ const displayTodoMessage = computed(() =>
|
||||
|| t('workspace.shippingNotice.todo.noActionMessage'),
|
||||
);
|
||||
|
||||
/**
|
||||
* 是否展示「待人工上传登记」提示。
|
||||
* 核心逻辑:优先 process_gate / current_blocking_gate 的 next_action_code 与
|
||||
* available_actions;RPA 上传中不展示;禁止用 workflow_item.lifecycle 作主判据。
|
||||
*/
|
||||
const showWaitingManualUploadNote = computed(() => {
|
||||
const process = String(props.detail.process_status || '').trim();
|
||||
if (process === 'uploading') return false;
|
||||
const gateNextAction = String(
|
||||
processGateSummary.value?.current_blocking_gate?.next_action_code
|
||||
|| processGateSummary.value?.next_action_code
|
||||
|| processGateNextAction.value
|
||||
|| '',
|
||||
).trim();
|
||||
const allowedActions = [
|
||||
...(summary.value.allowed_actions || []),
|
||||
...(actionButtons.value.map((item) => item.id)),
|
||||
];
|
||||
return gateSummaryIndicatesManualUpload({
|
||||
nextActionCode: gateNextAction,
|
||||
checkpointKind: checkpointKind.value,
|
||||
availableActions: allowedActions,
|
||||
});
|
||||
});
|
||||
|
||||
/** 当前导出工件 id,供人工上传登记对话框绑定。 */
|
||||
const currentExportArtifactId = computed(() => {
|
||||
const artifacts = props.detail.export_artifacts;
|
||||
@@ -147,41 +114,6 @@ const currentExportArtifactId = computed(() => {
|
||||
const id = Number(artifacts[0]?.id);
|
||||
return Number.isFinite(id) ? id : null;
|
||||
});
|
||||
/** auto_continue 仅保留刷新;正常 STP 由后台自动推进。 */
|
||||
const AUTO_CONTINUE_ACTIONS = new Set(['refresh']);
|
||||
/** wait_manual_upload 仅允许下载/导出/人工上传确认。 */
|
||||
const WAIT_MANUAL_UPLOAD_ACTIONS = new Set(['download_excel', 'export', 'mark_manual_uploaded', 'refresh']);
|
||||
/** must_human 保留例外处理动作,禁止 Chat 侧履约写路径。 */
|
||||
const MUST_HUMAN_ACTIONS = new Set([
|
||||
'confirm',
|
||||
'reject',
|
||||
'reparse',
|
||||
'replace_notice_file',
|
||||
'rematch',
|
||||
'retry_rpa',
|
||||
'confirm_inventory_source',
|
||||
'retry_resolve_inventory_source',
|
||||
'confirm_customer',
|
||||
'freeze_order',
|
||||
'upload_inventory_file',
|
||||
'match_inventory',
|
||||
'refresh',
|
||||
]);
|
||||
/**
|
||||
* 按 STP checkpoint_kind 过滤工作台动作,避免 auto_continue 误点写操作。
|
||||
*/
|
||||
function isActionAllowedForCheckpoint(actionId: string, kind: string): boolean {
|
||||
if (!kind || kind === 'complete') return actionId === 'refresh';
|
||||
if (kind === 'auto_continue') return AUTO_CONTINUE_ACTIONS.has(actionId);
|
||||
if (kind === 'wait_manual_upload') return WAIT_MANUAL_UPLOAD_ACTIONS.has(actionId);
|
||||
if (kind === 'must_human') return MUST_HUMAN_ACTIONS.has(actionId);
|
||||
return true;
|
||||
}
|
||||
const allowedIds = computed(() => {
|
||||
const fromSummary = summary.value.allowed_actions;
|
||||
if (Array.isArray(fromSummary) && fromSummary.length) return new Set(fromSummary.map(String));
|
||||
return new Set(actionButtons.value.map((item) => item.id));
|
||||
});
|
||||
const hasBlockingGate = computed(() => {
|
||||
const gate = processGateSummary.value;
|
||||
if (!gate?.current_blocking_gate) return false;
|
||||
@@ -205,40 +137,7 @@ const isSystemAutoWait = computed(() => {
|
||||
return !hasBlockingGate.value;
|
||||
});
|
||||
|
||||
const UNIFIED_OWNED_ACTION_IDS = new Set([
|
||||
'retry',
|
||||
'refresh',
|
||||
'download_excel',
|
||||
'export',
|
||||
'open_manual_upload',
|
||||
'mark_manual_uploaded',
|
||||
'regenerate_excel',
|
||||
'view_result',
|
||||
'open_order_review',
|
||||
'open_order_processing',
|
||||
]);
|
||||
|
||||
const visibleActions = computed(() => {
|
||||
// [STEP] 订单处理工作台:写操作仅 Footer;不渲染 Notice action_buttons(D1)。
|
||||
if (props.hidePrimaryActions) return [];
|
||||
// [STEP] Gate 阻断或系统自动等待时均由统一 Gate 投影拥有动作;
|
||||
// 禁止历史 action_buttons(如 edit_formal_task)穿透到当前阶段。
|
||||
if (hasBlockingGate.value || isSystemAutoWait.value) return [];
|
||||
return actionButtons.value.filter((action) => {
|
||||
const id = String(action.id || '');
|
||||
if (id === 'regenerate_manual_upload_todo') return false;
|
||||
if (UNIFIED_OWNED_ACTION_IDS.has(id)) {
|
||||
return false;
|
||||
}
|
||||
if (!allowedIds.value.has(id) || !isActionAllowedForCheckpoint(id, checkpointKind.value)) {
|
||||
return false;
|
||||
}
|
||||
if (processGateNextAction.value && id === processGateNextAction.value) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
});
|
||||
// 统一 actions 已是唯一按钮来源;旧 action_buttons 不再参与渲染。
|
||||
/** Gate 卡写权限;订单处理工作台传入 false 保持只读。 */
|
||||
const resolvedGateCanHandle = computed(() => (
|
||||
props.gateCanHandle !== undefined ? Boolean(props.gateCanHandle) : Boolean(props.canHandle)
|
||||
@@ -508,6 +407,17 @@ async function runAction(action: ShippingChatAction) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 将后端统一动作适配到现有专用弹窗/提交执行器;业务判断仍完全由后端提供。 */
|
||||
async function runUnifiedAction(action: NonNullable<typeof backendPrimaryAction.value>) {
|
||||
if (!action.enabled) return;
|
||||
await runAction({
|
||||
id: action.code,
|
||||
label: action.label || action.code,
|
||||
message: action.disabled_reason || '',
|
||||
variant: action.kind === 'terminate' ? 'danger' : action.kind === 'view' ? 'secondary' : 'primary',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 供订单处理工作台统一 ActionBar 委托履约动作(库存源/匹配/上传登记等)。
|
||||
*
|
||||
@@ -516,13 +426,11 @@ async function runAction(action: ShippingChatAction) {
|
||||
async function invokeActionByCode(actionId: string) {
|
||||
const id = String(actionId || '').trim();
|
||||
if (!id) return;
|
||||
const fromButtons = actionButtons.value.find((item) => String(item.id || '') === id);
|
||||
await runAction(fromButtons || {
|
||||
id,
|
||||
label: id,
|
||||
message: '',
|
||||
variant: 'primary',
|
||||
});
|
||||
const projected = [backendPrimaryAction.value, ...backendSecondaryActions.value]
|
||||
.find((item) => item && item.code === id);
|
||||
if (projected) {
|
||||
await runUnifiedAction(projected);
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
@@ -564,30 +472,33 @@ defineExpose({
|
||||
<div v-if="!resolvedActionsExecutable" class="mt-3 text-xs text-muted">
|
||||
{{ $t('workspace.shippingNotice.todo.adminViewOnly') }}
|
||||
</div>
|
||||
<div v-else-if="visibleActions.length" class="mt-3 flex flex-wrap gap-2">
|
||||
<div v-else-if="backendPrimaryAction || backendSecondaryActions.length" class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="action in visibleActions"
|
||||
:key="action.id"
|
||||
v-if="backendPrimaryAction"
|
||||
:key="backendPrimaryAction.code"
|
||||
type="button"
|
||||
class="rounded-xl px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-50"
|
||||
:class="action.variant === 'danger'
|
||||
:class="backendPrimaryAction.kind === 'terminate'
|
||||
? 'bg-rose-600 text-white hover:bg-rose-700'
|
||||
: action.variant === 'secondary'
|
||||
: backendPrimaryAction.kind === 'view'
|
||||
? 'border border-default bg-surface text-secondary hover:bg-surface-soft'
|
||||
: 'bg-brand-600 text-white hover:bg-brand-700'"
|
||||
:disabled="busyId === action.id"
|
||||
@click="runAction(action)"
|
||||
:disabled="!backendPrimaryAction.enabled || busyId === backendPrimaryAction.code"
|
||||
@click="runUnifiedAction(backendPrimaryAction)"
|
||||
>
|
||||
{{ action.label }}
|
||||
{{ backendPrimaryAction.label || backendPrimaryAction.code }}
|
||||
</button>
|
||||
<button
|
||||
v-for="action in backendSecondaryActions"
|
||||
:key="action.code"
|
||||
type="button"
|
||||
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:opacity-50"
|
||||
:disabled="!action.enabled || busyId === action.code"
|
||||
@click="runUnifiedAction(action)"
|
||||
>
|
||||
{{ action.label || action.code }}
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-if="showWaitingManualUploadNote"
|
||||
class="mt-3 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800"
|
||||
data-testid="manual-upload-end-note"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.todo.waitingManualUploadNote') }}
|
||||
</p>
|
||||
<ManualUploadEvidenceDialog
|
||||
v-model:open="manualUploadOpen"
|
||||
:task-no="detail.task_no"
|
||||
|
||||
@@ -14,7 +14,6 @@ function intakeItem(status: string): ShippingTaskSummary {
|
||||
todo_ref: 'SNI-1',
|
||||
intake_no: 'SNI-1',
|
||||
intake_parse_status: status,
|
||||
process_status: status,
|
||||
todo_category: 'intake_parse',
|
||||
} as ShippingTaskSummary;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
TERMINAL_PROCESSING_STATUSES,
|
||||
} from '@/features/chat/shipping/shippingProcessingFulfillment';
|
||||
|
||||
/** 仍视为进行中、需要自动刷新的任务 process_status(列表项无统一投影时的 notice 任务兜底)。 */
|
||||
/** 历史轮询状态集合;正常任务中心优先消费统一 ui_state。 */
|
||||
export const IN_PROGRESS_PROCESS = new Set([
|
||||
'parsing',
|
||||
'parsed',
|
||||
@@ -36,7 +36,7 @@ export const INTAKE_POLLING_PARSE_STATUSES = new Set([
|
||||
/**
|
||||
* 判断列表项是否应触发轮询刷新。
|
||||
* 核心逻辑:review_case 持续轮询;order_intake 仅 created/queued/parsing;
|
||||
* 其余优先 shipping_processing_status,缺省回退 process_status;
|
||||
* 其余优先 shipping_processing_status,再按统一 ui_state.stage;
|
||||
* 不复用 WorkflowItem lifecycle。
|
||||
* @param item - 我的待办列表项
|
||||
* @returns 是否需要继续轮询
|
||||
@@ -47,7 +47,7 @@ export function isShippingTodoListItemInProgress(item: ShippingTaskSummary): boo
|
||||
}
|
||||
if (item.item_kind === 'order_intake') {
|
||||
const intakeStatus = String(
|
||||
item.intake_parse_status || item.process_status || '',
|
||||
item.intake_parse_status || '',
|
||||
).trim().toLowerCase();
|
||||
return INTAKE_POLLING_PARSE_STATUSES.has(intakeStatus);
|
||||
}
|
||||
@@ -56,6 +56,6 @@ export function isShippingTodoListItemInProgress(item: ShippingTaskSummary): boo
|
||||
if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false;
|
||||
return IN_PROGRESS_PROCESSING_STATUSES.has(unified);
|
||||
}
|
||||
const process = String(item.process_status || '').trim();
|
||||
return IN_PROGRESS_PROCESS.has(process);
|
||||
const stage = String(item.ui_state?.stage?.code || '').trim();
|
||||
return Boolean(stage) && stage !== 'upload_complete';
|
||||
}
|
||||
@@ -558,6 +558,7 @@
|
||||
"resolveFailed": "Failed to resolve conflict. Refresh and try again."
|
||||
},
|
||||
"shippingNoticeUi": {
|
||||
"stage": {"intakeParse": "Intake and parsing", "orderReview": "Order review", "fulfillmentPrep": "Fulfillment preparation", "uploadComplete": "Upload complete"},
|
||||
"rpaModeBrowser": "Real RPA",
|
||||
"rpaModeMock": "Mock RPA",
|
||||
"rpaModeUnknown": "RPA mode unknown",
|
||||
@@ -2579,6 +2580,33 @@
|
||||
},
|
||||
"shippingProcessing": {
|
||||
"batchStatusTitle": "Batch Processing Status",
|
||||
"batchWorkbench": {
|
||||
"overview": {
|
||||
"totalFiles": "Total files",
|
||||
"processing": "Processing",
|
||||
"completed": "Completed",
|
||||
"needsAction": "Needs action",
|
||||
"completion": "{percent}% complete",
|
||||
"processedOfTotal": "{completed}/{total} processed"
|
||||
},
|
||||
"groups": {
|
||||
"failed": "Exceptions · {count} files",
|
||||
"waitingHuman": "Recognition confirmation required · {count} files",
|
||||
"processing": "Processing · {count} files",
|
||||
"failedFallback": "Failed",
|
||||
"waitingFallback": "Needs confirmation",
|
||||
"processingFallback": "Processing"
|
||||
},
|
||||
"artifacts": {
|
||||
"title": "Batch outputs",
|
||||
"downloadAll": "Download batch Excel files",
|
||||
"download": "Download",
|
||||
"empty": "No downloadable outputs",
|
||||
"downloadFailed": "{count} batch output download(s) failed. Retry individually.",
|
||||
"singleDownloadFailed": "Batch output download failed"
|
||||
},
|
||||
"fileProcessing": "File processing"
|
||||
},
|
||||
"batchFilesTotal": "{count} files total",
|
||||
"batchComplete": "Complete",
|
||||
"batchProcessed": "processed",
|
||||
@@ -2595,8 +2623,9 @@
|
||||
"parsingAttachments": "Parsing Attachments",
|
||||
"emailMeta": "Attachments · System processing",
|
||||
"batchFilesUnavailable": "File details are temporarily unavailable. Open the batch workbench to view them.",
|
||||
"openBatchWorkbench": "Open Batch Workbench",
|
||||
"panelTitle": "Processing in this conversation",
|
||||
"openBatchWorkbench": "Open Batch Progress Center",
|
||||
"closeWorkbench": "Close batch workbench",
|
||||
"panelTitle": "Batch Progress Center",
|
||||
"pendingMaterials": "Pending materials",
|
||||
"orderTasks": "Order tasks",
|
||||
"groupNeedsAction": "Needs your action · {count} tasks",
|
||||
@@ -2645,6 +2674,7 @@
|
||||
"status": {
|
||||
"processing": "Processing",
|
||||
"waiting_review": "Waiting for review",
|
||||
"waiting_human": "Waiting for manual handling",
|
||||
"blocked": "Blocked",
|
||||
"automating": "Automating",
|
||||
"completed": "Completed",
|
||||
|
||||
@@ -289,7 +289,7 @@
|
||||
"poll_freight_upload_rpa": "Refresh freight upload progress",
|
||||
"retry_freight_upload_rpa": "Retry freight upload RPA",
|
||||
"regenerate_manual_upload_todo": "Regenerate manual-upload todo",
|
||||
"mark_manual_uploaded": "Record manual upload"
|
||||
"mark_manual_uploaded": "Confirm manual upload"
|
||||
},
|
||||
"reasons": {
|
||||
"freeze_not_ready": "Order is not ready to build or freeze",
|
||||
@@ -426,7 +426,6 @@
|
||||
"line_index": "Line no.",
|
||||
"field_code": "Field",
|
||||
"request_id": "Request ID",
|
||||
"process_status": "Process status",
|
||||
"match_status": "Match status",
|
||||
"task_no": "Task no.",
|
||||
"has_inventory_lines": "Has inventory lines",
|
||||
@@ -445,7 +444,7 @@
|
||||
"openTask": "Open task",
|
||||
"openProcessingHint": "Review, edit, and fulfillment registration happen in the order processing workbench.",
|
||||
"openProcessingUnavailable": "Unable to locate the extraction run. Open order processing from the original conversation.",
|
||||
"progressSummary": "Current: {stage} · {current}/{total}",
|
||||
"progressSummary": "Current stage: {stage}",
|
||||
"progressBlocker": "Blocked: {reason}",
|
||||
"intakeParseBadge": "Material parsing",
|
||||
"buckets": {
|
||||
|
||||
@@ -558,6 +558,7 @@
|
||||
"resolveFailed": "แก้ความขัดแย้งไม่สำเร็จ กรุณารีเฟรชแล้วลองใหม่"
|
||||
},
|
||||
"shippingNoticeUi": {
|
||||
"stage": {"intakeParse": "รับและแยกวิเคราะห์", "orderReview": "ตรวจสอบคำสั่งซื้อ", "fulfillmentPrep": "เตรียมการจัดส่ง", "uploadComplete": "อัปโหลดเสร็จสิ้น"},
|
||||
"rpaModeBrowser": "RPA จริง",
|
||||
"rpaModeMock": "Mock RPA",
|
||||
"rpaModeUnknown": "ไม่ทราบโหมด RPA",
|
||||
@@ -2579,6 +2580,33 @@
|
||||
},
|
||||
"shippingProcessing": {
|
||||
"batchStatusTitle": "สถานะการประมวลผลเป็นชุด",
|
||||
"batchWorkbench": {
|
||||
"overview": {
|
||||
"totalFiles": "ไฟล์ทั้งหมด",
|
||||
"processing": "กำลังประมวลผล",
|
||||
"completed": "เสร็จสิ้น",
|
||||
"needsAction": "ต้องดำเนินการ",
|
||||
"completion": "เสร็จสิ้น {percent}%",
|
||||
"processedOfTotal": "ประมวลผลแล้ว {completed}/{total}"
|
||||
},
|
||||
"groups": {
|
||||
"failed": "ข้อผิดพลาด · {count} ไฟล์",
|
||||
"waitingHuman": "ต้องยืนยันผลการระบุ · {count} ไฟล์",
|
||||
"processing": "กำลังประมวลผล · {count} ไฟล์",
|
||||
"failedFallback": "ล้มเหลว",
|
||||
"waitingFallback": "ต้องยืนยัน",
|
||||
"processingFallback": "กำลังประมวลผล"
|
||||
},
|
||||
"artifacts": {
|
||||
"title": "ผลลัพธ์ของชุดนี้",
|
||||
"downloadAll": "ดาวน์โหลด Excel ทั้งชุด",
|
||||
"download": "ดาวน์โหลด",
|
||||
"empty": "ยังไม่มีผลลัพธ์ที่ดาวน์โหลดได้",
|
||||
"downloadFailed": "ดาวน์โหลดผลลัพธ์ {count} รายการไม่สำเร็จ โปรดลองทีละรายการ",
|
||||
"singleDownloadFailed": "ดาวน์โหลดผลลัพธ์ของชุดไม่สำเร็จ"
|
||||
},
|
||||
"fileProcessing": "กำลังประมวลผลไฟล์"
|
||||
},
|
||||
"batchFilesTotal": "ทั้งหมด {count} ไฟล์",
|
||||
"batchComplete": "เสร็จสิ้น",
|
||||
"batchProcessed": "ประมวลผลแล้ว",
|
||||
@@ -2595,8 +2623,9 @@
|
||||
"parsingAttachments": "กำลังวิเคราะห์ไฟล์แนบ",
|
||||
"emailMeta": "ไฟล์แนบ · ระบบกำลังประมวลผล",
|
||||
"batchFilesUnavailable": "ยังไม่สามารถโหลดรายละเอียดไฟล์ได้ โปรดเปิดเวิร์กเบนช์",
|
||||
"openBatchWorkbench": "เปิดเวิร์กเบนช์การประมวลผล",
|
||||
"panelTitle": "กำลังประมวลผลในการสนทนานี้",
|
||||
"openBatchWorkbench": "เปิดศูนย์ความคืบหน้าชุดงาน",
|
||||
"closeWorkbench": "ปิดเวิร์กเบนช์การประมวลผล",
|
||||
"panelTitle": "ศูนย์ความคืบหน้าชุดงาน",
|
||||
"pendingMaterials": "เอกสารรอดำเนินการ",
|
||||
"orderTasks": "งานคำสั่งซื้อ",
|
||||
"groupNeedsAction": "ต้องดำเนินการ · {count} งาน",
|
||||
@@ -2645,6 +2674,7 @@
|
||||
"status": {
|
||||
"processing": "กำลังประมวลผล",
|
||||
"waiting_review": "รอตรวจสอบ",
|
||||
"waiting_human": "รอดำเนินการโดยเจ้าหน้าที่",
|
||||
"blocked": "ถูกบล็อก",
|
||||
"automating": "กำลังดำเนินการอัตโนมัติ",
|
||||
"completed": "เสร็จสิ้น",
|
||||
|
||||
@@ -223,7 +223,7 @@
|
||||
"poll_freight_upload_rpa": "รีเฟรชความคืบหน้าอัปโหลด freight",
|
||||
"retry_freight_upload_rpa": "ลองอัปโหลด freight RPA อีกครั้ง",
|
||||
"regenerate_manual_upload_todo": "สร้างรายการอัปโหลดด้วยตนเองใหม่",
|
||||
"mark_manual_uploaded": "บันทึกการอัปโหลดด้วยตนเอง"
|
||||
"mark_manual_uploaded": "ยืนยันการอัปโหลดด้วยตนเอง"
|
||||
},
|
||||
"reasons": {
|
||||
"freeze_not_ready": "คำสั่งซื้อยังไม่พร้อมสร้างหรือ freeze",
|
||||
@@ -360,7 +360,6 @@
|
||||
"line_index": "แถว",
|
||||
"field_code": "ฟิลด์",
|
||||
"request_id": "รหัสคำขอ",
|
||||
"process_status": "สถานะกระบวนการ",
|
||||
"match_status": "สถานะการจับคู่",
|
||||
"task_no": "หมายเลขงาน",
|
||||
"has_inventory_lines": "มีแถวสต็อกแล้ว",
|
||||
@@ -379,7 +378,7 @@
|
||||
"openTask": "เปิดงาน",
|
||||
"openProcessingHint": "การตรวจแก้ แก้ไข และลงทะเบียนการจัดส่ง ให้ทำในโต๊ะประมวลผลคำสั่งซื้อ",
|
||||
"openProcessingUnavailable": "ไม่พบงานระบุตัวตน โปรดเปิดโต๊ะประมวลผลจากบทสนทนาเดิม",
|
||||
"progressSummary": "ปัจจุบัน: {stage} · {current}/{total}",
|
||||
"progressSummary": "ขั้นตอนปัจจุบัน: {stage}",
|
||||
"progressBlocker": "ถูกบล็อก: {reason}",
|
||||
"intakeParseBadge": "การแยกวิเคราะห์เอกสาร",
|
||||
"buckets": {
|
||||
@@ -608,8 +607,7 @@
|
||||
"uploadFailed": "อัปโหลดล้มเหลว",
|
||||
"rejected": "ถูกปฏิเสธ",
|
||||
"closed": "ปิดแล้ว",
|
||||
"unknown": "กำลังดำเนินการ",
|
||||
"alignReview": "รอยืนยันฟิลด์"
|
||||
"unknown": "กำลังดำเนินการ"
|
||||
},
|
||||
"matchStatus": {
|
||||
"fulfillable": "ส่งได้ครบ",
|
||||
|
||||
@@ -592,6 +592,7 @@
|
||||
"resolveFailed": "解决冲突失败,请刷新后重试"
|
||||
},
|
||||
"shippingNoticeUi": {
|
||||
"stage": {"intakeParse": "接收解析", "orderReview": "订单复核", "fulfillmentPrep": "发货准备", "uploadComplete": "上传完成"},
|
||||
"rpaModeBrowser": "真实 RPA",
|
||||
"rpaModeMock": "Mock RPA",
|
||||
"rpaModeUnknown": "RPA 模式未知",
|
||||
@@ -2653,6 +2654,33 @@
|
||||
},
|
||||
"shippingProcessing": {
|
||||
"batchStatusTitle": "批处理状态",
|
||||
"batchWorkbench": {
|
||||
"overview": {
|
||||
"totalFiles": "总文件",
|
||||
"processing": "处理中",
|
||||
"completed": "已完成",
|
||||
"needsAction": "需处理",
|
||||
"completion": "{percent}% 完成",
|
||||
"processedOfTotal": "{completed}/{total} 已处理"
|
||||
},
|
||||
"groups": {
|
||||
"failed": "异常 · {count} 个文件",
|
||||
"waitingHuman": "识别结果待确认 · {count} 个文件",
|
||||
"processing": "处理中 · {count} 个文件",
|
||||
"failedFallback": "失败",
|
||||
"waitingFallback": "需确认",
|
||||
"processingFallback": "处理中"
|
||||
},
|
||||
"artifacts": {
|
||||
"title": "本批产物",
|
||||
"downloadAll": "批量下载本批 Excel",
|
||||
"download": "下载",
|
||||
"empty": "暂无可下载产物",
|
||||
"downloadFailed": "本批有 {count} 个产物下载失败,请逐项重试",
|
||||
"singleDownloadFailed": "下载本批产物失败"
|
||||
},
|
||||
"fileProcessing": "文件处理中"
|
||||
},
|
||||
"batchFilesTotal": "共 {count} 个文件",
|
||||
"batchComplete": "完成",
|
||||
"batchProcessed": "已处理",
|
||||
@@ -2669,8 +2697,9 @@
|
||||
"parsingAttachments": "正在解析附件",
|
||||
"emailMeta": "附件处理 · 系统处理中",
|
||||
"batchFilesUnavailable": "文件明细暂不可用,请打开批处理工作台查看。",
|
||||
"openBatchWorkbench": "打开批处理工作台",
|
||||
"panelTitle": "本次处理中",
|
||||
"openBatchWorkbench": "打开批次进度中心",
|
||||
"closeWorkbench": "关闭批次工作台",
|
||||
"panelTitle": "批次进度中心",
|
||||
"pendingMaterials": "待处理材料",
|
||||
"orderTasks": "订单任务",
|
||||
"groupNeedsAction": "需要你处理 · {count} 个任务",
|
||||
@@ -2719,6 +2748,7 @@
|
||||
"status": {
|
||||
"processing": "处理中",
|
||||
"waiting_review": "待复核",
|
||||
"waiting_human": "待人工处理",
|
||||
"blocked": "已阻断",
|
||||
"automating": "自动推进中",
|
||||
"completed": "已完成",
|
||||
|
||||
@@ -289,7 +289,7 @@
|
||||
"poll_freight_upload_rpa": "刷新货代上传进度",
|
||||
"retry_freight_upload_rpa": "重试货代上传 RPA",
|
||||
"regenerate_manual_upload_todo": "重新生成待上传待办",
|
||||
"mark_manual_uploaded": "人工上传登记"
|
||||
"mark_manual_uploaded": "确认已人工上传"
|
||||
},
|
||||
"reasons": {
|
||||
"freeze_not_ready": "订单尚未满足建单/冻结条件",
|
||||
@@ -426,7 +426,6 @@
|
||||
"line_index": "行号",
|
||||
"field_code": "字段",
|
||||
"request_id": "请求编号",
|
||||
"process_status": "处理状态",
|
||||
"match_status": "匹配状态",
|
||||
"task_no": "任务编号",
|
||||
"has_inventory_lines": "是否已有库存行",
|
||||
@@ -445,7 +444,7 @@
|
||||
"openTask": "打开任务",
|
||||
"openProcessingHint": "单票校对、改单与履约登记请在订单处理工作台完成。",
|
||||
"openProcessingUnavailable": "暂无法定位识别任务,请从原对话打开订单处理工作台。",
|
||||
"progressSummary": "当前:{stage} · {current}/{total}",
|
||||
"progressSummary": "当前阶段:{stage}",
|
||||
"progressBlocker": "当前阻断:{reason}",
|
||||
"intakeParseBadge": "材料解析",
|
||||
"buckets": {
|
||||
|
||||
@@ -558,6 +558,7 @@
|
||||
"resolveFailed": "解決衝突失敗,請重新整理後再試"
|
||||
},
|
||||
"shippingNoticeUi": {
|
||||
"stage": {"intakeParse": "接收解析", "orderReview": "訂單複核", "fulfillmentPrep": "發貨準備", "uploadComplete": "上傳完成"},
|
||||
"rpaModeBrowser": "真實 RPA",
|
||||
"rpaModeMock": "Mock RPA",
|
||||
"rpaModeUnknown": "RPA 模式未知",
|
||||
@@ -2579,6 +2580,33 @@
|
||||
},
|
||||
"shippingProcessing": {
|
||||
"batchStatusTitle": "批次處理狀態",
|
||||
"batchWorkbench": {
|
||||
"overview": {
|
||||
"totalFiles": "總檔案",
|
||||
"processing": "處理中",
|
||||
"completed": "已完成",
|
||||
"needsAction": "需處理",
|
||||
"completion": "完成 {percent}%",
|
||||
"processedOfTotal": "已處理 {completed}/{total}"
|
||||
},
|
||||
"groups": {
|
||||
"failed": "異常 · {count} 個檔案",
|
||||
"waitingHuman": "識別結果待確認 · {count} 個檔案",
|
||||
"processing": "處理中 · {count} 個檔案",
|
||||
"failedFallback": "失敗",
|
||||
"waitingFallback": "需確認",
|
||||
"processingFallback": "處理中"
|
||||
},
|
||||
"artifacts": {
|
||||
"title": "本批產物",
|
||||
"downloadAll": "批次下載本批 Excel",
|
||||
"download": "下載",
|
||||
"empty": "暫無可下載產物",
|
||||
"downloadFailed": "本批有 {count} 個產物下載失敗,請逐項重試",
|
||||
"singleDownloadFailed": "下載本批產物失敗"
|
||||
},
|
||||
"fileProcessing": "檔案處理中"
|
||||
},
|
||||
"batchFilesTotal": "共 {count} 個檔案",
|
||||
"batchComplete": "完成",
|
||||
"batchProcessed": "已處理",
|
||||
@@ -2595,8 +2623,9 @@
|
||||
"parsingAttachments": "正在解析附件",
|
||||
"emailMeta": "附件處理 · 系統處理中",
|
||||
"batchFilesUnavailable": "檔案明細暫不可用,請開啟批次工作台查看。",
|
||||
"openBatchWorkbench": "開啟批次工作台",
|
||||
"panelTitle": "本次處理中",
|
||||
"openBatchWorkbench": "開啟批次進度中心",
|
||||
"closeWorkbench": "關閉批次工作台",
|
||||
"panelTitle": "批次進度中心",
|
||||
"pendingMaterials": "待處理材料",
|
||||
"orderTasks": "訂單任務",
|
||||
"groupNeedsAction": "需要你處理 · {count} 個任務",
|
||||
@@ -2645,6 +2674,7 @@
|
||||
"status": {
|
||||
"processing": "處理中",
|
||||
"waiting_review": "待複核",
|
||||
"waiting_human": "待人工處理",
|
||||
"blocked": "已阻斷",
|
||||
"automating": "自動推進中",
|
||||
"completed": "已完成",
|
||||
|
||||
@@ -289,7 +289,7 @@
|
||||
"poll_freight_upload_rpa": "重新整理貨代上傳進度",
|
||||
"retry_freight_upload_rpa": "重試貨代上傳 RPA",
|
||||
"regenerate_manual_upload_todo": "重新產生待上傳待辦",
|
||||
"mark_manual_uploaded": "人工上傳登記"
|
||||
"mark_manual_uploaded": "確認已人工上傳"
|
||||
},
|
||||
"reasons": {
|
||||
"freeze_not_ready": "訂單尚未滿足建單/凍結條件",
|
||||
@@ -426,7 +426,6 @@
|
||||
"line_index": "行號",
|
||||
"field_code": "欄位",
|
||||
"request_id": "請求編號",
|
||||
"process_status": "處理狀態",
|
||||
"match_status": "匹配狀態",
|
||||
"task_no": "任務編號",
|
||||
"has_inventory_lines": "是否已有庫存行",
|
||||
@@ -445,7 +444,7 @@
|
||||
"openTask": "打開任務",
|
||||
"openProcessingHint": "單票校對、改單與履約登記請在訂單處理工作台完成。",
|
||||
"openProcessingUnavailable": "暫無法定位識別任務,請從原對話打開訂單處理工作台。",
|
||||
"progressSummary": "目前:{stage} · {current}/{total}",
|
||||
"progressSummary": "目前階段:{stage}",
|
||||
"progressBlocker": "目前阻斷:{reason}",
|
||||
"intakeParseBadge": "材料解析",
|
||||
"buckets": {
|
||||
|
||||
Reference in new issue
Block a user