Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-08-20 20:27:21 +08:00
commit 3985b34dda
606 files changed
+52167 -36839

No files matched your search

+57 -210
View File
@@ -9,11 +9,11 @@
*/
import { BusinessError, requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
import {
normalizeShippingProcessingProjection,
normalizeShippingProcessingWorkItems,
} from '../shipping/normalizeShippingProcessing';
import { normalizeConversationProcessingProjection } from '../shipping/conversationProcessingProjection';
import type {
ShippingDecisionResponse,
ShippingOrderExtractionDocumentsResponse,
@@ -30,6 +30,9 @@ import type {
ShippingOrderExtractionRun,
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRunCreateResponse,
ShippingOrderReviewQueue,
ShippingOrderReviewEmailEvidencePreview,
ShippingOrderReviewIntakeParseContext,
OrderExtractionSubmissionRequest,
OrderExtractionSubmissionResponse,
ConversationProcessingProjection,
@@ -48,8 +51,6 @@ import type {
ShippingDuplicateAction,
ShippingOrderReviewDraftWrite,
ShippingOrderReviewEvidence,
ShippingOrderReviewInventoryCandidatesWrite,
ShippingOrderReviewInventoryRoutingDecisionWrite,
ShippingOrderReviewInventoryRoutingRerouteWrite,
ShippingOrderReviewLlmAdjudicationPayload,
ShippingOrderReviewLlmSuggestion,
@@ -91,28 +92,6 @@ function jsonPost(body?: unknown): RequestInit {
};
}
/** 订单处理工作台履约写归属上下文(与后端 assert_notice_task_ownership 对齐)。 */
export type ShippingFulfillmentOwnershipContext = {
expectedOrderTaskNo?: string;
expectedReviewCaseNo?: string;
expectedRunNo?: string;
};
/**
* 将归属上下文序列化为 API snake_case 载荷字段。
*/
function ownershipPayload(ownership?: ShippingFulfillmentOwnershipContext | null): Record<string, string> {
if (!ownership) return {};
const out: Record<string, string> = {};
const ot = String(ownership.expectedOrderTaskNo || '').trim();
const caseNo = String(ownership.expectedReviewCaseNo || '').trim();
const run = String(ownership.expectedRunNo || '').trim();
if (ot) out.expected_order_task_no = ot;
if (caseNo) out.expected_review_case_no = caseNo;
if (run) out.expected_run_no = run;
return out;
}
function assertShippingOk<T extends ShippingApiStatusPayload>(body: T): T {
if (body.status === 'failed') {
throw new BusinessError({
@@ -125,20 +104,13 @@ function assertShippingOk<T extends ShippingApiStatusPayload>(body: T): T {
return body;
}
// #region debug-point E:workspace-api
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
reportShippingDebugEvent('shipping.api.ts', hypothesisId, msg, data);
// #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));
@@ -177,6 +149,14 @@ export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
export const workspaceShippingExportUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
/** 当前任务已关联库存快照的受控下载 URL;后端会再次校验任务归属与活动 link。 */
export const workspaceShippingInventoryFileUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-file`;
/** 当前任务指定明细匹配快照的受控下载 URL;文件号必须由行级投影提供。 */
export const workspaceShippingLineInventoryFileUrl = (taskNo: string, inventoryFileNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-files/${encodeURIComponent(inventoryFileNo)}`;
/** 下载一个批次或显式任务集合的当前 ready 发货 Excel ZIP。 */
export async function downloadWorkspaceShippingExportArchive(payload: { batch_no?: string; task_nos?: string[] }) {
const response = await fetch('/api/workspace/shipping-exports/archive', {
@@ -219,8 +199,8 @@ export const createWorkspaceOrderExtractionSubmission = (
/**
* 拉取统一 ShippingProcessingProjection(唯一进度读源;含 order_intake / order_task)。
* 核心逻辑:内嵌 conversation_processing 可选;缺省时前端由 work_items 合成分组;
* 旧 conversation processing GET 已移除(无历史兼容)。
* 核心逻辑:内嵌 conversation_processing.status_groups 是新版批次列表唯一读源;
* 仅旧服务端未返回该字段时才由 work_items 合成兼容分组;旧 GET 已移除。
*/
type WorkspaceShippingProcessingResponse = {
conversation_id: string;
@@ -258,7 +238,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);
@@ -370,10 +354,24 @@ export const reparseWorkspaceShippingOrderExtractionRun = (
jsonPost(payload),
);
/** 在批次中心按 PDF 子任务创建重解析版本;已确认/履约文件由服务端排除。 */
export const reparseWorkspaceShippingOrderExtractionBatch = (
runNo: string,
payload: { reason: 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other'; comment?: string },
) => requestJson<{
batch_reparse_id: string;
source_run_no: string;
created: Array<{ case_no: string; document_id: number; run_no: string; reused: boolean }>;
excluded: Array<{ case_no: string; document_id: number; reason_code: string }>;
}>(
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/reparse-batch`,
jsonPost(payload),
);
/** 获取当前订单抽取 Run 的按 PDF 归并详情。 */
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) =>
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string, uploadBatchId?: string | null) =>
requestJson<ShippingOrderExtractionDocumentsResponse>(
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents`,
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents${uploadBatchId ? `?upload_batch_id=${encodeURIComponent(uploadBatchId)}` : ''}`,
);
/** 获取 Run 下每份 PDF 的建单前复核摘要,服务端负责 owner 隔离。 */
@@ -423,7 +421,7 @@ export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey:
);
export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expectedDraftVersion: number) =>
requestJson<ShippingOrderReviewCase>(
requestJson<{ case: ShippingOrderReviewCase }>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/validate`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
);
@@ -446,41 +444,6 @@ export const retryWorkspaceShippingOrderStpAutoCreate = (caseNo: string) =>
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) },
);
/**
* 对话级「重试自动推进」:服务端扫描会话下可恢复 Case/正式 OT。
* 核心逻辑:前端不提交对象列表;返回 summary + 逐对象 items。
* @param conversationId - 会话 ID
* @param reason - 可选原因码
*/
export const retryWorkspaceConversationAutoProgress = (
conversationId: string,
reason = 'user_retry_auto_progress',
) =>
requestJson<{
conversation_id: string;
summary: {
total: number;
retried: number;
skipped: number;
failed: number;
blocked?: number;
};
items: Array<{
object_type: 'review_case' | 'formal_task' | string;
object_ref: string;
action?: string | null;
outcome: 'queued' | 'skipped' | 'failed' | string;
reason_code?: string | null;
}>;
}>(
`/api/workspace/shipping-conversations/${encodeURIComponent(conversationId)}/retry-auto-progress`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason }),
},
);
/**
* 为复核明细人工选定一个或多个已启用库存源候选。
* 核心逻辑:携带 expected_draft_version 乐观锁;服务端写入行级 inventory_routing 后重跑资格校验。
@@ -488,15 +451,6 @@ export const retryWorkspaceConversationAutoProgress = (
* @param lineKey - Draft 行稳定标识 line_key
* @param payload - 候选编码与强制说明
*/
export const putWorkspaceShippingOrderReviewInventoryCandidates = (
caseNo: string,
lineKey: string,
payload: ShippingOrderReviewInventoryCandidatesWrite,
) => requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-candidates`,
{ method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/**
* 读取正式 Task 当前库存候选版本与历史摘要。
*/
@@ -527,38 +481,6 @@ export const postWorkspaceShippingOrderReviewInventoryRoutingReroute = (
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/**
* 采纳行级规则建议为有效库存源候选。
* 核心逻辑:清除 suggestion_pending;服务端写入后重跑建单资格。
* @param caseNo - 复核 Case 编号
* @param lineKey - Draft 行稳定标识
* @param payload - 版本锁、幂等键与可选原因
*/
export const postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion = (
caseNo: string,
lineKey: string,
payload: ShippingOrderReviewInventoryRoutingDecisionWrite,
) => requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-routing/adopt-suggestion`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/**
* 保留当前人工库存路由结果并忽略待决规则建议。
* 核心逻辑:清除 suggestion_pending;不覆盖已选人工候选。
* @param caseNo - 复核 Case 编号
* @param lineKey - Draft 行稳定标识
* @param payload - 版本锁、幂等键与可选原因
*/
export const postWorkspaceShippingOrderReviewInventoryRoutingKeepManual = (
caseNo: string,
lineKey: string,
payload: ShippingOrderReviewInventoryRoutingDecisionWrite,
) => requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-routing/keep-manual`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/**
* 复核工作台重新识别客户(不重解析 PDF)。
*/
@@ -712,20 +634,6 @@ export const reparseWorkspaceShippingOrderReviewDocument = (caseNo: string, reas
jsonPost({ reason, comment }),
);
/** 绑定已上传的替代 PDF;预解析成功后再单独创建替代识别 Run。 */
export const createWorkspaceShippingOrderReviewReplacementIntake = (caseNo: string, assetNo: string) =>
requestJson<ShippingNoticeIntakeResponse>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/replacement-intakes`,
jsonPost({ asset_no: assetNo }),
);
/** 替代 Intake 解析成唯一 PDF 后创建新的单文档 Run。 */
export const createWorkspaceShippingOrderReviewReplacementRun = (caseNo: string, intakeNo: string) =>
requestJson<ShippingOrderReviewReparseResponse>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/replacement-runs`,
jsonPost({ intake_no: intakeNo }),
);
/**
* 获取复核字段的安全证据摘要(含 highlight_quality / highlight_bbox 契约字段)。
* PDF 二进制继续由受控同源预览接口提供;坐标缺失不影响字段值。
@@ -848,6 +756,7 @@ export const decideWorkspaceShippingOrderReviewLineFulfillment = (
line_key: string;
decision_code: ShippingOrderReviewLineFulfillmentDecisionCode | string;
reason?: string;
release_field_values?: Record<string, string>;
expected_draft_version?: number;
},
) => requestJson<{
@@ -934,10 +843,28 @@ export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Pr
return response.blob();
}
/** 读取当前 Case 同 Intake 的邮件证据安全预览;evidenceId 仅用于受控唯一范围高亮。 */
export const getWorkspaceShippingOrderReviewEmailEvidencePreview = (caseNo: string, documentId: number, evidenceId?: string) =>
requestJson<ShippingOrderReviewEmailEvidencePreview>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/email-evidence-preview/${documentId}${evidenceId ? `?evidence_id=${encodeURIComponent(evidenceId)}` : ''}`,
);
/** 获取当前 Case 所属附件与同 Intake 邮件正文;仅在接收解析工作面打开时调用。 */
export const getWorkspaceShippingOrderReviewIntakeParseContext = (caseNo: string) =>
requestJson<ShippingOrderReviewIntakeParseContext>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/intake-parse-context`,
);
/** 获取当前 Run 所属会话的有效订单队列。 */
export const getWorkspaceShippingOrderReviewQueue = (runNo: string) =>
requestJson<ShippingOrderReviewQueue>(
`/api/workspace/shipping-notice/order-review-queue/${encodeURIComponent(runNo)}`,
);
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string, uploadBatchId?: string | null) =>
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events`,
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events${uploadBatchId ? `?upload_batch_id=${encodeURIComponent(uploadBatchId)}` : ''}`,
);
/** 在终态状态卡已投影到当前会话后确认已查看,避免只因预加载会话列表而消除提醒。 */
@@ -1003,20 +930,6 @@ export const purgeWorkspaceShippingTasks = (taskNos: string[], reason: string) =
'/api/workspace/shipping-tasks/batch-purge', jsonPost({ task_nos: taskNos, reason }),
);
/**
* 确认当前任务的库存 RPA 来源。
* @param taskNo - 发货任务编号
* @param sourceCode - 已配置的库存源编码
* @returns RPA 库存导出触发结果
*/
export async function confirmWorkspaceShippingInventorySource(taskNo: string, sourceCode: string) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/confirm-inventory-source`,
jsonPost({ source_code: sourceCode }),
);
return assertShippingOk(body);
}
/** 搜索可供业务用户确认的启用标准客户。 */
export const listWorkspaceShippingCustomerOptions = (query = '') => {
const params = new URLSearchParams({ limit: '200' });
@@ -1112,37 +1025,6 @@ export async function retryWorkspaceShippingTaskLine(
return assertShippingOk(body);
}
/**
* 提交人工决策。
* @param taskNo - 发货任务编号
* @param decision - 决策 ID,如 confirm、reject、reparse
* @param comment - 可选备注
* @returns 决策执行结果
*/
export async function submitWorkspaceShippingDecision(taskNo: string, decision: string, comment?: string) {
// #region debug-point E:submit-decision-entry
void reportRetryRpaDebug('E', 'submitWorkspaceShippingDecision entry', {
taskNo,
decision,
hasComment: Boolean(comment),
});
// #endregion
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/submit-decision`,
jsonPost({ decision, ...(comment ? { comment } : {}) }),
);
// #region debug-point E:submit-decision-response
void reportRetryRpaDebug('E', 'submitWorkspaceShippingDecision response', {
taskNo,
decision,
status: String(body?.status || ''),
message: String(body?.message || ''),
code: String(body?.code || ''),
});
// #endregion
return assertShippingOk(body);
}
/** 人工复核证据只允许已绑定文档单元格或具名人工输入。 */
export type ShippingReviewEvidence =
| { evidence_type: 'document_cell'; document_id: number; observation_id: number; page_no: number; table_id: string; cell_id: string }
@@ -1175,24 +1057,6 @@ export async function updateWorkspaceShippingNoticeFields(
return assertShippingOk(body);
}
/**
* 冻结已复核的订单数据为后续库存、Excel 与上传唯一读取的履约快照。
* @param taskNo - 当前任务编号
* @param expectedOrderDataVersion - 用户看到的订单版本,用于拒绝并发覆盖
*/
export async function freezeWorkspaceShippingOrder(
taskNo: string,
expectedOrderDataVersion: number,
) {
const body = await requestJson<ShippingApiStatusPayload & {
data?: { task_no: string; snapshot_id: number; order_data_version: number; frozen_at: string };
}>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/freeze-order`,
jsonPost({ expected_order_data_version: expectedOrderDataVersion }),
);
return assertShippingOk(body);
}
/**
* 更新指定订单行。
* @param taskNo - 发货任务编号
@@ -1364,23 +1228,6 @@ export async function markWorkspaceShippingManualUploaded(
return assertShippingOk(body);
}
/**
* 重试将发货 Excel 上传至货代系统。
* @param taskNo - 发货任务编号
* @param ownership - 可选工作台归属上下文
* @returns RPA 上传触发或等待结果
*/
export async function retryWorkspaceShippingUpload(
taskNo: string,
ownership?: ShippingFulfillmentOwnershipContext | null,
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry-upload`,
jsonPost(ownershipPayload(ownership)),
);
return assertShippingOk(body);
}
/** 发货通知 Agent 应用类型标识(运行时识别)。 */
export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
@@ -0,0 +1,115 @@
/**
* features/chat/components/ChatInputBar.spec.ts
* 用途:验证采购合同双文件在聊天输入栏中的统一卡片展示与删除交互。
* 依赖:Vue Test Utils、Vue I18n、ChatInputBar。
* 逻辑:我方原合同和卖方回传合同均以附件卡片展示;删除我方原合同必须通知上层清除对应资产状态。
*/
import { mount } from '@vue/test-utils';
import { ref } from 'vue';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import ChatInputBar from './ChatInputBar.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': {} },
});
/** 创建采购合同双文件输入栏所需的最小属性。 */
function mountProcurementInputBar() {
return mount(ChatInputBar, {
props: {
modelValue: '',
procurementReviewMode: 'compare',
attachments: [{
id: 'seller-contract',
kind: 'local',
file: new File(['seller'], '卖方回传合同.md', { type: 'text/markdown' }),
type: 'document',
uploadStatus: 'waiting',
uploadProgress: 0,
}],
attachmentPolicy: { anyEnabled: true, canLocal: true, canRemote: false, accept: '.md' },
isThinking: false,
isVoiceRecording: false,
isVoiceTranscribing: false,
isUploadingAttachments: false,
canSendMessage: true,
isShippingNoticeAgent: false,
isProcurementContractAgent: true,
procurementOriginalContractName: '我方原合同.md',
isMaintenanceAgent: false,
canManageMaintenance: false,
canForceCreateShippingDuplicate: false,
shippingSuggestedPrompt: '',
shippingPickerRefHolder: { pickerRef: ref(null) },
shippingNoticePickerRefHolder: { pickerRef: ref(null) },
},
global: { plugins: [i18n] },
});
}
/** 创建仅选择我方原合同、尚未选择卖方回传合同的输入栏。 */
function mountOriginalContractOnlyInputBar() {
return mount(ChatInputBar, {
props: {
modelValue: '',
procurementReviewMode: 'compare',
attachments: [],
attachmentPolicy: { anyEnabled: true, canLocal: true, canRemote: false, accept: '.md' },
isThinking: false,
isVoiceRecording: false,
isVoiceTranscribing: false,
isUploadingAttachments: true,
canSendMessage: false,
isShippingNoticeAgent: false,
isProcurementContractAgent: true,
procurementOriginalContractName: '我方原合同.md',
isMaintenanceAgent: false,
canManageMaintenance: false,
canForceCreateShippingDuplicate: false,
shippingSuggestedPrompt: '',
shippingPickerRefHolder: { pickerRef: ref(null) },
shippingNoticePickerRefHolder: { pickerRef: ref(null) },
},
global: { plugins: [i18n] },
});
}
describe('ChatInputBar procurement contract attachments', () => {
it('shows the original contract immediately even before a seller contract is selected', () => {
const wrapper = mountOriginalContractOnlyInputBar();
// 原合同上传中时卖方附件数组为空,仍必须显示原合同卡片提供明确反馈。
expect(wrapper.get('[data-testid="chat-attachment-list"]')).toBeTruthy();
expect(wrapper.get('[data-testid="procurement-original-contract-card"]')).toBeTruthy();
expect(wrapper.findAll('[data-testid="chat-attachment-card"]')).toHaveLength(0);
});
it('renders the original contract as a standard attachment card and clears it on delete', async () => {
const wrapper = mountProcurementInputBar();
// 断言两份合同使用同一附件卡片结构,防止我方原合同退化回独立小标签。
expect(wrapper.get('[data-testid="procurement-original-contract-card"]')).toBeTruthy();
expect(wrapper.findAll('[data-testid="chat-attachment-card"], [data-testid="procurement-original-contract-card"]')).toHaveLength(2);
await wrapper.get('[data-testid="remove-procurement-original-contract"]').trigger('click');
// 删除操作必须交由父级清空 originalContractAssetNo 与名称,避免残留无形基准文件。
expect(wrapper.emitted('clear-procurement-original-contract')).toHaveLength(1);
});
it('keeps original-contract delete pointer events out of the attachment drag surface', async () => {
const wrapper = mountProcurementInputBar();
let dragSurfaceReceivedPointerDown = false;
wrapper.get('[data-testid="chat-attachment-list"]').element.addEventListener('pointerdown', () => {
dragSurfaceReceivedPointerDown = true;
});
// 删除按钮不能触发横向拖拽容器,否则指针捕获会干扰实际 click 事件。
await wrapper.get('[data-testid="remove-procurement-original-contract"]').trigger('pointerdown');
expect(dragSurfaceReceivedPointerDown).toBe(false);
});
});
@@ -159,6 +159,12 @@ const hasProcurementContractAttachment = computed(() =>
&& props.attachments.some((item) => item.kind === 'local'),
);
/** 显示我方原合同卡片的文件扩展名;没有扩展名时使用通用文档标识。 */
function getProcurementOriginalContractExtension(name: string): string {
const extension = name.split('.').pop()?.trim();
return extension ? extension.toUpperCase().slice(0, 4) : 'DOC';
}
const procurementQuickActions = computed(() => {
const actions = [
{
@@ -457,7 +463,7 @@ watch(
</div>
<div
v-if="attachments.length > 0"
v-if="attachments.length > 0 || (isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName)"
data-testid="chat-attachment-list"
class="relative flex items-center gap-1 px-2.5 pb-2 pt-1"
>
@@ -473,9 +479,44 @@ watch(
@pointercancel="stopAttachmentDrag"
@pointerleave="stopAttachmentDrag"
>
<article
v-if="isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName"
data-testid="procurement-original-contract-card"
class="group relative flex h-[68px] w-[250px] shrink-0 items-center gap-3 rounded-xl border border-[#9cc7f2] bg-[#eef6ff] px-3 py-2.5 transition-colors"
:title="procurementOriginalContractName"
>
<div
class="flex h-11 w-10 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
aria-hidden="true"
>
<FileText class="h-4.5 w-4.5" />
<span class="mt-0.5 max-w-9 truncate text-[9px] font-bold leading-none">{{ getProcurementOriginalContractExtension(procurementOriginalContractName) }}</span>
</div>
<div class="min-w-0 flex-1 pr-5">
<p class="truncate text-sm font-medium text-primary">
<span class="mr-1 text-[#2f80d1]">{{ $t('chat.procurementContract.originalContractChip', { name: '' }) }}</span>
{{ procurementOriginalContractName }}
</p>
<div class="mt-1 flex min-w-0 items-center gap-1.5 text-[11px] leading-none text-muted">
<span>{{ $t('chat.attachment.pending') }}</span>
</div>
</div>
<button
type="button"
data-testid="remove-procurement-original-contract"
class="absolute right-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-full text-muted opacity-80 transition hover:bg-surface hover:text-red-500 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400"
:title="t('chat.attachment.remove')"
:aria-label="t('chat.attachment.removeNamed', { name: procurementOriginalContractName })"
@pointerdown.stop
@click.stop="emit('clear-procurement-original-contract')"
>
<X class="h-3.5 w-3.5" />
</button>
</article>
<article
v-for="a in attachments"
:key="a.id"
data-testid="chat-attachment-card"
class="group relative flex h-[68px] w-[250px] shrink-0 items-center gap-3 rounded-xl px-3 py-2.5 transition-colors"
:class="isProcurementContractAgent && a.kind === 'local'
? 'border border-[#9cc7f2] bg-[#eef6ff]'
@@ -572,7 +613,8 @@ watch(
:disabled="isAttachmentRemoveDisabled(a)"
:title="t('chat.attachment.remove')"
:aria-label="t('chat.attachment.removeNamed', { name: getAttachmentName(a) })"
@click="emit('remove-attachment', a.id)"
@pointerdown.stop
@click.stop="emit('remove-attachment', a.id)"
>
<X class="h-3.5 w-3.5" />
</button>
@@ -606,19 +648,6 @@ watch(
@change="emit('procurement-original-contract-selected', $event)"
/>
<div
v-if="isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName"
class="flex flex-wrap gap-2 px-3 pb-1"
>
<div class="flex items-center gap-2 rounded-lg border border-dashed border-[#8db8e6] bg-[#eef6ff] px-2 py-1 text-xs font-semibold text-[#1f5f99]">
<FileText class="h-3.5 w-3.5" />
<span class="max-w-[260px] truncate">{{ $t('chat.procurementContract.originalContractChip', { name: procurementOriginalContractName }) }}</span>
<button type="button" class="text-[#1f5f99] hover:opacity-80" @click="emit('clear-procurement-original-contract')">
<X class="h-3.5 w-3.5" />
</button>
</div>
</div>
<div
v-if="hasProcurementContractAttachment"
class="flex flex-wrap items-center gap-2 px-3 pb-1"
@@ -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) => {
@@ -77,32 +79,45 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
);
/** 同一 Run 只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
/** 同一 Run 或同一次上传批次只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
const current = items[index];
if (!current?.shipping_order_extraction_state) return false;
const payload = current.payload && typeof current.payload === 'object'
? current.payload as Record<string, unknown>
: {};
const identity = String(
const runIdentity = String(
payload.order_extraction_run_no
|| payload.formId
|| current.shipping_order_extraction_state.runNo
|| '',
).trim();
if (!identity) return false;
const batchIdentity = String(
payload.shipping_order_extraction_upload_batch_id
|| current.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
if (!runIdentity && !batchIdentity) return false;
return items.slice(index + 1).some((candidate) => {
if (!candidate?.shipping_order_extraction_state) return false;
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
? candidate.payload as Record<string, unknown>
: {};
const candidateIdentity = String(
const candidateRunIdentity = String(
candidatePayload.order_extraction_run_no
|| candidatePayload.formId
|| candidate.shipping_order_extraction_state.runNo
|| '',
).trim();
return candidateIdentity === identity;
const candidateBatchIdentity = String(
candidatePayload.shipping_order_extraction_upload_batch_id
|| candidate.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
return Boolean(
(batchIdentity && candidateBatchIdentity === batchIdentity)
|| (runIdentity && candidateRunIdentity === runIdentity),
);
});
};
@@ -153,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)"
@@ -161,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"
@@ -1,6 +1,6 @@
<!--
features/chat/components/shipping-review/ReviewActionConfirmDialog.vue
用途:复核页破坏性/不可逆操作的二次确认弹窗(确认建单、重识别、非订单、质量异常、替代 PDF)。
用途:复核页破坏性/不可逆操作的二次确认弹窗(确认建单、重识别、非订单、质量异常)。
依赖:vue-i18n、dialog-overlay / dialog-panel 设计系统样式。
逻辑:ShippingOrderReviewView 以 v-model 控制显隐;质量异常须选原因码,other 时备注必填;
非订单/重识别将说明写入 comment,并附带稳定 reasonCode。
@@ -9,7 +9,7 @@
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
export type ReviewConfirmAction = 'confirm' | 'reparse' | 'non_order' | 'replace' | 'quality_issue';
export type ReviewConfirmAction = 'confirm' | 'reparse' | 'non_order' | 'quality_issue';
/** 确认弹窗提交载荷:稳定原因码 + 自由说明,供后端审计复盘。 */
export type ReviewConfirmPayload = {
@@ -18,6 +18,8 @@ const i18n = createI18n({
line: '第 {index} 行',
buildEligibility: {
overallResult: '整单结果', canBuildYes: '可建单', canBuildNo: '待处理',
manualBuildLabel: '人工建单', autoBuildLabel: '自动建单',
autoBuildYes: '可自动建单', autoBuildNo: '暂不可自动建单',
manualConfirmOnly: '需人工确认', blockReasons: { unknown: '未知阻断' },
routingStatus: { unknown: '未知' },
},
@@ -40,6 +42,49 @@ const eligibility = {
};
describe('ReviewBuildEligibilityDetailsDrawer', () => {
it('separates manual buildability from automatic creation eligibility', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
open: true,
eligibility: {
can_build: true,
can_auto_create: false,
status: 'ready',
failed_gates: ['field_conflicts_resolved'],
issues: [],
line_projections: [],
},
},
global: { plugins: [i18n] },
});
// 关键断言:抽屉不能只写“可建单”而让自动门禁失败看似矛盾。
expect(wrapper.find('[data-testid="review-eligibility-manual-status"]').text()).toContain('可建单');
expect(wrapper.find('[data-testid="review-eligibility-auto-status"]').text()).toContain('暂不可自动建单');
});
it('does not render an empty diagnostic section when there are no diagnostic facts', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
open: true,
eligibility: {
can_build: true,
can_auto_create: false,
status: 'ready',
issues: [],
failed_gates: [],
assessment: { missing_required_fields: [] },
line_projections: [{ line_key: 'L1', line_index: 0, can_build: true }],
},
fieldConflicts: [],
},
global: { plugins: [i18n] },
});
// 关键断言:没有问题明细时不能留下无内容的边框占位区。
expect(wrapper.findAll('section')).toHaveLength(1);
});
it('lists the exact conflicting field, line, sources and values', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
@@ -134,6 +134,15 @@ const unexplainedBlocked = computed(() => Boolean(
&& !props.eligibility.assessment?.missing_required_fields?.length
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
));
/** 有可解释的诊断事实时才渲染中段,避免通过订单留下空白占位框。 */
const hasDiagnosticDetails = computed(() => Boolean(
props.eligibility?.assessment?.missing_required_fields?.length
|| nonConflictIssues.value.length
|| unexplainedBlocked.value
|| props.fieldConflicts?.length
|| hasFieldConflictIssue.value
));
</script>
<template>
@@ -163,12 +172,27 @@ const unexplainedBlocked = computed(() => Boolean(
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
data-testid="review-eligibility-details-overall"
>
<div class="flex items-center justify-between gap-2">
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
{{ eligibility.can_build
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span>
</span>
</div>
<div class="mt-2 flex flex-wrap items-center justify-between gap-2">
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.autoBuildLabel') }}</span>
<span
class="rounded-full px-2 py-0.5 font-medium"
:class="eligibility.can_auto_create
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'"
data-testid="review-eligibility-auto-status"
>
{{ eligibility.can_auto_create
? t('chat.shippingOrderReview.buildEligibility.autoBuildYes')
: t('chat.shippingOrderReview.buildEligibility.autoBuildNo') }}
</span>
</div>
<p v-if="eligibility.can_build && eligibility.can_auto_create === false" class="mt-1">
@@ -183,7 +207,10 @@ const unexplainedBlocked = computed(() => Boolean(
</ul>
</div>
</section>
<section class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40">
<section
v-if="hasDiagnosticDetails"
class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40"
>
<div v-if="eligibility.assessment?.missing_required_fields?.length" class="mt-2">
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.requiredFields') }}</div>
<div class="mt-1 text-rose-700 dark:text-rose-300">
@@ -165,8 +165,8 @@ describe('ReviewBuildEligibilitySummary', () => {
expect(wrapper.text()).not.toContain('can_auto_create');
});
it('hides primary-block under focusBuildability for inventory combo (UI-03)', () => {
// 关键断言:库存阻断由 Gate 卡表达时,资格摘要不得再输出首要阻断标题。
it('keeps primary-block under focusBuildability for inventory combo (UI-03)', () => {
// 关键断言:当前任务卡只承载动作,资格摘要仍保留库存门禁的具体解释。
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
@@ -218,13 +218,14 @@ describe('ReviewBuildEligibilitySummary', () => {
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-build-eligibility-summary"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-exception-nav"]').exists()).toBe(true);
});
it('hides primary-block under focusBuildability for field completeness combo (UI-03)', () => {
// 关键断言:字段阻断组合态下资格卡只保留摘要与异常导航,不输出第二份首要阻断。
it('keeps concrete missing-field diagnostics visible under focusBuildability (UI-03)', () => {
// 关键断言:当前任务卡只承载动作;建单资格卡仍必须给出缺失字段和首要阻断,
// 否则用户无法从泛化 Gate 文案定位订单明细问题。
const wrapper = mount(ReviewBuildEligibilitySummary, {
props: {
eligibility: {
@@ -280,11 +281,13 @@ describe('ReviewBuildEligibilitySummary', () => {
})],
},
});
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(true);
expect(wrapper.text()).toContain('缺失必填:PO');
});
it('hides primary-block when technical_auto_only leaves business gate inactive (UI-03)', () => {
// 关键断言:仅技术 Gate pending 时 focusBuildability=false,资格卡可展示阻断;本测验证开启 focus 时仍唯一。
it('keeps passing eligibility concise when focusBuildability is enabled (UI-03)', () => {
// 关键断言:无阻断时不额外渲染首要阻断;focusBuildability 不影响资格事实展示。
const wrapper = mount(ReviewBuildEligibilitySummary, {
props: {
eligibility: {
@@ -21,8 +21,8 @@ const props = defineProps<{
/** 当前定位异常序号;未定位时为 0。 */
exceptionOrdinal?: number;
/**
* 为 true 时只展示能否建单/自动建单与异常导航,隐藏门禁清单与首要阻断文案,
* 避免与 ProcessGateRecoveryCard 重复表达同一业务阻断。
* 兼容旧调用方的展示偏好。当前任务卡只承载动作,建单门禁仍须完整展示,
* 因此该参数不再隐藏字段级诊断,避免用户只能看到泛化阻断原因。
*/
focusBuildability?: boolean;
}>();
@@ -233,7 +233,7 @@ const gateChecklist = computed(() => {
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
</p>
<ul
v-if="!focusBuildability && gateChecklist.length"
v-if="gateChecklist.length"
class="mt-2 space-y-1 text-xs"
data-testid="review-eligibility-gate-checklist"
>
@@ -285,7 +285,7 @@ const gateChecklist = computed(() => {
<p v-if="conflictFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}:</span>{{ [...new Set(conflictFields)].join('、') }}</p>
</div>
<div
v-if="!focusBuildability && lowConfidenceFields.length"
v-if="lowConfidenceFields.length"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-low-confidence-fields"
>
@@ -298,7 +298,7 @@ const gateChecklist = computed(() => {
</div>
<div
v-if="!focusBuildability && !eligibility.can_build && primaryBlockMessage"
v-if="!eligibility.can_build && primaryBlockMessage"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-eligibility-primary-block"
>
@@ -1,87 +0,0 @@
<!--
features/chat/components/shipping-review/ReviewConversationRetryDrawer.vue
用途:按需展示本次对话级自动推进重试的逐项结果,不占用订单复核主内容。
依赖:vue-i18n、对话级重试 API 返回的摘要和对象结果。
逻辑:仅用户主动从顶栏打开;按结果分类展示,关闭不改变任务真实状态。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
type RetryItem = {
object_type: string;
object_ref: string;
action?: string | null;
outcome: string;
reason_code?: string | null;
};
const props = defineProps<{
open: boolean;
result: {
summary: { total: number; retried: number; skipped: number; failed: number; blocked?: number };
items: RetryItem[];
} | null;
}>();
const emit = defineEmits<{ close: [] }>();
const { t, te } = useI18n();
const items = computed(() => props.result?.items || []);
function itemLabel(item: RetryItem): string {
const code = String(item.reason_code || '').trim();
const key = `chat.shippingOrderReview.conversationRetry.reason.${code}`;
return code && te(key) ? t(key) : outcomeLabel(item.outcome);
}
function outcomeLabel(outcome: string): string {
const key = `chat.shippingOrderReview.conversationRetry.outcome.${String(outcome || '').trim()}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.conversationRetry.outcome.unknown');
}
</script>
<template>
<div
v-if="open && result"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/10"
data-testid="review-conversation-retry-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-[360px] flex-col border-l border-slate-200 bg-white shadow-2xl dark:border-slate-800 dark:bg-slate-900">
<header class="flex items-center justify-between gap-3 border-b border-slate-200 px-3 py-2.5 dark:border-slate-800">
<div class="flex min-w-0 items-center gap-2">
<span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/60 dark:text-amber-200">
<RefreshCw class="h-3.5 w-3.5" />
</span>
<div class="min-w-0">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.conversationRetry.title') }}</h2>
<p class="truncate text-[11px] text-muted">{{ t('chat.shippingOrderReview.conversationRetry.subtitle') }}</p>
</div>
</div>
<button type="button" class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800" data-testid="review-conversation-retry-drawer-close" @click="emit('close')">
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
</header>
<div class="flex flex-wrap gap-1.5 border-b border-slate-200 px-3 py-2 dark:border-slate-800">
<p class="rounded-full bg-emerald-50 px-2 py-1 text-[11px] text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300" data-testid="review-conversation-retry-retried">{{ t('chat.shippingOrderReview.conversationRetry.retried') }} <strong>{{ result.summary.retried }}</strong></p>
<p class="rounded-full bg-slate-100 px-2 py-1 text-[11px] text-slate-600 dark:bg-slate-800 dark:text-slate-300" data-testid="review-conversation-retry-skipped">{{ t('chat.shippingOrderReview.conversationRetry.skipped') }} <strong>{{ result.summary.skipped }}</strong></p>
<p class="rounded-full bg-rose-50 px-2 py-1 text-[11px] text-rose-700 dark:bg-rose-950/40 dark:text-rose-300" data-testid="review-conversation-retry-failed">{{ t('chat.shippingOrderReview.conversationRetry.failed') }} <strong>{{ result.summary.failed }}</strong></p>
<p class="rounded-full bg-violet-50 px-2 py-1 text-[11px] text-violet-700 dark:bg-violet-950/40 dark:text-violet-300" data-testid="review-conversation-retry-blocked">{{ t('chat.shippingOrderReview.conversationRetry.blocked') }} <strong>{{ result.summary.blocked || 0 }}</strong></p>
</div>
<ul class="min-h-0 flex-1 divide-y divide-slate-100 overflow-y-auto dark:divide-slate-800" data-testid="review-conversation-retry-item-list">
<li v-for="item in items" :key="`${item.object_type}:${item.object_ref}`" class="px-3 py-2.5 text-xs">
<div class="flex items-center justify-between gap-2">
<p class="min-w-0 truncate font-medium text-slate-800 dark:text-slate-100">{{ item.object_ref }}</p>
<span
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px]"
:class="item.outcome === 'queued' ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300' : item.outcome === 'needs_human' ? 'bg-amber-50 text-amber-700 dark:bg-amber-950/40 dark:text-amber-300' : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300'"
>{{ outcomeLabel(item.outcome) }}</span>
</div>
<p class="mt-0.5 text-[11px] text-muted">{{ itemLabel(item) }}</p>
</li>
</ul>
</aside>
</div>
</template>
@@ -15,6 +15,39 @@ const i18n = createI18n({
messages: {
'zh-CN': {
'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching': '重新库存匹配',
workspace: {
shippingNotice: {
processGate: {
actionCodes: {
retry_inventory_preparation: '重新获取库存',
},
inventoryActions: {
retryInventoryMatching: '重新库存匹配',
retryInventoryPreparation: '重新获取库存',
},
reasons: {
inventory_shortage_review_required: '存在库存缺口,需要人工处理',
},
},
},
},
chat: {
shippingOrderReview: {
saveOrderAndValidate: '保存订单并校验',
currentProcessing: {
waitingStart: '等待系统启动',
},
currentTask: {
statusRunning: '系统处理中',
nextStepWaitingExternal: '等待外部系统回执,暂不需要人工操作',
},
},
shippingProcessing: {
gateReasons: {
generic: '当前步骤需要人工处理',
},
},
},
},
},
});
@@ -44,6 +77,20 @@ describe('ReviewCurrentProcessingCard', () => {
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
});
it('hides the order-review entry when the user is already in the lifecycle workbench', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
primaryAction: { code: 'open_order_review', i18nKey: 'chat.shippingProcessing.action.open_order_review' },
},
global: { plugins: [i18n] },
});
// 批次中心可以用它进入工作台;工作台当前阶段不能再显示同一个自跳转入口。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
});
it('renders Gate label_key for every primary action presentation', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
@@ -60,18 +107,113 @@ describe('ReviewCurrentProcessingCard', () => {
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新库存匹配');
});
it('renders server-provided recovery actions without duplicating the primary action', async () => {
it('does not render save and validate as a current-task action', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
},
global: { plugins: [i18n] },
});
// 保存订单并校验是底栏唯一动作;未提交校验必须给出明确交接提示,不能显示系统处理中。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('保存订单并校验');
});
it('labels an unqueued automatic Gate as waiting for system start', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'fulfillment_prep',
userStatus: 'running',
gateStatus: 'pending',
},
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('等待系统启动');
});
it('explains external wait without calling it generic system processing', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'upload_complete',
userStatus: 'running',
gateStatus: 'waiting_external',
},
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text())
.toBe('等待外部系统回执,暂不需要人工操作');
});
it('never exposes an internal action code when its presentation is absent', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
primaryAction: { code: 'edit_draft' },
},
global: { plugins: [i18n] },
});
// 回退显示 edit_draft 会泄漏内部能力码;必须 fail-closed 隐藏。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('edit_draft');
});
it('renders a localized reason instead of an internal blocking code in the next step', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
userStatus: 'waiting_human',
blockingReason: { code: 'inventory_shortage_review_required' },
},
global: { plugins: [i18n] },
});
const nextStep = wrapper.get('[data-testid="review-current-task-next-step-text"]').text();
expect(nextStep).toBe('存在库存缺口,需要人工处理');
expect(nextStep).not.toContain('inventory_shortage_review_required');
});
it('hides internal inventory recovery targets while retaining the stable primary action', async () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
userStatus: 'waiting_human',
primaryAction: { code: 'retry_inventory_matching', i18nKey: 'retry_inventory_matching' },
recoveryActions: [{ code: 'retry_inventory_from_preparation' }],
recoveryActions: [{
code: 'retry_inventory_from_preparation',
i18nKey: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching',
}],
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-current-task-recovery-retry_inventory_from_preparation"]').exists()).toBe(true);
expect(wrapper.findAll('button').length).toBe(2);
expect(wrapper.find('[data-testid="review-current-task-recovery-retry_inventory_from_preparation"]').exists()).toBe(false);
expect(wrapper.findAll('button').length).toBe(1);
});
it('emits rematch and RPA refresh as distinct actions for a shortage with an active inventory file', async () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'fulfillment_prep',
userStatus: 'waiting_human',
primaryAction: { code: 'retry_inventory_matching' },
recoveryActions: [{ code: 'retry_inventory_preparation' }],
},
global: { plugins: [i18n] },
});
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
await wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]').trigger('click');
// 两个稳定 action 码分别进入 Gate API:重匹配不可误触 RPA,重新获取库存才会触发 RPA。
expect(wrapper.emitted('action')).toEqual([
['retry_inventory_matching', {}],
['retry_inventory_preparation', {}],
]);
});
});
@@ -8,13 +8,16 @@
-->
<script setup lang="ts">
import { computed } from 'vue';
import { RefreshCw, Crosshair } from 'lucide-vue-next';
import { Bot, RefreshCw, Crosshair } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import type {
ShippingProcessingBlockingReason,
ShippingProcessingPrimaryAction,
} from '@/features/chat/types/shipping.api.types';
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
import { lookupWorkbenchAction, shouldRenderWorkbenchAction } from '@/features/shipping-progress/workbenchActionRegistry';
import { inventoryActionLabelKey, isInternalInventoryAction } from '@/features/shipping-progress/actionPresentation';
const props = defineProps<{
stageCode?: string | null;
@@ -41,14 +44,14 @@ const props = defineProps<{
label_key?: string | null;
parameters?: Record<string, unknown>;
}>;
/** 正式 Gate 原始状态仅用于区分未入队、运行中与外部回执等待;不参与按钮裁决。 */
gateStatus?: string | null;
taskMissing?: boolean;
confirmedTaskId?: number | null;
showAdminDiagnosis?: boolean;
retrying?: boolean;
locating?: boolean;
/** 题7A:自动次数已耗尽但允许人工继续的源;不为空时按钮语义提示「人工继续」+ tooltip 列名。 */
retryExhaustedSources?: string[] | null;
/** 仅 UI 展示的 running 文案(如 inventory_preparation 正在跑时主卡按钮 loading 附加信息)。 */
automation?: {
status?: string | null;
@@ -103,12 +106,16 @@ const statusLabel = computed(() => {
if (props.taskMissing) {
return t('chat.shippingOrderReview.currentProcessing.taskMissing');
}
if (s === 'running' && String(props.gateStatus || '').trim().toLowerCase() === 'pending') {
return t('chat.shippingOrderReview.currentProcessing.waitingStart');
}
if (!s) return t('chat.shippingOrderReview.currentProcessing.statusIdle');
return map[s] ?? t('chat.shippingOrderReview.currentProcessing.statusIdle');
});
/**
* 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason,否则按 user_status 给系统态文案。
* 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason 的统一 i18n 映射,
* 否则按 user_status 给系统态文案;禁止将后端内部原因码直接展示给用户。
*/
const nextStepText = computed(() => {
const safeMessage = (value: unknown): string => {
@@ -136,8 +143,27 @@ const nextStepText = computed(() => {
if (i18nKey && te(i18nKey)) {
return t(i18nKey);
}
// i18n 键缺失时回落为 code(不裸露给普通用户,最终 QA 期间应全部补齐)
return safeMessage(br.code) || t('chat.shippingOrderReview.currentTask.nextStepUnknown');
return resolveGateReasonLabel(br.code, { t, te })
|| t('chat.shippingOrderReview.currentTask.nextStepUnknown');
}
// 建单前订单冻结校验尚未提交时,明确告诉用户下一步是保存并校验。
// 保存是底栏唯一的表单提交入口,不升级为右栏 CTA;该分支也兼容历史响应
// 仍携带 validate 的情形,避免「待人工」与「无需操作」产生语义矛盾。
if (
String(props.stageCode || '').trim() === 'order_review'
&& !props.blockingReason
&& (
String(props.primaryAction?.code || '').trim() === 'validate'
|| String(props.userStatus || '').trim() === 'waiting_human'
)
) {
return t('chat.shippingOrderReview.saveOrderAndValidate');
}
if (
String(props.userStatus || '').trim() === 'running'
&& String(props.gateStatus || '').trim().toLowerCase() === 'waiting_external'
) {
return t('chat.shippingOrderReview.currentTask.nextStepWaitingExternal');
}
// 2) 无阻断时,按 user_status 给系统说明文案
const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | '';
@@ -168,9 +194,33 @@ const showNextStep = computed(() => {
return !['completed', 'cancelled'].includes(status);
});
/**
* 判断当前工作台是否应隐藏后端下发的纯导航动作。
* 批次中心可用它打开工作台;进入工作台后必须复用注册表规则,避免当前阶段再次显示
* 「进入订单复核」或「编辑正式任务」等自跳转入口。
*/
function isHiddenWorkbenchNavigationAction(code: string): boolean {
const entry = lookupWorkbenchAction(code);
return Boolean(entry && !shouldRenderWorkbenchAction(entry, {
actionsExecutable: true,
surface: 'review',
actionCode: code,
}));
}
/**
* 当前任务卡只承载正式 Gate 的可执行业务动作。
*
* 草稿编辑/建草稿是页面能力,保存校验是底栏唯一提交;它们即使出现在历史响应中,
* 也不能升级为右栏 CTA,更不能因缺失文案泄漏内部动作码。
*/
function isNonTaskCapabilityAction(code: string): boolean {
return new Set(['edit_draft', 'create_draft', 'validate']).has(code.trim().toLowerCase());
}
/**
* 业务动作按钮:后端确认 retryable=true → 主按钮为「重试」;
* 否则若 primary_action.code 非 retry → 用 primary_action.code + i18n_key 渲染对应人工动作(进入复核/确认客户等)。
* 否则若 primary_action.code 非 retry 且不是工作台内自跳转 → 渲染对应人工动作。
*/
const showBusinessAction = computed(() => {
if (props.loading) return false;
@@ -180,21 +230,23 @@ const showBusinessAction = computed(() => {
if (props.userStatus === 'running') return false;
if (props.retryable) return true;
const code = String(props.primaryAction?.code || '').trim();
if (isInternalInventoryAction(code)) return false;
if (!code) return false;
if (isNonTaskCapabilityAction(code)) return false;
if (isHiddenWorkbenchNavigationAction(code)) return false;
// retry 仅当 retryable=true 时展示(避免按钮闪烁矛盾)
if (code === 'retry') return false;
return true;
});
const businessActionLabel = computed(() => {
if (props.retryable) {
if ((props.retryExhaustedSources || []).length > 0) {
return t('chat.shippingOrderReview.currentTask.actionRetryWithExhausted');
}
return t('chat.shippingOrderReview.currentTask.actionRetry');
}
const code = String(props.primaryAction?.code || '').trim();
const inventoryKey = inventoryActionLabelKey(code);
if (inventoryKey && te(inventoryKey)) return t(inventoryKey);
if (props.retryable) return t('chat.shippingOrderReview.currentTask.actionRetry');
const pa = props.primaryAction;
if (!pa) return '';
if (isNonTaskCapabilityAction(String(pa.code || ''))) return '';
// Gate action presentation uses label_key; normalize it at the shared card boundary
// so every gate renders its business label instead of exposing the action code.
const i18nKey = String(
@@ -210,17 +262,11 @@ const businessActionLabel = computed(() => {
if (te(legacyKey)) {
return t(legacyKey);
}
return pa.code;
// 当前任务按钮没有受控文案时 fail-closed,禁止泄漏内部 action code。
return '';
});
/** 题7A:按钮 tooltip(exhausted_sources 列表与文案)。 */
const businessActionTitle = computed(() => {
const exhausted = Array.isArray(props.retryExhaustedSources) ? props.retryExhaustedSources.filter(Boolean) : [];
if (exhausted.length > 0) {
return t('chat.shippingOrderReview.currentTask.actionRetryExhaustedTooltip', {
sources: exhausted.join(', '),
});
}
const retryingFlag = Boolean(props.retrying);
if (retryingFlag) {
return t('chat.shippingOrderReview.currentTask.actionRetryRunningTooltip');
@@ -229,18 +275,28 @@ const businessActionTitle = computed(() => {
});
const actionIsRetry = computed(() => Boolean(props.retryable) || String(props.primaryAction?.code || '') === 'retry');
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
const code = String(action.code || '').trim();
return code && code !== String(props.primaryAction?.code || '').trim();
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
if (code === String(props.primaryAction?.code || '').trim()) return false;
const key = String(
action.i18nKey
|| action.label_key
|| `workspace.shippingNotice.processGate.actionCodes.${code}`,
).trim();
return Boolean(key && te(key));
}));
function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): string {
const inventoryKey = inventoryActionLabelKey(action.code);
if (inventoryKey && te(inventoryKey)) return t(inventoryKey);
const key = String(
action.i18nKey
|| action.label_key
|| `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
).trim();
return key && te(key) ? t(key) : action.code;
return key && te(key) ? t(key) : '';
}
function handleBusinessActionClick() {
@@ -383,8 +439,9 @@ type ReviewCurrentUserStatus =
:title="businessActionTitle"
@click="handleBusinessActionClick"
>
<Bot v-if="actionIsInventoryRpa" class="h-3.5 w-3.5" />
<RefreshCw
v-if="actionIsRetry"
v-else-if="actionIsRetry"
class="h-3.5 w-3.5"
:class="{ 'animate-spin': Boolean(retrying) }"
/>
@@ -246,6 +246,21 @@ describe('ReviewDocumentEvidenceDrawer', () => {
expect(wrapper.find('[data-testid="review-evidence-no-bbox"]').text()).toContain('10 EA');
});
it('renders email evidence through the safe HTML preview URL', () => {
const wrapper = mountDrawer({
emailPreview: {
document_id: 9,
filename: 'source.eml',
text: 'fallback text',
render_kind: 'safe_html',
preview_url: '/email-preview?token=one-shot',
},
});
expect(wrapper.find('[data-testid="review-email-evidence-html"]').attributes('src'))
.toBe('/email-preview?token=one-shot');
expect(wrapper.find('[data-testid="review-email-evidence-preview"]').exists()).toBe(false);
});
it('does not render when closed', () => {
const wrapper = mountDrawer({ open: false });
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
@@ -44,6 +44,7 @@ const props = defineProps<{
docked: boolean;
floatSide: 'right' | 'left';
src: string;
emailPreview?: { document_id: number; filename: string; text: string; render_kind: 'safe_html' | 'text'; preview_url?: string } | null;
evidence: ShippingOrderReviewEvidence | null;
evidenceList: ShippingOrderReviewEvidence[];
fieldLabel?: string;
@@ -729,8 +730,20 @@ onBeforeUnmount(() => {
</div>
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
<iframe
v-if="emailPreview?.render_kind === 'safe_html' && emailPreview.preview_url"
:src="emailPreview.preview_url"
sandbox=""
referrerpolicy="no-referrer"
:title="fieldLabel || t('chat.shippingOrderReview.evidenceDrawer.title')"
class="min-h-0 h-full w-full border-0 bg-white"
data-testid="review-email-evidence-html"
/>
<div v-else-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"
@@ -20,6 +20,13 @@ const i18n = createI18n({
unnamedDocument: '未命名 PDF',
documentNavigation: '导航',
caseStatuses: { draft: '草稿', unknown: '未知' },
lifecycle: {
stages: {
order_review: '订单复核',
fulfillment_prep: '通知准备',
upload_complete: '通知完成',
},
},
otNav: {
listTitle: '订单列表 · {count}',
searchPlaceholder: '搜索',
@@ -71,16 +78,66 @@ describe('ReviewDocumentNavigation', () => {
expect(wrapper.find('[data-testid="review-document-navigation"]').exists()).toBe(false);
});
it('uses top tabs for 2–4 OTs', () => {
const wrapper = mountNav(3, 'tabs');
it('uses compact top tabs for 2–4 OTs', () => {
const wrapper = mountNav(3);
expect(wrapper.find('[data-testid="review-doc-nav-tabs"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(false);
expect(wrapper.attributes('data-nav-mode')).toBe('tabs');
});
it('uses sidebar list for 5–20 OTs', () => {
const wrapper = mountNav(8, 'sidebar');
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(true);
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
expect(wrapper.classes()).toContain('sticky');
});
it('keeps the sidebar collapse rail and the explicitly forced sidebar mode', async () => {
const wrapper = mount(ReviewDocumentNavigation, {
props: {
items: items(8),
activeCaseNo: 'C-1',
navAriaLabel: 'nav',
forceMode: 'sidebar',
initiallyCollapsed: true,
},
global: { plugins: [i18n] },
});
// 关键断言:收起后仍保留文件身份摘要,不能退化成无法识别的纯编号轨。
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('f2');
await wrapper.get('[data-testid="review-doc-nav-collapse"]').trigger('click');
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('f2.pdf');
expect(wrapper.get('[data-testid="review-doc-nav-list"]').attributes('data-collapsed')).toBe('false');
});
it('keeps the file name as the queue row title while projecting PO, lifecycle stage and status', () => {
const rows = items(5);
rows[1] = {
...rows[1],
file_name: 'purchase-order-2.pdf',
po_number: 'PO-002',
lifecycle_stage: 'fulfillment_prep',
status: 'processing',
};
const wrapper = mount(ReviewDocumentNavigation, {
props: {
items: rows,
activeCaseNo: 'C-1',
navAriaLabel: 'nav',
forceMode: 'sidebar',
},
global: { plugins: [i18n] },
});
// 文件导航先展示可识别的文件名;PO/阶段/状态仍都来自后端队列 DTO。
const queueRow = wrapper.get('[data-testid="review-doc-nav-C-2"]');
expect(queueRow.find('.font-medium').text()).toBe('purchase-order-2.pdf');
expect(queueRow.text()).toContain('PO-002');
expect(queueRow.text()).toContain('通知准备');
// 关键断言:队列行内容必须是实际 DOM 子节点,不能被原生 template 隐藏成空白框。
expect(queueRow.find('template').exists()).toBe(false);
});
it('shows search for 20+ OTs', () => {
@@ -94,4 +151,25 @@ describe('ReviewDocumentNavigation', () => {
await wrapper.get('[data-testid="review-doc-nav-C-2"]').trigger('click');
expect(wrapper.emitted('select')?.[0]).toEqual(['C-2']);
});
it('keeps backend lifecycle stage visible in tabs and narrow queue', async () => {
const rows = items(2);
rows[1] = { ...rows[1], lifecycle_stage: 'fulfillment_prep', status: 'processing' };
const tabs = mount(ReviewDocumentNavigation, {
props: { items: rows, activeCaseNo: 'C-1', navAriaLabel: 'nav', forceMode: 'tabs' },
global: { plugins: [i18n] },
});
const narrow = mount(ReviewDocumentNavigation, {
props: { items: rows, activeCaseNo: 'C-1', navAriaLabel: 'nav', forceMode: 'narrow' },
global: { plugins: [i18n] },
attachTo: document.body,
});
// 关键断言:文件队列在任何响应式形态都只投影后端已裁决阶段。
expect(tabs.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('通知准备');
await narrow.get('[data-testid="review-doc-nav-narrow-trigger"]').trigger('click');
// 窄屏抽屉通过 Teleport 挂到 body,断言真实可见容器而非组件根节点。
expect(document.body.querySelector('[data-testid="review-doc-nav-C-2"]')?.textContent).toContain('通知准备');
narrow.unmount();
});
});
@@ -1,8 +1,8 @@
<!--
features/chat/components/shipping-review/ReviewDocumentNavigation.vue
用途:订单处理工作台 OT/PDF 导航(按数量响应式:隐藏 / 顶栏标签 / 左侧列表 / 窄屏抽屉)。
用途:订单处理工作台 OT/PDF 导航(按数量响应式:隐藏 / 紧凑标签 / 左侧列表 / 窄屏抽屉)。
依赖:vue-i18n、lucide-vue-next。
逻辑:1 份隐藏;2–4 顶栏;≥5 左侧列表(可收起);20+ 搜索过滤;窄屏「订单 i/n」抽屉。
逻辑:1 份隐藏;桌面端 2–4 紧凑标签、5–20 左侧列表(可收起);20+ 搜索过滤;窄屏「订单 i/n」抽屉。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
@@ -26,8 +26,12 @@ export type ReviewDocumentNavItem = {
po_number?: string | null;
customer_name?: string | null;
stage_label?: string | null;
/** 队列接口下发的生命周期码;仅用于本地化展示,不参与阶段裁决。 */
lifecycle_stage?: ReviewLifecycleStageCode | null;
};
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
const props = defineProps<{
@@ -44,6 +48,7 @@ const props = defineProps<{
const emit = defineEmits<{
select: [caseNo: string];
'mode-change': [mode: ReviewDocumentNavMode];
'collapse-change': [collapsed: boolean];
}>();
const { t, te } = useI18n();
@@ -82,12 +87,14 @@ const mode = computed<ReviewDocumentNavMode>(() => {
const count = props.items.length;
if (count <= 1) return 'hidden';
if (isNarrow.value) return 'narrow';
// 多文件先选文件、后查看阶段;2–4 用紧凑标签,5+ 才占用左侧工作列。
if (count <= 4) return 'tabs';
if (count <= 20) return 'sidebar';
return 'sidebar_search';
});
watch(mode, (value) => emit('mode-change', value), { immediate: true });
watch(collapsed, (value) => emit('collapse-change', value), { immediate: true });
const activeIndex = computed(() => {
const idx = props.items.findIndex((item) => item.case_no === props.activeCaseNo);
@@ -102,6 +109,14 @@ function caseStatusLabel(status: string): string {
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
}
/** 后端阶段码只做 i18n 投影;缺失时保留空白,禁止按 Case 状态补造阶段。 */
function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
const code = String(item.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(code)) return null;
const key = `chat.shippingOrderReview.lifecycle.stages.${code}`;
return te(key) ? t(key) : null;
}
/**
* 导航状态图标语义。
*/
@@ -168,7 +183,7 @@ function onSelect(caseNo: string) {
? 'rounded-xl border border-slate-200 bg-white p-2 shadow-sm dark:border-slate-800 dark:bg-slate-900'
: mode === 'narrow'
? ''
: 'sticky top-3 flex max-h-[calc(100vh-6rem)] w-full shrink-0 flex-col rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900 lg:w-64'"
: ['sticky top-3 flex max-h-[calc(100vh-6rem)] w-full shrink-0 flex-col rounded-xl border border-slate-200 bg-white shadow-sm transition-[width] duration-200 dark:border-slate-800 dark:bg-slate-900', collapsed ? 'lg:w-20' : 'lg:w-64']"
>
<!-- 2–4:顶部标签 -->
<div
@@ -208,11 +223,15 @@ function onSelect(caseNo: string) {
class="h-3 w-3 shrink-0 text-slate-400"
aria-hidden="true"
/>
<span class="truncate">{{ item.po_number || item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
<span class="truncate">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
</span>
<span class="truncate text-[10px] text-slate-500 dark:text-slate-400">
{{ item.customer_name || caseStatusLabel(item.status) }}
<template v-if="item.stage_label"> · {{ item.stage_label }}</template>
{{ [
item.po_number,
lifecycleStageLabel(item),
item.stage_label,
item.customer_name || caseStatusLabel(item.status),
].filter(Boolean).join(' · ') }}
</span>
</button>
</div>
@@ -227,6 +246,7 @@ function onSelect(caseNo: string) {
type="button"
class="rounded p-1 text-muted hover:bg-slate-100 dark:hover:bg-slate-800"
data-testid="review-doc-nav-collapse"
:aria-label="collapsed ? t('chat.shippingOrderReview.documentNavigation') : t('chat.shippingOrderReview.documentNavigation')"
@click="collapsed = !collapsed"
>
<ChevronLeft
@@ -270,6 +290,7 @@ function onSelect(caseNo: string) {
<div
class="min-h-0 flex-1 overflow-y-auto p-1.5"
data-testid="review-doc-nav-list"
:data-collapsed="collapsed"
>
<button
v-for="(item, index) in (collapsed ? items : filteredItems)"
@@ -287,9 +308,13 @@ function onSelect(caseNo: string) {
>
<span
v-if="collapsed"
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-slate-100 text-[10px] font-semibold dark:bg-slate-800"
class="flex h-12 w-full min-w-0 flex-col items-center justify-center rounded-md bg-slate-100 px-1 text-[10px] dark:bg-slate-800"
:title="`${index + 1}. ${item.file_name || item.case_no}`"
>
{{ index + 1 }}
<span class="font-semibold">{{ index + 1 }}</span>
<span class="mt-0.5 w-full truncate text-center text-[9px] font-medium text-slate-600 dark:text-slate-300">
{{ (item.file_name || item.case_no).replace(/\.[^.]+$/, '').slice(0, 7) }}
</span>
</span>
<template v-else>
<TriangleAlert
@@ -310,10 +335,14 @@ function onSelect(caseNo: string) {
/>
<span class="min-w-0 flex-1">
<span class="block truncate font-medium text-primary">
{{ item.po_number || item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}
{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}
</span>
<span class="block truncate text-[10px] text-muted">
{{ item.customer_name || caseStatusLabel(item.status) }}
{{ [
item.po_number,
lifecycleStageLabel(item),
item.customer_name || caseStatusLabel(item.status),
].filter(Boolean).join(' · ') }}
</span>
</span>
</template>
@@ -367,7 +396,9 @@ function onSelect(caseNo: string) {
@click="onSelect(item.case_no)"
>
<span class="font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
<span class="text-[10px] text-muted">{{ caseStatusLabel(item.status) }}</span>
<span class="text-[10px] text-muted">
{{ [lifecycleStageLabel(item), caseStatusLabel(item.status)].filter(Boolean).join(' · ') }}
</span>
</button>
</div>
</aside>
@@ -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(', ') }) }}
@@ -0,0 +1,87 @@
/**
* features/chat/components/shipping-review/ReviewFieldConflictPanel.spec.ts
* 用途:验证过期字段冲突卡在服务端返回 404 后会刷新,而不会保留为可再次提交的错误入口。
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewFieldConflictPanel。
* 逻辑:模拟并发刷新已消耗冲突,组件必须通知父工作台重取 Case 最新投影。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it, vi } from 'vitest';
import { BusinessError } from '@/shared/api/client';
import ReviewFieldConflictPanel from './ReviewFieldConflictPanel.vue';
const { resolveFieldConflict } = vi.hoisted(() => ({
resolveFieldConflict: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
resolveWorkspaceShippingOrderReviewFieldConflict: resolveFieldConflict,
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: { shippingOrderReview: {
fieldConflict: {
title: '字段冲突 {count} 项', subtitle: '请选择值', focusEvidence: '定位证据',
evidenceIssueTitle: '证据待确认({count})', evidenceIssueSubtitle: '请核对证据',
scope: { header: '订单头', line: '订单明细' },
customValue: '手工值', customPlaceholder: '请输入', submitCustom: '确认手工值',
resolveReason: '人工裁决', resolveFailed: '提交失败', resolveSuccess: '已处理',
fields: { part_number: '料号' }, reasons: { field_conflict: '字段冲突' },
evidenceRole: {}, optionLabel: '候选 {index}', adoptOption: '采用候选值',
},
resume: { autoCreated: '已自动建单', waitingManualConfirm: '待人工确认' },
} },
},
},
});
describe('ReviewFieldConflictPanel', () => {
it('separates evidence gaps from value conflicts and does not offer a duplicate value decision', () => {
const wrapper = mount(ReviewFieldConflictPanel, {
props: {
caseNo: 'SORC-1', draftVersion: 1, editable: true,
conflicts: [],
evidenceIssues: [{
conflict_key: '-1:reservation_id', field_code: 'reservation_id', line_index: null, scope: 'header',
reason: 'evidence_missing', options: [],
}],
},
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-evidence-issue-panel"]').text()).toContain('订单头 · reservation_id');
expect(wrapper.find('[data-testid="review-field-conflict-custom-toggle"]').exists()).toBe(false);
});
it('refreshes the case when confirming a stale manual value returns conflict-not-found', async () => {
resolveFieldConflict.mockRejectedValueOnce(new BusinessError({
message: 'Field conflict not found',
code: 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
status: 404,
}));
const wrapper = mount(ReviewFieldConflictPanel, {
props: {
caseNo: 'SORC-1', draftVersion: 1, editable: true,
conflicts: [{
conflict_key: '-1:part_number', field_code: 'part_number', line_index: -1,
reason: 'field_conflict', options: [],
}],
},
global: { plugins: [i18n] },
});
await wrapper.get('[data-testid="review-field-conflict-custom-toggle"]').trigger('click');
await wrapper.get('[data-testid="review-field-conflict-custom-input"]').setValue('PN-001');
await wrapper.get('[data-testid="review-field-conflict-custom-submit"]').trigger('click');
await vi.waitFor(() => expect(wrapper.emitted('refreshed')).toHaveLength(1));
// 关键断言:404 代表页面投影过期,父工作台会加载最新 Case 并移除这张卡。
expect(resolveFieldConflict).toHaveBeenCalledWith('SORC-1', '-1:part_number', expect.objectContaining({
resolution: 'custom', custom_value: 'PN-001', expected_draft_version: 1,
}));
});
});
@@ -18,6 +18,7 @@ const props = defineProps<{
caseNo: string;
draftVersion: number | null | undefined;
conflicts: ShippingOrderReviewFieldConflict[] | null | undefined;
evidenceIssues?: ShippingOrderReviewFieldConflict[] | null | undefined;
editable: boolean;
}>();
@@ -33,6 +34,7 @@ const customOpenKey = ref<string | null>(null);
const customValue = ref('');
const openConflicts = computed(() => props.conflicts || []);
const openEvidenceIssues = computed(() => props.evidenceIssues || []);
/**
* 字段编码本地化标签(无文案时回退 field_code)。
@@ -50,6 +52,17 @@ function reasonLabel(reason: string): string {
return te(key) ? t(key) : reason;
}
/**
* 区分订单头与明细字段;同名字段不能被误读成同一份业务值。
*/
function scopeLabel(scope: string | null | undefined): string {
const code = ['header', 'line', 'line_unassigned', 'unscoped'].includes(String(scope || ''))
? String(scope)
: 'unscoped';
const key = `chat.shippingOrderReview.fieldConflict.scope.${code}`;
return t(key);
}
/**
* 证据角色本地化(主 PDF / 辅助 / 邮件正文)。
*/
@@ -105,6 +118,12 @@ async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionInd
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
if (error instanceof BusinessError && error.code === 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND') {
// 冲突已被其他刷新/裁决消耗:以服务端最新 Case 为准,撤掉当前过期卡片。
msg.info(resolveLocalizedErrorMessage(error.code, error.message));
emit('refreshed');
return;
}
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
@@ -146,6 +165,12 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
if (error instanceof BusinessError && error.code === 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND') {
// 与采用候选值保持同一 stale-data 恢复路径,禁止把已解决冲突留在页面上。
msg.info(resolveLocalizedErrorMessage(error.code, error.message));
emit('refreshed');
return;
}
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
@@ -158,11 +183,11 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
<template>
<section
v-if="openConflicts.length"
v-if="openConflicts.length || openEvidenceIssues.length"
class="rounded-xl border border-rose-200 bg-rose-50/70 p-3 shadow-sm dark:border-rose-900 dark:bg-rose-950/40"
data-testid="review-field-conflict-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<header v-if="openConflicts.length" class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-rose-950 dark:text-rose-50">
{{ t('chat.shippingOrderReview.fieldConflict.title', { count: openConflicts.length }) }}
@@ -264,5 +289,38 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
</div>
</li>
</ul>
<div
v-if="openEvidenceIssues.length"
class="mt-3 rounded-lg border border-amber-200 bg-amber-50/80 p-2.5 dark:border-amber-900 dark:bg-amber-950/30"
data-testid="review-evidence-issue-panel"
>
<h2 class="text-sm font-semibold text-amber-950 dark:text-amber-50">
{{ t('chat.shippingOrderReview.fieldConflict.evidenceIssueTitle', { count: openEvidenceIssues.length }) }}
</h2>
<p class="mt-0.5 text-xs text-amber-800 dark:text-amber-200">
{{ t('chat.shippingOrderReview.fieldConflict.evidenceIssueSubtitle') }}
</p>
<ul class="mt-2 space-y-1.5">
<li
v-for="issue in openEvidenceIssues"
:key="`${issue.conflict_key}-${issue.reason}`"
class="flex flex-wrap items-center justify-between gap-2 rounded border border-amber-200 bg-white/95 px-2.5 py-2 text-xs dark:border-amber-900 dark:bg-slate-900"
>
<span class="text-amber-950 dark:text-amber-50">
<span class="text-muted">{{ scopeLabel(issue.scope) }} · </span>
<span class="font-mono">{{ fieldLabel(issue.field_code) }}</span>
</span>
<button
type="button"
class="text-[11px] text-primary underline-offset-2 hover:underline"
data-testid="review-evidence-issue-focus"
@click="onFocus(issue)"
>
{{ t('chat.shippingOrderReview.fieldConflict.focusEvidence') }}
</button>
</li>
</ul>
</div>
</section>
</template>
@@ -0,0 +1,150 @@
/**
* features/chat/components/shipping-review/ReviewIntakeParsePanel.spec.ts
* 用途:锁定接收解析工作面只展示当前 Case 已授权的邮件正文与附件预览。
* 依赖:Vitest、Vue Test Utils、vue-i18n、ReviewIntakeParsePanel。
* 逻辑:PDF 才允许嵌入预览;非 PDF 明确降级;所有处置仅向父级发出意图。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import ReviewIntakeParsePanel from './ReviewIntakeParsePanel.vue';
import type { ShippingOrderReviewIntakeParseContext } from '@/features/chat/types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
lifecycle: {
intakeParse: {
title: '接收解析',
email: '邮件正文',
noEmail: '无邮件上下文',
attachment: '当前附件',
fileName: '文件名',
fileType: '文件类型',
preview: '附件预览',
loadPreview: '加载附件预览',
previewUnsupported: '当前附件不支持预览',
loadFailed: '接收解析上下文加载失败',
retry: '重试',
loading: '正在加载接收解析上下文',
},
},
markNonOrder: '标记为非订单',
markQualityIssue: '文件质量异常',
reparse: '重新识别此 PDF',
},
},
},
},
});
const emailPdfContext: ShippingOrderReviewIntakeParseContext = {
case_no: 'CASE-1',
attachment: {
document_id: 11,
filename: 'current.pdf',
mime_type: 'application/pdf',
preview_kind: 'pdf',
},
email: {
document_id: 7,
filename: 'source.eml',
render_kind: 'text',
text: 'approved body text',
},
};
const unsupportedContext: ShippingOrderReviewIntakeParseContext = {
...emailPdfContext,
attachment: {
document_id: 12,
filename: 'source.xlsx',
mime_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
preview_kind: 'unsupported',
},
email: null,
};
function mountPanel(props: Record<string, unknown>) {
return mount(ReviewIntakeParsePanel, {
props: {
loading: false,
loadFailed: false,
previewUrl: null,
previewLoading: false,
...props,
},
global: { plugins: [i18n] },
});
}
describe('ReviewIntakeParsePanel', () => {
it('renders EML text and only the selected attachment preview', () => {
const wrapper = mountPanel({ context: emailPdfContext, previewUrl: 'blob:pdf' });
// 关键断言:邮件正文与当前附件来自同一个受控 Case context,PDF 才嵌入预览。
expect(wrapper.get('[data-testid="intake-parse-email-body"]').text()).toContain('approved body text');
expect(wrapper.get('[data-testid="intake-parse-attachment-preview"] iframe').attributes('src')).toBe('blob:pdf');
});
it('uses a compact attachment heading without duplicate metadata', () => {
const wrapper = mountPanel({ context: emailPdfContext, previewUrl: 'blob:pdf' });
// 关键断言:文件名与当前附件合并展示,MIME 类型不再占用预览空间。
expect(wrapper.get('[data-testid="intake-parse-attachment-heading"]').text()).toContain('当前附件');
expect(wrapper.get('[data-testid="intake-parse-attachment-heading"]').text()).toContain('current.pdf');
expect(wrapper.text()).not.toContain('文件类型');
});
it('loads isolated EML HTML from the backend preview URL inside a sandboxed iframe', () => {
const wrapper = mountPanel({
context: {
...emailPdfContext,
email: {
...emailPdfContext.email!,
render_kind: 'safe_html',
preview_url: '/api/workspace/shipping-notice/order-review-cases/CASE-1/email-preview?preview_token=single-use',
},
},
});
// 关键断言:HTML 不得通过 srcdoc 注入工作台 DOM,必须由受控 URL 在无脚本 iframe 中读取。
const frame = wrapper.get('[data-testid="intake-parse-email-html"]');
expect(frame.attributes('sandbox')).toBeDefined();
expect(frame.attributes('src')).toContain('preview_token=single-use');
expect(frame.attributes('srcdoc')).toBeUndefined();
expect(wrapper.find('[data-testid="intake-parse-email-body"]').exists()).toBe(false);
});
it('does not render a PDF frame for an unsupported attachment', () => {
const wrapper = mountPanel({ context: unsupportedContext });
// 关键断言:非 PDF 不得退化为 iframe,必须明确告知不可预览。
expect(wrapper.find('[data-testid="intake-parse-attachment-preview"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="intake-parse-preview-unsupported"]').exists()).toBe(true);
expect(wrapper.get('[data-testid="intake-parse-no-email"]').text()).toContain('无邮件上下文');
});
it('does not render parse disposition controls inside the scrolling intake panel', () => {
const wrapper = mountPanel({
context: emailPdfContext,
});
// 关键断言:按钮由父级固定底栏统一承载,面板滚动时不得随内容离开视口。
expect(wrapper.find('[data-testid="intake-parse-disposition-actions"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="intake-parse-mark-non-order"]').exists()).toBe(false);
});
it('does not render deprecated parse disposition controls inside the scrolling panel', () => {
const wrapper = mountPanel({
context: emailPdfContext,
});
// 关键断言:处置由固定底栏承载,滚动内容区不得遗留重复入口。
expect(wrapper.find('[data-testid="intake-parse-reparse"]').exists()).toBe(false);
});
});
@@ -0,0 +1,146 @@
<!--
features/chat/components/shipping-review/ReviewIntakeParsePanel.vue
用途:在接收解析阶段展示当前 Case 已授权的邮件正文、当前附件及安全预览。
依赖:vue、vue-i18n、ShippingOrderReviewIntakeParseContext。
逻辑:只消费父级按 Case 获取的受控上下文;仅 PDF 可请求/渲染 iframe;处置操作只 emit,
由父页沿用既有确认弹窗和 Case 命令。
-->
<script setup lang="ts">
import { watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewIntakeParseContext } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
context: ShippingOrderReviewIntakeParseContext | null;
loading: boolean;
loadFailed: boolean;
previewUrl: string | null;
previewLoading: boolean;
}>();
const emit = defineEmits<{
'retry-context': [];
'load-preview': [];
}>();
const { t } = useI18n();
/**
* 当前附件为 PDF 且尚无受控 Blob 时,通知父级使用当前 Case 加载预览。
* 仅 Case context 改变时触发,禁止对不受支持文件发起预览请求。
*/
watch(
() => props.context,
(context) => {
if (context?.attachment.preview_kind === 'pdf' && !props.previewUrl) {
emit('load-preview');
}
},
{ immediate: true },
);
</script>
<template>
<section
class="space-y-4"
data-testid="intake-parse-panel"
>
<div
v-if="loading"
class="rounded-xl border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-600 dark:border-slate-700 dark:bg-slate-900/40 dark:text-slate-300"
data-testid="intake-parse-loading"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loading') }}
</div>
<div
v-else-if="loadFailed"
class="rounded-xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-900 dark:bg-rose-950/40 dark:text-rose-100"
data-testid="intake-parse-load-failed"
>
<p>{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loadFailed') }}</p>
<button
type="button"
class="mt-3 rounded border border-rose-300 px-2.5 py-1 text-xs hover:bg-rose-100 dark:border-rose-800 dark:hover:bg-rose-950"
data-testid="intake-parse-retry-context"
@click="emit('retry-context')"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.retry') }}
</button>
</div>
<template v-else-if="context">
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.email') }}</h2>
<template v-if="context.email">
<p class="mt-1 text-xs text-slate-500">{{ context.email.filename }}</p>
<iframe
v-if="context.email.render_kind === 'safe_html' && context.email.preview_url"
:src="context.email.preview_url"
sandbox=""
referrerpolicy="no-referrer"
:title="t('chat.shippingOrderReview.lifecycle.intakeParse.emailPreviewTitle')"
class="mt-3 h-72 w-full rounded border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-950"
data-testid="intake-parse-email-html"
/>
<pre
v-else
class="mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-slate-50 p-3 text-xs text-slate-700 dark:bg-slate-950/50 dark:text-slate-200"
data-testid="intake-parse-email-body"
>{{ context.email.text }}</pre>
</template>
<p
v-else
class="mt-2 text-sm text-slate-500"
data-testid="intake-parse-no-email"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.noEmail') }}
</p>
</section>
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
<h2 class="text-sm font-semibold" data-testid="intake-parse-attachment-heading">
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.attachment') }} ·
<span class="font-normal text-slate-500 dark:text-slate-400">{{ context.attachment.filename }}</span>
</h2>
<div
v-if="context.attachment.preview_kind === 'pdf'"
class="mt-3"
data-testid="intake-parse-attachment-preview"
>
<p
v-if="previewLoading"
class="mt-2 text-sm text-slate-500"
data-testid="intake-parse-preview-loading"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewLoading') }}
</p>
<iframe
v-else-if="previewUrl"
:src="previewUrl"
:title="context.attachment.filename"
class="mt-2 h-[32rem] w-full rounded border border-slate-200 dark:border-slate-700"
/>
<button
v-else
type="button"
class="mt-2 rounded border border-slate-300 px-2.5 py-1 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="intake-parse-load-preview"
@click="emit('load-preview')"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loadPreview') }}
</button>
</div>
<p
v-else
class="mt-4 rounded bg-slate-50 p-3 text-sm text-slate-500 dark:bg-slate-950/50"
data-testid="intake-parse-preview-unsupported"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewUnsupported') }}
</p>
</section>
</template>
</section>
</template>
@@ -1,9 +1,9 @@
/**
* features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts
* 用途:验证库存路由面板在服务端刷新后重置本地表单,并展示规则码/源编码以满足可追溯。
* 用途:验证库存路由面板展示服务端规则结果、规则码与源编码以满足可追溯。
* 依赖:Vitest、Vue Test Utils、vue-i18n、chat 文案。
* 逻辑:构造带技术编码的行投影;断言显示名+编码与命中规则;两列标签卡可扫描;
* 变更候选后本地勾选被重置。
* 自动重算意图只透传 line_key,不允许出现人工候选表单。
*/
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
@@ -31,7 +31,6 @@ function line(
rule_suggestion_source_codes: ['DSV360_AWSDU'],
matched_rules: [{ rule_code: 'ROUTE_HINT_AWSSG', version: 1 }],
rule_versions: [{ rule_code: 'INVENTORY_RULE_18', version: 18 }],
manual_reason: 'initial reason',
...overrides,
};
}
@@ -82,24 +81,19 @@ describe('ReviewInventoryCandidatesPanel', () => {
expect(wrapper.text()).toContain('新加坡仓');
});
it('resets local form when server candidates change for the same line_key', async () => {
it('renders refreshed rule candidates without exposing manual selection inputs', async () => {
const wrapper = mount(ReviewInventoryCandidatesPanel, {
props: {
lines: [line({ candidate_inventory_source_codes: ['DSV360_AWSDU'], manual_reason: 'old' })],
lines: [line({ candidate_inventory_source_codes: ['DSV360_AWSDU'] })],
sourceLabels: { DSV360_AWSDU: '杜塞尔多夫仓', DSV360_AWSBI: '伯明翰仓' },
editable: true,
},
global: { plugins: [i18n] },
});
const textarea = wrapper.get('textarea');
await textarea.setValue('user typed reason');
expect((textarea.element as HTMLTextAreaElement).value).toBe('user typed reason');
await wrapper.setProps({
lines: [line({
candidate_inventory_source_codes: ['DSV360_AWSBI'],
manual_reason: 'server refreshed',
raw_rule_source_codes: ['DSV360_AWSBI'],
unavailable_source_codes: [],
rule_suggestion_source_codes: ['DSV360_AWSBI'],
@@ -107,11 +101,10 @@ describe('ReviewInventoryCandidatesPanel', () => {
})],
});
await flushPromises();
const refreshed = wrapper.get('textarea');
expect((refreshed.element as HTMLTextAreaElement).value).toBe('server refreshed');
expect(wrapper.text()).toContain('伯明翰仓');
expect(wrapper.text()).toContain('DSV360_AWSBI');
expect(wrapper.text()).toContain('ROUTE_HINT_AWSBI');
expect(wrapper.find('textarea').exists()).toBe(false);
expect(wrapper.find('input[type="checkbox"]').exists()).toBe(false);
});
});
@@ -1,20 +1,16 @@
<!--
features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.vue
用途:库存路由恢复面板——展示规则建议/不可用源,支持 reroute、采纳建议、保留人工与多选提交。
用途:库存路由恢复面板——展示发布规则结果、不可用源并支持自动重算。
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection 类型。
逻辑:接收 recovery / suggestion_pending 行;规则候选优先,零候选回退已启用源;
服务端行指纹变化时重置本地表单;业务名与等宽 source_code 始终可见;
原始/不可用/建议候选用两列标签卡降低密度;emit 由 composable 写 API。
逻辑:只展示服务端规则裁决;服务端行指纹变化时刷新显示;业务名与等宽 source_code 始终可见;
原始/不可用/有效候选用两列标签卡降低密度;仅 emit 自动重算意图。
-->
<script setup lang="ts">
import { reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
/** 已启用库存源;规则零候选时作为可选列表 */
enabledSourceCodes?: string[];
/** 库存源编码 → 业务显示名;提交仍使用编码 */
sourceLabels?: Record<string, string>;
editable?: boolean;
@@ -22,30 +18,11 @@ const props = defineProps<{
}>();
const emit = defineEmits<{
(e: 'submit', payload: { lineKey: string; sourceCodes: string[]; reason: string }): void;
(e: 'reroute', lineKey?: string): void;
(e: 'adopt', payload: { lineKey: string; reason?: string }): void;
(e: 'keep', payload: { lineKey: string; reason?: string }): void;
}>();
const { t, te } = useI18n();
/** 每行本地表单状态:已选候选与原因。 */
const formState = reactive<Record<string, { selected: string[]; reason: string }>>({});
/**
* 行级可选源:规则候选优先,否则回退已启用库存源。
*/
function selectableCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
const candidates = (line.candidate_inventory_source_codes || [])
.map((code) => String(code || '').trim().toUpperCase())
.filter(Boolean);
if (candidates.length) return candidates;
return (props.enabledSourceCodes || [])
.map((code) => String(code || '').trim().toUpperCase())
.filter(Boolean);
}
/**
* 规则建议可用源编码。
*/
@@ -56,63 +33,6 @@ function ruleSuggestionCodes(line: ShippingOrderReviewBuildEligibilityLineProjec
|| [];
}
/**
* 服务端行投影指纹;变化时用于重置本地表单,避免提交过期候选/原因。
*/
function lineServerFingerprint(line: ShippingOrderReviewBuildEligibilityLineProjection): string {
return JSON.stringify({
line_key: String(line.line_key || line.line_index || ''),
candidates: (line.candidate_inventory_source_codes || []).map(String),
reason: String(line.manual_reason || ''),
suggestion_pending: Boolean(line.suggestion_pending),
rule: ruleSuggestionCodes(line).map(String),
unavailable: (line.unavailable_source_codes || []).map(String),
raw: (line.raw_rule_source_codes || []).map(String),
block_reason: String(line.block_reason || ''),
});
}
/**
* 清空本地表单缓存(下次 getForm 按服务端投影重新初始化)。
*/
function resetFormState() {
for (const key of Object.keys(formState)) {
delete formState[key];
}
}
watch(
() => (props.lines || []).map(lineServerFingerprint).join('\n'),
() => {
resetFormState();
},
);
/**
* 获取或初始化某行的表单状态。
*/
function getForm(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const key = String(line.line_key || (line.line_index ?? ''));
if (!formState[key]) {
const ruleCandidates = (line.candidate_inventory_source_codes || []).map(String);
formState[key] = {
selected: [...ruleCandidates],
reason: String(line.manual_reason || ''),
};
}
return formState[key];
}
/**
* 切换候选编码勾选状态。
*/
function toggleCode(line: ShippingOrderReviewBuildEligibilityLineProjection, code: string) {
const form = getForm(line);
const index = form.selected.indexOf(code);
if (index >= 0) form.selected.splice(index, 1);
else form.selected.push(code);
}
/**
* 解析阻断原因展示文案。
*/
@@ -160,20 +80,6 @@ function unavailableReasonLabel(line: ShippingOrderReviewBuildEligibilityLinePro
return te(key) ? t(key) : t('chat.shippingOrderReview.inventoryRouting.unavailableReasonUnknown');
}
/**
* 校验并提交指定行的人工候选选择。
*/
function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
if (!lineKey) return;
const form = getForm(line);
emit('submit', {
lineKey,
sourceCodes: [...form.selected],
reason: form.reason.trim(),
});
}
/**
* 触发行级重新匹配路由。
*/
@@ -182,25 +88,6 @@ function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
emit('reroute', lineKey || undefined);
}
/**
* 采纳待决规则建议。
*/
function adoptLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
if (!lineKey) return;
const reason = getForm(line).reason.trim();
emit('adopt', { lineKey, ...(reason ? { reason } : {}) });
}
/**
* 保留当前人工路由结果。
*/
function keepLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
if (!lineKey) return;
const reason = getForm(line).reason.trim();
emit('keep', { lineKey, ...(reason ? { reason } : {}) });
}
</script>
<template>
@@ -313,55 +200,6 @@ function keepLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
</div>
</div>
<p
v-if="line.suggestion_pending"
class="mt-2 rounded border border-amber-200 bg-amber-50 px-2 py-1 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-inventory-suggestion-pending"
>
{{ t('chat.shippingOrderReview.inventoryRouting.suggestionPending') }}
</p>
<div v-if="selectableCodes(line).length" class="mt-3">
<div class="text-xs font-medium text-slate-600 dark:text-slate-300">
{{
(line.candidate_inventory_source_codes || []).length
? t('chat.shippingOrderReview.inventoryCandidates.selectSources')
: t('chat.shippingOrderReview.inventoryCandidates.selectEnabledSources')
}}
</div>
<div class="mt-2 flex flex-wrap gap-2">
<label
v-for="code in selectableCodes(line)"
:key="code"
class="inline-flex cursor-pointer items-center gap-1.5 rounded border border-slate-200 px-2 py-1 text-xs dark:border-slate-600"
>
<input
type="checkbox"
:checked="getForm(line).selected.includes(code)"
:disabled="!editable || saving"
@change="toggleCode(line, code)"
>
<span>{{ sourceBusinessName(code) }}</span>
<span class="font-mono text-[11px] text-slate-500">{{ sourceCodeLabel(code) }}</span>
</label>
</div>
</div>
<p v-else class="mt-2 text-xs text-rose-600 dark:text-rose-300">
{{ t('chat.shippingOrderReview.inventoryCandidates.noEnabledSources') }}
</p>
<label class="mt-3 block text-xs font-medium text-slate-600 dark:text-slate-300">
{{ t('chat.shippingOrderReview.inventoryCandidates.reasonLabel') }}
<textarea
:value="getForm(line).reason"
:disabled="!editable || saving"
rows="2"
class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-xs dark:border-slate-600 dark:bg-slate-950"
:placeholder="t('chat.shippingOrderReview.inventoryCandidates.reasonPlaceholder')"
@input="getForm(line).reason = ($event.target as HTMLTextAreaElement).value"
/>
</label>
<div class="mt-3 flex flex-wrap items-center justify-end gap-2">
<button
type="button"
@@ -372,35 +210,6 @@ function keepLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
>
{{ t('chat.shippingOrderReview.inventoryRouting.reroute') }}
</button>
<template v-if="line.suggestion_pending">
<button
type="button"
class="rounded border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-900 disabled:opacity-50 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-100"
data-testid="review-inventory-routing-adopt"
:disabled="!editable || saving"
@click="adoptLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryRouting.adoptSuggestion') }}
</button>
<button
type="button"
class="rounded border border-slate-300 bg-white px-3 py-1.5 text-xs text-slate-700 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-950 dark:text-slate-200"
data-testid="review-inventory-routing-keep"
:disabled="!editable || saving"
@click="keepLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryRouting.keepManual') }}
</button>
</template>
<button
type="button"
class="rounded bg-sky-600 px-3 py-1.5 text-xs text-white disabled:opacity-50"
data-testid="review-inventory-candidates-submit"
:disabled="!editable || saving || !getForm(line).selected.length || !getForm(line).reason.trim()"
@click="submitLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryCandidates.submit') }}
</button>
</div>
</article>
</section>
@@ -8,6 +8,7 @@
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { inventoryActionLabelKey } from '@/features/shipping-progress/actionPresentation';
export interface InventoryIssueFallback {
kind?: string | null;
@@ -70,7 +71,7 @@ const reasonLabel = computed(() => {
:disabled="busy"
@click="emit('retry-preparation')"
>
{{ t('chat.shippingOrderReview.lineOps.retryPreparation') }}
{{ t(inventoryActionLabelKey('retry_inventory_preparation')!) }}
</button>
</section>
</template>
@@ -0,0 +1,94 @@
/**
* features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts
* 用途:验收订单生命周期阶段导航的只读查看与前置阻断交互。
* 依赖:ReviewLifecycleStageNavigation;Vue Test Utils 与 Vue I18n 测试运行时。
* 逻辑:阶段状态由父级传入;本测试只验证组件不会绕过 blocked 状态发出选择事件。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewLifecycleStageNavigation, {
type ReviewLifecycleStageItem,
} from './ReviewLifecycleStageNavigation.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
lifecycle: {
navigation: '订单生命周期阶段',
current: '当前可处理',
completed: '已完成,可查看',
blocked: '前置未完成',
},
},
},
},
},
});
const stages: ReviewLifecycleStageItem[] = [
{ code: 'order_review', label: '订单复核', state: 'completed' },
{ code: 'fulfillment_prep', label: '通知准备', state: 'current' },
{ code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' },
];
/** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */
function mountNavigation() {
return mount(ReviewLifecycleStageNavigation, {
props: { stages, activeCode: 'fulfillment_prep' },
global: { plugins: [i18n] },
});
}
describe('ReviewLifecycleStageNavigation', () => {
it('renders intake_parse as the first lifecycle stage', () => {
const wrapper = mount(ReviewLifecycleStageNavigation, {
props: {
stages: [
{ code: 'intake_parse' as ReviewLifecycleStageItem['code'], label: '接收解析', state: 'current' },
...stages,
],
activeCode: 'intake_parse' as ReviewLifecycleStageItem['code'],
},
global: { plugins: [i18n] },
});
const nodes = wrapper.findAll('div[data-testid^="review-lifecycle-stage-"]');
// 关键断言:接收解析必须在用户生命周期导航首位,不得回退为三阶段。
expect(nodes.map((node) => node.attributes('data-testid'))).toEqual([
'review-lifecycle-stage-intake_parse',
'review-lifecycle-stage-order_review',
'review-lifecycle-stage-fulfillment_prep',
'review-lifecycle-stage-upload_complete',
]);
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-4');
});
it('allows opening a completed stage for inspection', async () => {
const wrapper = mountNavigation();
await wrapper.get('[data-testid="review-lifecycle-stage-order_review"]').findAll('button')[1].trigger('click');
// 关键断言:完成的阶段可回看,不会因已完成而被禁用。
expect(wrapper.emitted('select')).toEqual([['order_review']]);
});
it('disables a future stage and does not emit a selection', async () => {
const wrapper = mountNavigation();
const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
// 关键断言:前置未完成只展示原因,不能通过前端导航越过后端阶段。
expect(future.text()).toContain('请先完成通知准备');
await future.findAll('button')[1].trigger('click');
expect(wrapper.emitted('select')).toBeUndefined();
});
it('opens process details from the stage label without reserving a separate row', async () => {
const wrapper = mountNavigation();
const detail = wrapper.get('[data-testid="review-lifecycle-stage-detail-fulfillment_prep"]');
// 关键断言:阶段名称本身是流程详情入口,不额外占用工作台一整行。
await detail.trigger('click');
expect(wrapper.emitted('open-detail')).toEqual([['fulfillment_prep']]);
});
});
@@ -0,0 +1,87 @@
<!--
features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue
用途:订单生命周期工作台的四阶段导航,只呈现父级已裁决的阶段状态。
依赖:父级 ShippingOrderReviewView 提供阶段、状态和阻断原因;lucide-vue-next 图标。
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。
-->
<script setup lang="ts">
import { Check, LockKeyhole } from 'lucide-vue-next';
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
export interface ReviewLifecycleStageItem {
code: ReviewLifecycleStageCode;
label: string;
state: ReviewLifecycleStageState;
reason?: string | null;
}
const props = defineProps<{
stages: ReviewLifecycleStageItem[];
/** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */
activeCode: ReviewLifecycleStageCode | null;
}>();
const emit = defineEmits<{
select: [code: ReviewLifecycleStageCode];
'open-detail': [code: ReviewLifecycleStageCode];
}>();
/**
* 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。
*/
function selectStage(stage: ReviewLifecycleStageItem) {
if (stage.state === 'blocked') return;
emit('select', stage.code);
}
</script>
<template>
<nav
class="rounded-xl border border-default bg-surface p-2"
:aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')"
data-testid="review-lifecycle-stage-navigation"
>
<div class="grid gap-2 sm:grid-cols-4">
<div
v-for="stage in props.stages"
:key="stage.code"
class="min-w-0 rounded-lg border px-3 py-2 text-left transition-colors"
:class="[
stage.code === props.activeCode
? 'border-brand-500 bg-brand-50 text-brand-950 dark:bg-brand-950/30 dark:text-brand-50'
: 'border-transparent hover:bg-surface-soft',
stage.state === 'blocked' ? 'opacity-60' : '',
]"
:data-testid="`review-lifecycle-stage-${stage.code}`"
>
<span class="flex items-center gap-2 text-sm font-semibold">
<Check v-if="stage.state === 'completed'" class="h-4 w-4 shrink-0 text-emerald-600" />
<LockKeyhole v-else-if="stage.state === 'blocked'" class="h-4 w-4 shrink-0 text-muted" />
<span v-else class="h-2 w-2 shrink-0 rounded-full bg-brand-600" aria-hidden="true" />
<button
type="button"
class="truncate text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500"
:data-testid="`review-lifecycle-stage-detail-${stage.code}`"
@click="emit('open-detail', stage.code)"
>{{ stage.label }}</button>
</span>
<button
type="button"
class="mt-1 block w-full truncate text-left text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 disabled:cursor-not-allowed"
:class="stage.state === 'blocked' ? 'text-muted' : 'text-secondary'"
:title="stage.reason || undefined"
:disabled="stage.state === 'blocked'"
@click="selectStage(stage)"
>
{{ stage.state === 'current'
? $t('chat.shippingOrderReview.lifecycle.current')
: stage.state === 'completed'
? $t('chat.shippingOrderReview.lifecycle.completed')
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
</button>
</div>
</div>
</nav>
</template>
@@ -34,8 +34,8 @@ function mountPanel(needsReview = false) {
needs_review: needsReview,
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
candidates: [
{ profile_code: 'ODP-A', score: 0.99 },
{ profile_code: 'ODP-B', score: 0.98 },
{ profile_code: 'ODP-A', display_name: '客户订单模板', score: 0.99 },
{ profile_code: 'ODP-B', display_name: '客户订单模板(旧版)', score: 0.98 },
],
fallback_reason_codes: [],
},
@@ -59,4 +59,14 @@ describe('ReviewProfileMatchPanel', () => {
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
expect(wrapper.find('[data-testid="review-profile-match-candidates"]').exists()).toBe(false);
});
it('候选模板优先展示模板名称,不把内部编号作为主文案', async () => {
const wrapper = mountPanel(true);
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
// 关键断言:业务用户辨认模板依赖 display_name,ODP 编号不应出现在候选列表主展示中。
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).toContain('客户订单模板');
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).not.toContain('ODP-A');
});
});
@@ -57,7 +57,7 @@ const selectedLabel = computed(() => {
if (!selected) {
return t('chat.shippingOrderReview.profileMatch.noSelected');
}
const name = String(selected.display_name || selected.profile_code || '').trim();
const name = String(selected.display_name || '').trim();
if (!name) return t('chat.shippingOrderReview.profileMatch.noSelected');
if (!isAdminView.value) return name;
const version = selected.version != null ? ` v${selected.version}` : '';
@@ -128,7 +128,7 @@ const selectedLabel = computed(() => {
:key="`${item.profile_code}-${item.version}-${idx}`"
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5 text-[11px] text-secondary"
>
<span class="font-mono">{{ item.profile_code }}</span>
<span>{{ item.display_name || t('chat.shippingOrderReview.profileMatch.noSelected') }}</span>
<span v-if="item.score != null" class="ml-2 text-muted">{{ item.score }}</span>
</li>
</ul>
@@ -0,0 +1,62 @@
/**
* features/chat/components/shipping-review/ReviewWorkbenchFooter.spec.ts
* 用途:验证字段冲突的 Gate 主动作只由右栏当前任务卡承载,底栏不得重复展示。
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewWorkbenchFooter。
* 逻辑:订单复核底栏只保留保存校验,不展示已由当前任务卡或阶段页承载的流程动作。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import ReviewWorkbenchFooter from './ReviewWorkbenchFooter.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingProcessing: { action: { resolve_field_conflicts: '处理字段冲突', view_result: '查看结果', none: '无操作' } },
shippingOrderReview: { unsavedSwitch: { unsavedCount: '未保存 {count} 项' } },
},
workspace: { shippingNotice: { processGate: { actions: {} } } },
},
},
});
describe('ReviewWorkbenchFooter', () => {
it('keeps intake parse dispositions in the sticky footer without replacement upload', () => {
const wrapper = mount(ReviewWorkbenchFooter, {
props: {
availableActions: ['mark_non_order', 'mark_quality_issue', 'reparse', 'validate'],
canConfirmBuild: false, saving: false, isReadOnly: false, hasDraft: true,
showParseDispositions: true, showValidate: false,
},
global: { plugins: [i18n] },
});
// 关键断言:接收解析动作与订单复核使用同一 sticky 底栏;业务不支持替代 PDF 上传。
expect(wrapper.get('[data-testid="review-footer-actions"]').classes()).toEqual(expect.arrayContaining(['sticky', 'bottom-0']));
expect(wrapper.text()).toContain('chat.shippingOrderReview.markNonOrder');
expect(wrapper.text()).toContain('chat.shippingOrderReview.markQualityIssue');
expect(wrapper.text()).toContain('chat.shippingOrderReview.reparse');
expect(wrapper.text()).not.toContain('chat.shippingOrderReview.saveOrderAndValidate');
});
it('does not duplicate current-case flow actions in the order-review footer', () => {
const wrapper = mount(ReviewWorkbenchFooter, {
props: {
availableActions: [], canConfirmBuild: false, saving: false, isReadOnly: false, hasDraft: true,
flowPresentation: {
primary: { intent: 'resolve_field_conflicts', actionCode: 'resolve_field_conflicts', labelKey: 'chat.shippingProcessing.action.resolve_field_conflicts' },
secondary: { intent: 'view_result', actionCode: 'view_result', labelKey: 'chat.shippingProcessing.action.view_result' },
overflow: [],
},
},
global: { plugins: [i18n] },
});
// 关键断言:字段冲突、重试和查看结果各有上游上下文,复核底栏不得重复它们。
expect(wrapper.find('[data-testid="review-footer-flow-resolve_field_conflicts"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-footer-flow-view_result"]').exists()).toBe(false);
});
});
@@ -3,7 +3,7 @@
用途:订单处理工作台底部唯一写操作栏(处置 / 保存 / 统一流程动作)。
依赖:vue-i18n、lucide-vue-next、ActionPresentation。
逻辑:ShippingOrderReviewView 传入 available_actions 与流程动作投影;sticky bottom;
只读查看时仍可展示 view_result/view_record;写按钮受 actionsExecutable 约束;
订单复核只保留保存校验;流程动作由所属阶段或当前任务卡承载;写按钮受 actionsExecutable 约束;
流程写操作经 flow-action emit(与 Resolver 同链);flowBusy||saving 时禁用。
-->
<script setup lang="ts">
@@ -36,6 +36,10 @@ const props = withDefaults(defineProps<{
actionsExecutable?: boolean;
/** 统一流程动作提交中 */
flowBusy?: boolean;
/** 解析处置入口由接收解析工作面承载时,订单复核底栏隐藏四项解析操作。 */
showParseDispositions?: boolean;
/** 保存并校验只属于订单复核表单,接收解析阶段必须隐藏。 */
showValidate?: boolean;
}>(), {
unsavedCount: 0,
flowPresentation: null,
@@ -46,20 +50,21 @@ const props = withDefaults(defineProps<{
autoGateHint: '',
actionsExecutable: true,
flowBusy: false,
showParseDispositions: true,
showValidate: true,
});
const emit = defineEmits<{
'mark-non-order': [];
'mark-quality-issue': [];
reparse: [];
'upload-replacement': [event: Event];
validate: [];
confirm: [];
'retry-stp': [];
'flow-action': [item: ActionPresentationItem];
}>();
const { t, te } = useI18n();
const { t } = useI18n();
/**
* 判断某 action 是否在当前 Case 可用。
@@ -68,40 +73,25 @@ function hasAction(action: string): boolean {
return props.availableActions.includes(action);
}
const flowItems = computed((): ActionPresentationItem[] => {
const presentation = props.flowPresentation;
if (!presentation) return [];
const items: ActionPresentationItem[] = [];
if (presentation.primary) items.push(presentation.primary);
if (presentation.secondary) items.push(presentation.secondary);
items.push(...presentation.overflow);
// 刷新留给顶部只读区;底栏不重复。
return items.filter((item) => item.intent !== 'refresh');
});
/**
* 订单复核底栏不承载流程投影动作。
*
* 核心逻辑:保存并校验是表单级提交,固定放在这里;字段裁决、重试、查看结果等
* Case/阶段级动作必须留在其业务上下文中,避免同一动作在顶栏、右栏和底栏重复出现。
*/
const footerFlowItems = computed((): ActionPresentationItem[] => []);
const hasViewOnlyFlow = computed(() => flowItems.value.some((item) => (
item.intent === 'view_result'
|| item.intent === 'view_record'
|| item.intent === 'open_profile_review'
)));
/** 保留统一动作的文案解析,供后续恢复 Footer 流程动作时复用。 */
function flowLabel(item: ActionPresentationItem): string {
return t(item.labelKey);
}
/** 可编辑底栏,或只读但仍有导航/查看类流程动作。 */
const showFooter = computed(() => (
props.hasDraft && (!props.isReadOnly || hasViewOnlyFlow.value)
));
/** 仅可编辑草稿显示表单提交底栏;只读版本不显示无上下文的流程按钮。 */
const showFooter = computed(() => props.hasDraft && !props.isReadOnly);
const controlsBusy = computed(() => props.saving || props.flowBusy);
const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isReadOnly);
/**
* 流程动作文案。
*/
function flowLabel(item: ActionPresentationItem): string {
if (te(item.labelKey)) return t(item.labelKey);
const gateKey = `workspace.shippingNotice.processGate.actions.${item.actionCode}`;
if (te(gateKey)) return t(gateKey);
return t('chat.shippingProcessing.action.none');
}
</script>
<template>
@@ -116,7 +106,7 @@ function flowLabel(item: ActionPresentationItem): string {
<div class="order-1 flex flex-wrap items-center gap-2 sm:order-1">
<template v-if="!automating && canWriteCaseActions">
<button
v-if="hasAction('mark_non_order')"
v-if="showParseDispositions && hasAction('mark_non_order')"
type="button"
:disabled="controlsBusy"
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/40"
@@ -125,7 +115,7 @@ function flowLabel(item: ActionPresentationItem): string {
{{ t('chat.shippingOrderReview.markNonOrder') }}
</button>
<button
v-if="hasAction('mark_quality_issue')"
v-if="showParseDispositions && hasAction('mark_quality_issue')"
type="button"
:disabled="controlsBusy"
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 hover:bg-amber-50 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200 dark:hover:bg-amber-950/40"
@@ -134,7 +124,7 @@ function flowLabel(item: ActionPresentationItem): string {
{{ t('chat.shippingOrderReview.markQualityIssue') }}
</button>
<button
v-if="hasAction('reparse')"
v-if="showParseDispositions && hasAction('reparse')"
type="button"
:disabled="controlsBusy"
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
@@ -142,24 +132,10 @@ function flowLabel(item: ActionPresentationItem): string {
>
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
</button>
<label
v-if="hasAction('mark_quality_issue')"
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
:class="controlsBusy ? 'pointer-events-none opacity-50' : ''"
>
<input
class="sr-only"
type="file"
accept="application/pdf,.pdf"
:disabled="controlsBusy"
@change="emit('upload-replacement', $event)"
>
{{ t('chat.shippingOrderReview.uploadReplacement') }}
</label>
</template>
<button
v-for="item in flowItems"
v-for="item in footerFlowItems"
:key="`${item.intent}-${item.actionCode}`"
type="button"
:disabled="controlsBusy"
@@ -196,23 +172,13 @@ function flowLabel(item: ActionPresentationItem): string {
</p>
<template v-if="!automating && canWriteCaseActions">
<button
v-if="showStpRetry || hasAction('retry_stp_auto_create')"
type="button"
:disabled="controlsBusy"
class="inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-3 py-2 text-sm text-amber-950 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-retry-stp-auto-create"
@click="emit('retry-stp')"
>
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.autoProgress.retryObject') }}
</button>
<button
v-if="hasAction('validate')"
v-if="showValidate && hasAction('validate')"
type="button"
:disabled="controlsBusy"
class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50"
@click="emit('validate')"
>
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveOrderAndValidate') }}
</button>
</template>
</div>
@@ -1,60 +1,33 @@
<!--
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
用途:订单复核工作台顶栏——对话级动作、审计/版本入口与保存状态。
用途:订单复核工作台顶栏——审计/版本入口与保存状态。
依赖:vue-i18n、lucide-vue-next。
逻辑:仅当后端 conversation_allowed_actions 含 retry_auto_progress 时渲染对话级按钮;
审计/版本为查看入口;「已保存」为状态文本;不含单个任务单写操作。
逻辑:审计/版本为查看入口;「已保存」为状态文本;不含单个任务单写操作。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { ArrowLeft, RefreshCw } from 'lucide-vue-next';
import { ArrowLeft } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
runNo: string;
itemNo?: string | null;
versionLabel?: string;
selectedOrderSummary?: string | null;
saving: boolean;
saveFailed: boolean;
draftConflict: boolean;
isReadOnly: boolean;
showVersionHistory?: boolean;
showAuditTrail?: boolean;
/** 对话级「重试自动推进」;仅 eligible_count>0 时由父级置 true */
showConversationRetry?: boolean;
conversationRetryEligibleCount?: number;
conversationRetrying?: boolean;
conversationRetryDisabled?: boolean;
hasConversationRetryResult?: boolean;
}>();
const emit = defineEmits<{
back: [];
'open-version-history': [];
'open-audit-trail': [];
'retry-conversation-auto-progress': [];
'open-conversation-retry-result': [];
}>();
const { t } = useI18n();
/**
* 副标题:优先工作项编号与版本,否则识别批次号。
*/
const subtitle = computed(() => {
if (props.itemNo) {
return t('chat.shippingOrderReview.workItemHeader', {
itemNo: props.itemNo,
version: props.versionLabel || '',
});
}
return t('chat.shippingOrderReview.run', { runNo: props.runNo });
});
const showRetry = computed(() => (
Boolean(props.showConversationRetry)
&& Number(props.conversationRetryEligibleCount || 0) > 0
));
</script>
<template>
@@ -69,36 +42,12 @@ const showRetry = computed(() => (
</button>
<div class="min-w-0 flex-1">
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
<p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ subtitle }}</p>
<p
v-if="selectedOrderSummary"
class="truncate text-xs text-slate-600 dark:text-slate-300"
data-testid="review-selected-order-summary"
>{{ selectedOrderSummary }}</p>
</div>
<button
v-if="showRetry"
type="button"
class="inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-2.5 py-1.5 text-xs font-medium text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-conversation-retry-auto-progress"
:disabled="conversationRetrying || conversationRetryDisabled || isReadOnly"
@click="emit('retry-conversation-auto-progress')"
>
<RefreshCw
class="h-3.5 w-3.5"
:class="conversationRetrying ? 'animate-spin' : ''"
/>
{{ conversationRetrying ? t('chat.shippingOrderReview.conversationRetry.retrying') : t('chat.shippingOrderReview.autoProgress.retry') }}
<span
v-if="conversationRetryEligibleCount"
class="rounded bg-amber-200/80 px-1 text-[10px] dark:bg-amber-900/60"
>{{ conversationRetryEligibleCount }}</span>
</button>
<button
v-if="hasConversationRetryResult"
type="button"
class="relative rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-open-conversation-retry-result"
@click="emit('open-conversation-retry-result')"
>
{{ t('chat.shippingOrderReview.conversationRetry.viewResult') }}
<span class="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-rose-500" />
</button>
<button
v-if="showAuditTrail"
type="button"
@@ -117,6 +117,210 @@ function buildWorkItem(
}
describe('ShippingConversationProcessingCard', () => {
it('only exposes file cancellation when the backend explicitly authorizes cancel_unit', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-CANCEL-UNIT', group: 'processing', status_label: 'extracting',
file_count: 1, run_no: 'RUN-CANCEL-UNIT', can_append: false,
objects: [{ kind: 'document', object_key: 'DOC-9', label: 'cancel.pdf', filename: 'cancel.pdf',
document_id: 9, root_document_id: 9, status_label: 'extracting' }],
}];
const workItem = buildWorkItem('OT-CANCEL-UNIT', {
availableActions: ['cancel_unit'],
sourceSummary: { ...buildWorkItem('OT-CANCEL-UNIT').sourceSummary, documentId: 9 },
uiState: {
status: 'running',
stage: 'document_parsing',
blocking_reason: null,
primary_action: null,
secondary_actions: [{ code: 'cancel_unit', enabled: true }],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [workItem], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
await wrapper.find('summary').trigger('click');
await wrapper.find('[data-testid="shipping-processing-file-cancel"]').trigger('click');
expect(wrapper.emitted('fileAction')?.[0]?.[0]).toMatchObject({
action: 'cancel_unit', projection: { workItemNo: 'OT-CANCEL-UNIT' },
});
});
it('does not fall back to legacy cancellation when ui_state revokes it', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-CANCEL-REVOKED', group: 'processing', status_label: 'extracting',
file_count: 1, run_no: 'RUN-CANCEL-REVOKED', can_append: false,
objects: [{ kind: 'document', object_key: 'DOC-10', label: 'revoked.pdf', filename: 'revoked.pdf',
document_id: 10, root_document_id: 10, status_label: 'extracting' }],
}];
const workItem = buildWorkItem('OT-CANCEL-REVOKED', {
availableActions: ['cancel_unit'],
sourceSummary: { ...buildWorkItem('OT-CANCEL-REVOKED').sourceSummary, documentId: 10 },
uiState: {
status: 'running',
stage: 'document_parsing',
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [workItem], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
// ui_state 已出现即表示后端完成了正式动作裁决;遗留 availableActions 不得重新授权。
expect(wrapper.find('[data-testid="shipping-processing-file-cancel"]').exists()).toBe(false);
expect(wrapper.emitted('fileAction')).toBeUndefined();
});
it('does not render legacy document_names as a batch file row without a live leaf projection', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-HISTORICAL-SNAPSHOT', group: 'processing', status_label: 'extracting',
title: 'legacy-run.pdf', document_names: ['legacy-run.pdf'], file_count: 1,
run_no: 'RUN-HISTORICAL-SNAPSHOT', can_append: false,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
// 批次中心没有实时叶子投影时不得由历史 Run 快照补造文件行或操作入口。
expect(wrapper.find('[data-testid="shipping-processing-file-OT-HISTORICAL-SNAPSHOT-document-0"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('legacy-run.pdf');
});
it('uses the live leaf summary instead of a stale task object in batch mode', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-LIVE-LEAF', group: 'processing', status_label: 'extracting',
title: 'snapshot-old-name.pdf', file_count: 1, run_no: 'RUN-LIVE-LEAF', can_append: false,
objects: [{
kind: 'document', object_key: 'DOC-88', label: 'snapshot-old-name.pdf',
filename: 'snapshot-old-name.pdf', document_id: 88, root_document_id: 88,
status_label: 'pending_review',
}],
}];
const live = buildWorkItem('OT-LIVE-LEAF', {
runNo: 'RUN-LIVE-LEAF',
sourceSummary: {
emailSubject: null, filename: 'realtime-name.pdf', documentId: 88,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-REALTIME',
},
uiState: {
status: 'running', stage: 'order_review', lifecycleStage: 'order_review',
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [live], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-88"]');
expect(row.text()).toContain('realtime-name.pdf');
expect(row.text()).toContain('PO:PO-REALTIME');
expect(row.text()).not.toContain('snapshot-old-name.pdf');
});
it('expands EML files only from the live aggregate work item', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'INTAKE:EML-LIVE', group: 'processing', status_label: 'extracting',
title: 'snapshot-mail.eml', document_names: ['snapshot-attachment.pdf'],
file_count: 1, run_no: 'RUN-EML-LIVE', can_append: false,
aggregateChildren: [],
}];
const liveChild = buildWorkItem('DOCUMENT:77', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
sourceSummary: {
emailSubject: null, filename: 'live-attachment.pdf', documentId: 77,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-EML-LIVE',
},
uiState: {
status: 'running', stage: 'order_review', lifecycleStage: 'order_review',
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const liveEmlRoot = buildWorkItem('INTAKE:EML-LIVE', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
sourceSummary: {
emailSubject: 'Live mail', filename: 'live-mail.eml', documentId: null,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: null,
},
aggregateChildren: [liveChild],
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [liveEmlRoot], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-77"]');
expect(row.text()).toContain('live-attachment.pdf');
expect(row.text()).toContain('PO:PO-EML-LIVE');
expect(wrapper.text()).not.toContain('snapshot-attachment.pdf');
});
it('keeps an EML attachment when it has a linked child order task', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'INTAKE:EML-WITH-CHILD-OT', group: 'processing', status_label: 'extracting',
title: 'mail.eml', file_count: 2, run_no: 'RUN-EML-WITH-CHILD-OT', can_append: false,
}];
const firstAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: null, filename: 'first.pdf', documentId: 266,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-FIRST',
},
childOrderTasks: [{
orderTaskNo: 'OT-EML-WITH-CHILD-OT-C1', status: 'blocked', stage: 'inventory_matching',
customerName: null, poNumber: 'PO-SECOND', lastActivityAt: null,
}],
});
const secondAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT-C1', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: null, filename: 'second.pdf', documentId: 267,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-SECOND',
},
});
const liveEmlRoot = buildWorkItem('INTAKE:EML-WITH-CHILD-OT', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: 'Mail', filename: 'mail.eml', documentId: null,
documentCount: 2, parsedDocumentCount: 2, candidateCount: 2,
customerName: null, poNumber: null,
},
aggregateChildren: [firstAttachment, secondAttachment],
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [liveEmlRoot], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-266"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-267"]').exists()).toBe(true);
expect(wrapper.text()).toContain('处理中 · 2 个文件');
});
it('renders needs_action / processing groups and collapsible processing records with three subsections', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection: buildProjection() },
@@ -125,10 +329,11 @@ describe('ShippingConversationProcessingCard', () => {
await flushPromises();
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-needs_action"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
expect(wrapper.text()).toContain('需要你处理 · 1 个任务');
expect(wrapper.text()).toContain('系统处理中 · 1 个任务');
// 批次中心统一按文件计数;旧任务数文案不再是页面统计口径。
expect(wrapper.text()).toContain('异常 · 0 个文件');
expect(wrapper.text()).toContain('处理中 · 0 个文件');
expect(wrapper.text()).toContain('刚刚创建');
// 处理记录默认折叠;标题 count = completed + history 返回条数。
@@ -441,20 +646,36 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.findAll('[data-testid="shipping-conversation-processing-card"]')).toHaveLength(1);
});
it('renders pending order_intake work items above task groups', async () => {
it('renders an EML order_intake in the unified failed group rather than the removed intake side path', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: null,
projection: {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
needs_action: [{
user_task_no: 'SNI-1',
group: 'needs_action',
userGroup: 'failed',
status_label: 'failed',
title: 'mail.eml',
file_count: 1,
run_no: null,
can_append: false,
}],
processing: [],
completed: [],
history: [],
},
workItems: [{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
sourceType: 'eml',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'failed',
userGroup: 'failed',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-04T12:00:00Z',
@@ -484,16 +705,10 @@ describe('ShippingConversationProcessingCard', () => {
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-intake-SNI-1"]').exists()).toBe(true);
expect(wrapper.text()).toContain('po.pdf');
expect(wrapper.find('[data-testid="shipping-processing-intake-recovery"]').exists()).toBe(true);
expect(wrapper.text()).toContain('SHIPPING_NOTICE.INTAKE_PARSE_FAILED');
await wrapper.find('[data-testid="shipping-processing-intake-action-retry_parse"]').trigger('click');
expect(wrapper.emitted('intakeAction')?.[0]?.[0]).toMatchObject({
action: 'retry_parse',
item: { workItemNo: 'SNI-1' },
});
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-SNI-1"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(false);
expect(wrapper.text()).toContain('重试解析');
});
it('keeps a human Gate action visible before and after selecting its task', async () => {
@@ -549,7 +764,110 @@ describe('ShippingConversationProcessingCard', () => {
});
await flushPromises();
expect(wrapper.text()).toContain('待复核');
// 旧聚合卡不再显示内部 Case 状态;工作台文件行才展示后端 ui_state。
expect(wrapper.text()).not.toContain('review_case_draft');
expect(wrapper.text()).not.toContain('review_case_draft');
});
it('renders a compact V3 file row with named lifecycle entries', async () => {
const projection = buildProjection();
projection.processing = [{
...projection.processing[0],
user_task_no: 'OT-LIFECYCLE',
run_no: 'RUN-LIFECYCLE',
file_count: 1,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection,
workbenchMode: true,
workItems: [buildWorkItem('OT-LIFECYCLE', {
runNo: 'RUN-LIFECYCLE',
caseNo: 'CASE-LIFECYCLE',
sourceSummary: {
emailSubject: null,
filename: 'lifecycle.pdf',
documentId: 9,
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-LIFECYCLE',
},
uiState: {
status: 'running',
stage: 'inventory_match',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
})],
},
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-9"]');
expect(row.exists()).toBe(true);
expect(row.text()).toContain('lifecycle.pdf');
expect(row.text()).toContain('PO:PO-LIFECYCLE');
expect(row.text()).toContain('通知准备');
expect(row.text()).toContain('订单复核 · 可进入');
expect(row.text()).toContain('通知准备 · 当前可处理');
expect(row.text()).toContain('通知完成 · 前置未完成');
});
it('fails closed when a lifecycle entry has an unknown backend state', async () => {
const projection = buildProjection();
projection.processing = [{
...projection.processing[0],
user_task_no: 'OT-LIFECYCLE-UNKNOWN',
run_no: 'RUN-LIFECYCLE-UNKNOWN',
file_count: 1,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection,
workbenchMode: true,
workItems: [buildWorkItem('OT-LIFECYCLE-UNKNOWN', {
runNo: 'RUN-LIFECYCLE-UNKNOWN',
sourceSummary: {
emailSubject: null,
filename: 'unknown-entry.pdf',
documentId: 10,
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-UNKNOWN',
},
uiState: {
status: 'running',
stage: 'inventory_match',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [
{ code: 'order_review', state: 'paused', targetSurface: 'order_lifecycle_workbench' },
] as unknown as ShippingProcessingProjection['uiState']['lifecycleEntries'],
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
})],
},
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
const orderReview = row.findAll('button').find((button) => button.text().includes('订单复核'));
expect(orderReview?.attributes('disabled')).toBeDefined();
await orderReview?.trigger('click');
expect(wrapper.emitted('openLifecycleStage')).toBeUndefined();
});
});
@@ -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;
@@ -13,10 +13,11 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight } from 'lucide-vue-next';
import { ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-vue-next';
import type {
ConversationProcessingProjection,
ConversationProcessingUserTask,
ShippingProcessingLifecycleEntry,
ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import { getPrimaryDocumentName } from '@/features/chat/shipping/conversationProcessingDisplay';
@@ -30,11 +31,12 @@ import {
} from '@/features/chat/shipping/conversationProcessingState';
import {
resolveShippingProcessingMessage,
resolveShippingProcessingReasonLabel,
resolveShippingProcessingStageLabel,
resolveShippingProcessingStatusLabel,
shippingProcessingSourceTypeKey,
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';
@@ -46,6 +48,15 @@ const props = defineProps<{
conversationId?: string | null;
/** 后端截断提示:history 还有未返回内容时在处理记录底部展示 */
hasMoreHistory?: boolean;
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
workbenchMode?: boolean;
/** 批次四阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
/** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */
fileSearchQuery?: string;
/** 后端已授权下载的正式 Excel 对应 OT。 */
downloadableTaskNos?: string[];
selectedDownloadTaskNos?: string[];
}>();
const emit = defineEmits<{
@@ -59,6 +70,12 @@ const emit = defineEmits<{
intakeAction: [payload: { item: ShippingProcessingProjection; action: string }];
/** OT 卡内统一进度动作。 */
projectionAction: [payload: { projection: ShippingProcessingProjection; item: ActionPresentationItem }];
downloadArtifact: [taskNo: string];
toggleDownloadSelection: [taskNo: string];
/** 文件级生命周期入口;父级只切换工作台展示,不在导航时写入业务状态。 */
openLifecycleStage: [payload: { projection: ShippingProcessingProjection; entry: ShippingProcessingLifecycleEntry }];
/** 单文件低频操作;仅当后端明确授权该动作时才发出。 */
fileAction: [payload: { projection: ShippingProcessingProjection; action: string }];
}>();
const { t, te } = useI18n();
@@ -66,27 +83,63 @@ 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;
po_number?: string | null;
projection?: ShippingProcessingProjection;
};
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number];
const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
order_review: 'orderReview',
fulfillment_prep: 'fulfillmentPrep',
upload_complete: 'uploadComplete',
};
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
const activeProjection = computed((): ConversationProcessingProjection | null => (
props.projection || null
));
/** 尚未建 OT、仍应展示在「待处理材料」的 Intake 工作项。 */
const pendingIntakeItems = computed((): ShippingProcessingProjection[] => {
const items = Array.isArray(props.workItems) ? props.workItems : [];
return items.filter((item) => {
if (item.workItemType !== 'order_intake') return false;
return !['completed', 'cancelled'].includes(String(item.status || ''));
});
});
const hasContent = computed(() => Boolean(
activeProjection.value
|| pendingIntakeItems.value.length,
activeProjection.value,
));
const completedTasks = computed(() => activeProjection.value?.completed || []);
const historyTasks = computed(() => activeProjection.value?.history || []);
const statusGroups = computed(() => activeProjection.value?.status_groups || null);
const completedTasks = computed(() => statusGroups.value?.completed || activeProjection.value?.completed || []);
const historyTasks = computed(() => statusGroups.value
? [...statusGroups.value.cancelled, ...statusGroups.value.archived]
: (activeProjection.value?.history || []));
/** EML 卡必须由后端 userGroup 分入独立用户区;旧任务保留 needs_action 兼容归属。 */
const failedTasks = computed(() => statusGroups.value?.failed
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'failed' || !task.userGroup));
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'waiting_human'));
const processingTasks = computed(() => statusGroups.value?.processing || activeProjection.value?.processing || []);
/** 任务只要含一个命中附件即保留,避免筛选后打散同一封 EML 的上下文。 */
function taskMatchesLifecycleFilter(task: ConversationProcessingUserTask): boolean {
const filter = props.lifecycleFilter || 'all';
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
// 非批次中心保留历史任务卡兼容展示;只有批次中心才按叶子文件筛选。
if (!props.workbenchMode && filter === 'all' && !query) return true;
return workbenchFileRows(task).some((file) => {
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
return !query || [file.filename, file.label, file.po_number]
.some((value) => String(value || '').toLowerCase().includes(query));
});
}
const visibleFailedTasks = computed(() => failedTasks.value.filter(taskMatchesLifecycleFilter));
const visibleWaitingHumanTasks = computed(() => waitingHumanTasks.value.filter(taskMatchesLifecycleFilter));
const visibleProcessingTasks = computed(() => processingTasks.value.filter(taskMatchesLifecycleFilter));
const visibleCompletedTasks = computed(() => completedTasks.value.filter(taskMatchesLifecycleFilter));
/** history 中非取消 →「历史版本」。 */
const historyVersionTasks = computed(() => historyTasks.value.filter(
@@ -97,6 +150,8 @@ const historyVersionTasks = computed(() => historyTasks.value.filter(
const cancelledHistoryTasks = computed(() => historyTasks.value.filter(
(task) => String(task.status_label || '').trim().toLowerCase() === 'cancelled',
));
const visibleHistoryVersionTasks = computed(() => historyVersionTasks.value.filter(taskMatchesLifecycleFilter));
const visibleCancelledHistoryTasks = computed(() => cancelledHistoryTasks.value.filter(taskMatchesLifecycleFilter));
/** 处理记录标题计数:当前返回的 completed + history。 */
const recordTaskCount = computed(() => (
@@ -123,7 +178,7 @@ function projectionForTask(task: ConversationProcessingUserTask): ShippingProces
if (!taskNo) return null;
const items = Array.isArray(props.workItems) ? props.workItems : [];
return items.find((item) => (
item.workItemType === 'order_task'
(item.workItemType === 'order_task' || item.workItemType === 'order_intake')
&& String(item.workItemNo || '').trim() === taskNo
)) || null;
}
@@ -187,6 +242,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';
@@ -204,6 +260,249 @@ 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 || [];
// [AUTHORITY] 批次模式只以实时 work_items 作为文件行真相。Conversation task 的
// children / objects / document_names 是 Run 级兼容快照,可用于非批次卡历史展示,
// 但不得重建批次中的文件名、状态、阶段或操作。
if (props.workbenchMode) {
const taskNo = String(task.user_task_no || '').trim();
const liveLeaves = (props.workItems || []).flatMap((item) => {
const isTaskRoot = String(item.rootOrderTaskNo || '').trim() === taskNo
|| String(item.workItemNo || '').trim() === taskNo;
if (!isTaskRoot) return [];
// EML 父项的实时附件只存在于 aggregateChildren;展开同一份后端 work_item,
// 不读取 conversation task 兼容快照。
return item.sourceType === 'eml'
? flattenBusinessFileProjections([item])
: [item];
}).filter((item) => (
Number(item.sourceSummary?.documentId || 0) > 0
));
const seenLiveDocumentIds = new Set<number>();
const uniqueLiveLeaves = liveLeaves.filter((item) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
if (seenLiveDocumentIds.has(documentId)) return false;
seenLiveDocumentIds.add(documentId);
return true;
});
return uniqueLiveLeaves.map((item, index) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
return {
kind: 'document' as const,
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-live-${item.workItemNo || index}`,
label: filename || item.workItemNo || `文件 ${index + 1}`,
filename: filename || item.workItemNo || `文件 ${index + 1}`,
document_id: documentId || null,
status_label: String(item.uiState?.status || item.userStatus || item.status || ''),
po_number: item.sourceSummary?.poNumber || null,
projection: item,
};
});
}
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 || ''),
po_number: child.sourceSummary?.poNumber || null,
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,
po_number: directFileProjection?.sourceSummary?.poNumber || null,
projection: directFileProjection?.sourceType === 'direct_pdf'
? directFileProjection
: undefined,
}));
}
const taskName = String(task.title || '').trim().toLowerCase();
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
// 新版实时投影可只返回 work_items,不重复旧 task.objects;此时以同一 OT 的叶子
// document 投影生成行,确保文件状态、阶段和按钮仍完全来自后端。
const taskNo = String(task.user_task_no || '').trim();
const liveLeaves = (props.workItems || []).filter((item) => (
String(item.rootOrderTaskNo || '').trim() === taskNo
&& Number(item.sourceSummary?.documentId || 0) > 0
&& !item.childOrderTasks?.length
));
if (liveLeaves.length) {
return liveLeaves.map((item, index) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
return {
kind: 'document' as const,
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-live-${item.workItemNo || index}`,
label: filename || item.workItemNo || `文件 ${index + 1}`,
filename: filename || item.workItemNo || `文件 ${index + 1}`,
document_id: documentId || null,
status_label: String(item.uiState?.status || item.userStatus || item.status || ''),
po_number: item.sourceSummary?.poNumber || null,
projection: item,
};
});
}
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,
po_number: null,
}));
}
/** 阶段筛选只收窄附件行,EML 卡本身仍保留以便用户识别邮件来源。 */
function visibleWorkbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const filter = props.lifecycleFilter || 'all';
const rows = workbenchFileRows(task);
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
return rows.filter((file) => {
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
if (!query) return true;
return [file.filename, file.label, file.po_number].some((value) => String(value || '').toLowerCase().includes(query));
});
}
function fileDownloadTaskNo(file: WorkbenchFileRow): string | null {
const taskNo = String(file.projection?.rootOrderTaskNo || '').trim();
return taskNo && (props.downloadableTaskNos || []).includes(taskNo) ? taskNo : null;
}
function isDownloadSelected(taskNo: string): boolean {
return (props.selectedDownloadTaskNos || []).includes(taskNo);
}
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
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;
return resolveShippingProcessingReasonLabel(reason, te, t);
}
return taskReasonLabel(task);
}
/** 文件工作面显示四阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
function workbenchFileLifecycleStage(file: WorkbenchFileRow): string {
const code = String(file.projection?.uiState?.lifecycleStage || '').trim();
const key = LIFECYCLE_STAGE_LABEL_KEYS[code];
return key
? t(`chat.shippingNoticeUi.stage.${key}`)
: t('chat.shippingProcessing.stageLabel.waiting_system_start');
}
/** 生命周期入口仅消费后端投影;禁止按候选、Case 或阶段顺序二次裁决。 */
function lifecycleEntries(file: WorkbenchFileRow): ShippingProcessingLifecycleEntry[] {
return file.projection?.uiState?.lifecycleEntries || [];
}
function lifecycleEntry(file: WorkbenchFileRow, target: LifecycleStageCode): ShippingProcessingLifecycleEntry | null {
return lifecycleEntries(file).find((entry) => entry.code === target) || null;
}
function lifecycleEntryState(file: WorkbenchFileRow, target: LifecycleStageCode): 'available' | 'current' | 'unavailable' {
const state = lifecycleEntry(file, target)?.state;
// [FAIL-CLOSED] 服务端新增或异常状态不得被 UI 当作可进入工作台。
return state === 'available' || state === 'current' ? state : 'unavailable';
}
function lifecycleEntryLabel(file: WorkbenchFileRow, target: LifecycleStageCode): string {
void file;
// 阶段状态由按钮颜色和 disabled 表达,避免重复的“当前可处理/前置未完成”文案挤占文件行。
return t(`chat.shippingNoticeUi.stage.${LIFECYCLE_STAGE_LABEL_KEYS[target]}`);
}
function onOpenLifecycleStage(file: WorkbenchFileRow, lifecycleStage: LifecycleStageCode) {
const entry = lifecycleEntry(file, lifecycleStage);
if (!file.projection || !entry) return;
if (lifecycleEntryState(file, lifecycleStage) === 'unavailable') return;
emit('openLifecycleStage', { projection: file.projection, entry });
}
/** 叶子文件动作由自身 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}」。
*/
@@ -229,7 +528,38 @@ 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,
);
}
/** 展示统一投影的真实履约阶段;识别候选不再冒充最终完成。 */
function stageLabel(task: ConversationProcessingUserTask): string {
const projection = projectionForTask(task);
if (!projection) return '';
return intakeStageLabel(projection);
}
/** 展示后端 ui_state 已裁决的阻断原因;i18n 仅负责翻译,不映射或猜测业务原因。 */
function taskReasonLabel(task: ConversationProcessingUserTask): string {
const reason = task.uiState
? task.uiState.blocking_reason
: task.blockingReason;
return resolveShippingProcessingReasonLabel(reason, te, t);
}
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
function aggregateStatusLabel(task: ConversationProcessingUserTask): string {
const summary = task.aggregateSummary;
if (!summary) return '';
const parts: string[] = [];
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
return parts.join(' · ');
}
/**
@@ -256,6 +586,16 @@ function taskActionPresentation(task: ConversationProcessingUserTask): ActionPre
return resolveConversationTaskActionPresentation(task, { surface: 'right' });
}
/**
* 待确认分组的批次重解析入口:仅消费该分组任务的后端授权,避免按钮脱离业务上下文。
*/
function waitingHumanBatchReparseTask(): ConversationProcessingUserTask | null {
return visibleWaitingHumanTasks.value.find((task) => (
task.available_actions?.includes('reparse_batch')
&& String(task.run_no || '').trim()
)) || null;
}
/**
* 唯一主 CTA(实心按钮);处理记录只读卡不调用。
*/
@@ -270,10 +610,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',
@@ -326,6 +670,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));
}
@@ -364,7 +709,27 @@ function presentationActionLabel(task: ConversationProcessingUserTask, item: Act
if (key && te(key)) return t(key);
const extractionKey = `chat.shippingOrderExtractionAction.${code}`;
if (te(extractionKey)) return t(extractionKey);
return code;
return t('chat.shippingProcessing.action.unknown');
}
/**
* 文件低频操作优先读取正式 ui_state;旧 availableActions 仅兼容未下发 ui_state 的旧投影。
* 一旦后端提供 ui_state,遗留字段绝不能重新授予已撤销的操作。
*/
function canCancelFile(file: WorkbenchFileRow): boolean {
const projection = file.projection;
if (!projection) return false;
if (projection.uiState) {
return projection.uiState.secondary_actions.some(
(action) => action.enabled && action.code === 'cancel_unit',
);
}
return projection.availableActions.includes('cancel_unit');
}
function onFileAction(file: WorkbenchFileRow, action: string) {
if (!file.projection || action !== 'cancel_unit' || !canCancelFile(file)) return;
emit('fileAction', { projection: file.projection, action });
}
/**
@@ -391,93 +756,11 @@ function toggleHistorySection() {
historySectionExpanded.value = !historySectionExpanded.value;
}
/**
* Intake 材料标题:文件名 / 邮件主题 / Intake 编号。
*/
function intakeTitle(item: ShippingProcessingProjection): string {
return String(
item.sourceSummary?.filename
|| item.sourceSummary?.emailSubject
|| item.workItemNo
|| '',
).trim() || item.workItemNo;
}
/**
* Intake 状态文案。
*/
function intakeStatusLabel(item: ShippingProcessingProjection): string {
return resolveShippingProcessingStatusLabel(item.status, te, t);
}
/**
* Intake 阶段文案。
*/
function intakeStageLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingStageKey(item.stage);
return te(key) ? t(key) : String(item.stage || '');
}
/**
* Intake 来源类型文案。
*/
function intakeSourceLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingSourceTypeKey(item.sourceType);
return te(key) ? t(key) : String(item.sourceType || '');
}
/**
* Intake / OT 门禁与失败恢复元信息(Gate / Attempt / 资产状态)。
*/
function intakeRecoveryMeta(item: ShippingProcessingProjection): string[] {
const parts: string[] = [];
const gate = item.currentGate;
const reason = String(
gate?.blockingReasonCode
|| item.sourceSummary?.failureReasonCode
|| '',
).trim();
if (reason) {
parts.push(t('chat.shippingProcessing.failureReason', { code: reason }));
}
const attempt = gate?.attemptNo ?? item.sourceSummary?.parseAttemptCount;
if (attempt != null && Number(attempt) > 0) {
parts.push(t('chat.shippingProcessing.parseAttempt', { count: Number(attempt) }));
}
const assetStatus = String(item.sourceSummary?.assetStatus || '').trim();
if (assetStatus) {
const key = `chat.shippingProcessing.assetStatus.${assetStatus}`;
parts.push(te(key) ? t(key) : t('chat.shippingProcessing.assetStatusLabel', { status: assetStatus }));
}
if (gate?.gateCode) {
parts.push(t('chat.shippingProcessing.gateCode', { code: gate.gateCode }));
}
return parts;
}
/**
* Intake 可见动作(仅展示 retry_parse)。
*/
function visibleIntakeActions(item: ShippingProcessingProjection): string[] {
const actions = Array.isArray(item.availableActions) ? item.availableActions : [];
return actions.filter((code) => code === 'retry_parse');
}
/**
* Intake 动作文案。
*/
function intakeActionLabel(action: string): string {
if (action === 'retry_parse') return t('chat.shippingProcessing.retryFromFailure');
return action;
}
/**
* 触发 Intake 级动作。
*/
function onIntakeAction(item: ShippingProcessingProjection, action: string) {
const code = String(action || '').trim();
if (!code) return;
emit('intakeAction', { item, action: code });
return resolveShippingProcessingStageLabel(item.stage, te, t);
}
</script>
@@ -488,70 +771,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
data-testid="shipping-conversation-processing-card"
>
<section
v-if="pendingIntakeItems.length"
data-testid="shipping-processing-group-order-intake"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300">
{{ t('chat.shippingProcessing.pendingMaterials') }}
· {{ pendingIntakeItems.length }}
</div>
<div class="space-y-2">
<article
v-for="item in pendingIntakeItems"
:key="item.workItemNo"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:data-testid="`shipping-processing-intake-${item.workItemNo}`"
:data-source-type="item.sourceType"
:data-status="item.status"
>
<div class="text-sm font-semibold text-primary">
{{ intakeTitle(item) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span>{{ intakeSourceLabel(item) }}</span>
<span>{{ intakeStatusLabel(item) }}</span>
<span v-if="intakeStageLabel(item)">{{ intakeStageLabel(item) }}</span>
</div>
<div
v-if="intakeRecoveryMeta(item).length"
class="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-rose-700 dark:text-rose-300"
data-testid="shipping-processing-intake-recovery"
>
<span
v-for="(meta, idx) in intakeRecoveryMeta(item)"
:key="`${item.workItemNo}-meta-${idx}`"
>{{ meta }}</span>
</div>
<div
v-if="visibleIntakeActions(item).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-intake-actions"
>
<button
v-for="action in visibleIntakeActions(item)"
:key="`${item.workItemNo}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-intake-action-${action}`"
@click="onIntakeAction(item, action)"
>
{{ intakeActionLabel(action) }}
</button>
</div>
</article>
</div>
</section>
<section
v-if="activeProjection?.needs_action.length"
data-testid="shipping-processing-group-needs_action"
v-if="visibleFailedTasks.length"
data-testid="shipping-processing-group-failed"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: activeProjection.needs_action.length }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.failed', { count: groupFileCount(visibleFailedTasks) }) }}
</div>
<div class="space-y-2">
<article
v-for="task in activeProjection.needs_action"
v-for="task in visibleFailedTasks"
:key="task.user_task_no"
class="rounded-lg border px-2.5 py-2 transition"
:class="[
@@ -569,19 +797,24 @@ function onIntakeAction(item: ShippingProcessingProjection, action: 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"
>
{{ primaryFileLabel(task) }}
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
{{ taskReasonLabel(task) }}
</div>
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
{{ aggregateStatusLabel(task) }}
</div>
<div
v-if="task.recent_append_count"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
@@ -595,27 +828,41 @@ function onIntakeAction(item: ShippingProcessingProjection, action: 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 visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-white/70 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center dark:bg-slate-950/30" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div>
<div class="flex min-w-0 flex-wrap items-center gap-1">
<span class="w-fit shrink-0 rounded-full bg-rose-100 px-2 py-0.5 font-medium text-rose-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.failedFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md border border-rose-300 px-2 py-0.5 font-medium text-rose-700 hover:bg-rose-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
<label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label>
<button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button>
</div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5">
<div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600 dark:text-rose-300" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div>
<div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div>
<details v-if="canCancelFile(file)" class="relative shrink-0">
<summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary>
<button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button>
</details>
</div>
</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'"
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
/>
<div
v-if="shouldShowTaskLevelActions(task) || (!projectionForTask(task) && canExpandFileDetails(task))"
v-if="shouldShowTaskLevelActions(task) || (!workbenchMode && !projectionForTask(task) && canExpandFileDetails(task))"
class="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1"
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}`"
@@ -630,15 +877,75 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
</section>
<section
v-if="activeProjection?.processing.length"
data-testid="shipping-processing-group-processing"
v-if="visibleWaitingHumanTasks.length"
data-testid="shipping-processing-group-waiting_human"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: activeProjection.processing.length }) }}
<div class="mb-1.5 flex items-center justify-between gap-2 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ t('chat.shippingProcessing.batchWorkbench.groups.waitingHuman', { count: groupFileCount(visibleWaitingHumanTasks) }) }}
<button
v-if="workbenchMode && waitingHumanBatchReparseTask()"
type="button"
class="inline-flex items-center gap-1 rounded-md border border-amber-300 bg-amber-50 px-2.5 py-1 text-[11px] font-medium normal-case text-amber-800 hover:bg-amber-100 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-200"
data-testid="shipping-processing-batch-reparse"
@click="onTaskAction(waitingHumanBatchReparseTask()!, 'reparse_batch')"
>
{{ t('chat.shippingOrderReview.lineOps.reparse_batch') }}
</button>
</div>
<div class="space-y-2">
<article
v-for="task in activeProjection.processing"
v-for="task in visibleWaitingHumanTasks"
:key="task.user_task_no"
class="rounded-lg border border-amber-400 bg-amber-50/80 px-2.5 py-2 transition dark:border-amber-700 dark:bg-amber-950/30"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button type="button" class="w-full text-left" @click="onSelectTask(task)">
<div class="text-sm font-semibold text-primary">{{ 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>
</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="workbenchMode" class="mt-3 space-y-2 border-t border-amber-200/70 pt-2">
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-white/70 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center dark:bg-slate-950/30" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div>
<div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-amber-100 px-2 py-0.5 font-medium text-amber-800">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.waitingFallback') }}</span><button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md bg-brand-600 px-2 py-0.5 font-medium text-white hover:bg-brand-700" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600 dark:text-rose-300" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div><details v-if="canCancelFile(file)" class="relative shrink-0"><summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary><button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button></details></div>
</div>
</div>
<SidebarProgressInline
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>
<section
v-if="visibleProcessingTasks.length"
data-testid="shipping-processing-group-processing"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
{{ t('chat.shippingProcessing.batchWorkbench.groups.processing', { count: groupFileCount(visibleProcessingTasks) }) }}
</div>
<div class="space-y-2">
<article
v-for="task in visibleProcessingTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:class="focusedTaskNo === task.user_task_no
@@ -653,19 +960,21 @@ function onIntakeAction(item: ShippingProcessingProjection, action: 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"
>
{{ primaryFileLabel(task) }}
</div>
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
{{ aggregateStatusLabel(task) }}
</div>
<div
v-if="task.recent_append_count"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
@@ -679,8 +988,16 @@ function onIntakeAction(item: ShippingProcessingProjection, action: 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 visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-surface-muted/40 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div><div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-sky-100 px-2 py-0.5 font-medium text-sky-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.processingFallback') }}</span><button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md border border-brand-300 px-2 py-0.5 font-medium text-brand-700 hover:bg-brand-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div><details v-if="canCancelFile(file)" class="relative shrink-0"><summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary><button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button></details></div>
</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'"
@@ -692,7 +1009,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: 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}`"
@@ -701,7 +1018,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
</button>
<button
v-if="canExpandFileDetails(task)"
v-if="!workbenchMode && canExpandFileDetails(task)"
type="button"
class="inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
data-testid="shipping-processing-expand-files"
@@ -724,7 +1041,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
</button>
</div>
<button
v-else-if="canExpandFileDetails(task)"
v-else-if="!workbenchMode && canExpandFileDetails(task)"
type="button"
class="mt-1.5 inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
data-testid="shipping-processing-expand-files"
@@ -785,7 +1102,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
data-testid="shipping-processing-history-body"
>
<div
v-if="completedTasks.length"
v-if="visibleCompletedTasks.length"
data-testid="shipping-processing-history-completed"
>
<div class="mb-1 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">
@@ -793,7 +1110,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
</div>
<div class="space-y-2">
<article
v-for="task in completedTasks"
v-for="task in visibleCompletedTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -805,6 +1122,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
</div>
<div
v-if="primaryFileLabel(task)"
@@ -813,6 +1131,17 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
>
{{ primaryFileLabel(task) }}
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
{{ taskReasonLabel(task) }}
</div>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-emerald-200/70 pt-2">
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-emerald-50/40 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div><div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-emerald-100 px-2 py-0.5 font-medium text-emerald-700">{{ workbenchFileStatus(file, task) }}</span><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div></div>
</div>
</div>
<button
v-if="recordViewDetailsItem(task)"
type="button"
@@ -827,7 +1156,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
</div>
<div
v-if="historyVersionTasks.length"
v-if="visibleHistoryVersionTasks.length"
data-testid="shipping-processing-history-versions"
>
<div class="mb-1 text-[11px] font-medium text-slate-600 dark:text-slate-300">
@@ -835,7 +1164,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
</div>
<div class="space-y-2">
<article
v-for="task in historyVersionTasks"
v-for="task in visibleHistoryVersionTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -869,7 +1198,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
</div>
<div
v-if="cancelledHistoryTasks.length"
v-if="visibleCancelledHistoryTasks.length"
data-testid="shipping-processing-history-cancelled"
>
<div class="mb-1 text-[11px] font-medium text-slate-500 dark:text-slate-400">
@@ -877,7 +1206,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
</div>
<div class="space-y-2">
<article
v-for="task in cancelledHistoryTasks"
v-for="task in visibleCancelledHistoryTasks"
:key="task.user_task_no"
class="rounded-lg border border-dashed border-default bg-surface/60 px-2.5 py-2 opacity-90"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -5,11 +5,13 @@
* 逻辑:断言不再渲染进度列表/刷新取消/完整 handling 卡片;失败重试与需处理继续处理互斥。
*/
import { mount } from '@vue/test-utils';
import { ref } from 'vue';
import { describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
import type { ShippingOrderExtractionState } from '../../types/chat.types';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
const i18n = createI18n({
legacy: false,
@@ -51,6 +53,477 @@ 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('does not present historical handling items or CTA as current work when the live projection exists', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
status: 'review_required',
availableActions: ['review_candidate'],
primaryNotice: 'candidate_confirmation',
handlingItems: [{
category: 'candidate_confirmation', count: 2, reasonCodes: [],
affectedRefs: [], primaryAction: 'review_candidate',
}],
}),
},
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running' },
summary: { total_files: 1, completed_files: 0, waiting_human_files: 0, failed_files: 0 },
status_groups: {
failed: [], waiting_human: [], processing: [{
user_task_no: 'OT-LIVE', title: 'live.pdf', file_count: 1,
userGroup: 'processing', group: 'processing', aggregateChildren: [],
}], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
expect(wrapper.text()).not.toContain('候选待人工确认');
expect(wrapper.find('[data-testid="shipping-order-extraction-handling-summary"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
});
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',
shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1',
status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'forwarder.eml', documentCount: 3, parsedDocumentCount: 3, candidateCount: 2, customerName: null, poNumber: null }, childOrderTasks: [],
userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' },
aggregateSummary: { intakeNo: 'SNI-1', total: 3, completed: 1, processing: 1, needsAction: 0, failed: 1, stages: ['completed', 'candidate_creating'], reasonCodes: ['upload_rpa_failed'] },
aggregateChildren: [
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1', shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'completed', stage: 'completed', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'done.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null }, childOrderTasks: [], userStatus: 'completed', userStage: 'completed', facts: { uploadState: 'succeeded' } },
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: 'OT-1', shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'candidate.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null }, childOrderTasks: [], userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' } },
],
} as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-EML' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([aggregate]) } } },
});
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('已上传完成 1 · 处理中 1 · 异常 1');
expect(wrapper.text()).not.toContain('已生成候选 3 个文件');
await wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"] button').trigger('click');
expect(wrapper.text()).toContain('candidate.pdf');
expect(wrapper.text()).toContain('处理中 1');
});
it('uses the current three PDF rows instead of stale Run review totals', () => {
const currentPdfRows = ['4210020274.pdf', '4210020272.pdf', '4210020273.pdf'].map((fileName, index) => ({
unitId: index + 1,
documentId: index + 101,
intakeId: 1,
documentType: 'attachment',
fileName,
status: 'candidate_ready' as const,
userVisibleStage: 'candidate_ready',
reasonCode: null,
}));
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
runNo: 'SNER-STALE-COUNTS',
state: buildState({
// 历史 Run/Case 累计不能污染当前邮件的三份有效 PDF 统计。
summary: {
totalDocuments: 20,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 2,
reviewRequiredDocuments: 21,
failedDocuments: 0,
cancelledDocuments: 0,
candidateCount: 3,
},
documents: currentPdfRows,
}),
},
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
});
// 当前卡片的总数、完成率和候选列表必须来自同一份有效 PDF 清单。
expect(wrapper.text()).toContain('共 3 个文件');
expect(wrapper.text()).toContain('0/3 已处理');
expect(wrapper.text()).toContain('已生成候选 3 个文件');
expect(wrapper.text()).not.toContain('23/20 已处理');
expect(wrapper.text()).not.toContain('100% 完成');
});
it('keeps its matched EML card when the side-panel poll temporarily omits the intake', async () => {
const workItems = ref<any[]>([{
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-STABLE', sourceType: 'eml', rootOrderTaskNo: 'OT-STABLE',
shippingNoticeNo: null, runNo: 'SNER-STABLE', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'stable.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
childOrderTasks: [], userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' },
aggregateSummary: { intakeNo: 'SNI-STABLE', total: 2, completed: 0, processing: 2, needsAction: 0, failed: 0, stages: ['candidate_creating'], reasonCodes: [] },
aggregateChildren: [],
}]);
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-STABLE' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: workItems } } },
});
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
// 关键断言:右侧轮询暂时省略本 Intake 时,中间消息卡仍保留其自身的 EML 形态。
workItems.value = [];
await wrapper.vm.$nextTick();
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
});
it('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: '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;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-DETAIL' },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({ status_groups: { failed: [task], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [] } }),
processingWorkItems: ref([]),
},
},
},
});
await wrapper.get('[data-testid="shipping-order-extraction-eml-failed-INTAKE:SNI-DETAIL"] button').trigger('click');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('failed.pdf');
expect(wrapper.text()).toContain('异常 1');
expect(wrapper.text()).toContain('当前步骤需要人工处理');
expect(wrapper.text()).not.toContain('PARSE_FAILED');
expect(wrapper.get('[data-testid="shipping-order-extraction-child-status-OT-CHILD-1"]')
.classes()).toContain('text-rose-600');
});
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',
status: 'processing', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'inside.eml.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
childOrderTasks: [], userStatus: 'running', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
} as any;
const task = { user_task_no: 'INTAKE:SNI-FALLBACK', title: 'inside.eml', file_count: 1, userGroup: 'processing', group: 'processing', aggregateChildren: [], aggregateSummary: { intakeNo: 'SNI-FALLBACK', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: ['document_parsing'], reasonCodes: [] } } as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-FALLBACK' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }),
processingWorkItems: ref([{ workItemType: 'order_intake', workItemNo: 'INTAKE:SNI-FALLBACK', sourceType: 'eml', intakeNo: 'SNI-FALLBACK', aggregateChildren: [child] } as any]),
} } },
});
await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-FALLBACK"] button').trigger('click');
// 状态组出现后,子文件必须完全来自该组;不能用另一份 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 个文件');
// 关键断言:待人工处理不是完成,聊天摘要必须与批次中心 completed_files 同口径。
expect(wrapper.text()).toContain('0/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 () => {
const childA = { workItemType: 'order_task', workItemNo: 'OT-A', sourceType: 'eml', intakeNo: 'SNI-COUNT', sourceSummary: { filename: 'a.pdf', documentId: 101, documentCount: 1 }, status: 'processing', stage: 'document_parsing', userStatus: 'running', facts: { uploadState: 'not_created' } } as any;
const childB = { ...childA, workItemNo: 'OT-B', sourceSummary: { filename: 'b.pdf', documentId: 102, documentCount: 1 } } as any;
const task = { user_task_no: 'INTAKE:SNI-COUNT', title: 'count.eml', file_count: 2, userGroup: 'processing', group: 'processing', aggregateChildren: [childA, childB], aggregateSummary: { intakeNo: 'SNI-COUNT', total: 2, completed: 0, processing: 2, needsAction: 0, failed: 0, stages: [], reasonCodes: [] } } as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-COUNT' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }), processingWorkItems: ref([]) } } },
});
expect(wrapper.text()).toContain('2 个文件');
});
it('renders every projected file when the batch has two documents', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
summary: {
totalDocuments: 2,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 0,
reviewRequiredDocuments: 2,
failedDocuments: 0,
candidateCount: 0,
},
documents: [
{ unitId: 1, documentId: 11, fileName: '4518838154.pdf', status: 'review_required' },
{ unitId: 2, documentId: 12, fileName: '4518838152.pdf', status: 'review_required' },
],
availableActions: ['enter_manual_review'],
healthTips: [],
}),
runNo: 'SNER-2',
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('4518838154.pdf');
expect(wrapper.text()).toContain('4518838152.pdf');
});
it('groups completed attachments under their EML intake instead of mixing unrelated files', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
documents: [
{ unitId: 1, documentId: 11, intakeId: 7, documentType: 'email_body', fileName: 'Forwarder_A.eml', status: 'processing' },
{ unitId: 2, documentId: 12, intakeId: 7, documentType: 'attachment', fileName: 'Packing_List.pdf', status: 'candidate_ready' },
{ unitId: 3, documentId: 13, intakeId: 8, documentType: 'attachment', fileName: 'Customs_Form.pdf', status: 'processing' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
await wrapper.find('button').trigger('click');
const text = wrapper.text();
expect(text.indexOf('Forwarder_A.eml')).toBeLessThan(text.indexOf('Packing_List.pdf'));
expect(text).toContain('Customs_Form.pdf');
expect(text.match(/Packing_List\.pdf/g)?.length).toBe(1);
});
it('groups by email_body document type and renders parse failure as failed', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
status: 'failed',
summary: {
totalDocuments: 2,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 0,
reviewRequiredDocuments: 0,
failedDocuments: 1,
candidateCount: 0,
},
documents: [
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder-message', status: 'failed', reasonCode: 'intake_parse_failed' },
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'po.pdf', status: 'failed', reasonCode: 'intake_parse_failed' },
],
healthTips: [],
currentActivity: null,
}),
},
global: { plugins: [i18n] },
});
const text = wrapper.text();
expect(text).toContain('forwarder-message');
expect(text).toContain('po.pdf');
expect(text).toContain('异常');
expect(wrapper.findAll('.animate-spin').length).toBe(0);
});
it('does not render completed files again as standalone cards', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
summary: {
totalDocuments: 2,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 2,
reviewRequiredDocuments: 0,
failedDocuments: 0,
candidateCount: 2,
},
documents: [
{ unitId: 1, documentId: 11, fileName: '4518838152.pdf', status: 'candidate_ready' },
{ unitId: 2, documentId: 12, fileName: '4518838154.pdf', status: 'candidate_ready' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
const accordion = wrapper.find('button');
await accordion.trigger('click');
expect(wrapper.text().match(/4518838152\.pdf/g)?.length).toBe(1);
});
it('aggregates a fully completed EML intake only inside the completed section', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
summary: {
totalDocuments: 2,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 2,
reviewRequiredDocuments: 0,
failedDocuments: 0,
candidateCount: 2,
},
documents: [
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'candidate_ready' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).not.toContain('forwarder.eml');
expect(wrapper.text()).not.toContain('packing.pdf');
await wrapper.find('button').trigger('click');
expect(wrapper.text()).toContain('forwarder.eml');
expect(wrapper.text()).toContain('packing.pdf');
expect(wrapper.text().match(/forwarder\.eml/g)?.length).toBe(1);
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
expect(wrapper.text()).toContain('已提取');
});
it('keeps a partially completed EML intake outside the completed section', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
documents: [
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'candidate_ready' },
{ unitId: 9, documentId: 9, intakeId: 7, documentType: 'attachment', fileName: 'invoice.pdf', status: 'processing' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
await wrapper.find('button').trigger('click');
expect(wrapper.text()).toContain('forwarder.eml');
expect(wrapper.text()).toContain('invoice.pdf');
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
});
it('shows an EML as exception when a child failed even if the parent status is processing', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
documents: [
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'failed', reasonCode: 'intake_parse_failed' },
],
healthTips: [],
}),
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('异常');
expect(wrapper.text()).not.toContain('解析附件中');
});
it('renders summary title, file count, system processing and no progress/refresh/cancel', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-1' },
@@ -61,7 +534,7 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).toContain('3 个文件');
expect(wrapper.text()).toContain('系统处理中');
expect(wrapper.text()).toContain('处理时间偏长');
expect(wrapper.text()).toContain('查看详情');
expect(wrapper.text()).toContain('打开批次进度中心');
expect(wrapper.text()).not.toContain('刷新状态');
expect(wrapper.text()).not.toContain('取消本次识别');
expect(wrapper.text()).not.toContain('PO-450003.pdf');
@@ -134,7 +607,7 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.text()).toContain('订单候选已生成');
expect(wrapper.text()).toContain('候选待人工确认 · 2 项');
expect(wrapper.text()).toContain('继续处理');
expect(wrapper.text()).toContain('打开批次进度中心');
expect(wrapper.text()).not.toContain('部分附件需人工处理');
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
});
@@ -193,11 +666,11 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).not.toContain('ST-88');
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBe(0);
// 失败优先:唯一主 CTA 为重试解析。
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('重试解析');
// 当前原型将执行入口统一收敛到批次进度中心,旧消息卡不再保留重试 CTA。
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
});
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({
@@ -227,8 +700,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', () => {
@@ -292,10 +766,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({
@@ -315,13 +789,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({
@@ -333,8 +805,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,15 +2,16 @@
* 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, ref } from 'vue';
import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
import { AlertCircle, ArrowRight, CheckCircle2, ChevronDown, CircleX, FileText, LoaderCircle, Mail, RefreshCw, TriangleAlert } from 'lucide-vue-next';
import type {
ShippingOrderExtractionHandlingItemState,
ShippingOrderExtractionFileState,
ShippingOrderExtractionState,
} from '../../types/chat.types';
import type {
@@ -18,6 +19,11 @@ import type {
ShippingOrderExtractionProgressEvent,
} from '../../types/shipping.api.types';
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
import {
resolveShippingProcessingReasonLabel,
resolveShippingProcessingStageLabel,
} from '../../shipping/shippingProcessingLabels';
import {
listWorkspaceShippingOrderExtractionDocuments,
listWorkspaceShippingOrderExtractionProgressEvents,
@@ -35,17 +41,199 @@ 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();
const route = useRoute();
const router = useRouter();
const shippingWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
type ConversationStatusGroups = NonNullable<import('../../types/shipping.api.types').ConversationProcessingProjection['status_groups']>;
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' },
{ key: 'waiting_human', label: 'chat.shippingProcessing.groupWaitingHuman' },
{ key: 'processing', label: 'chat.shippingProcessing.groupProcessing' },
{ key: 'completed', label: 'chat.shippingProcessing.groupCompleted' },
{ key: 'cancelled', label: 'chat.shippingProcessing.groupCancelled' },
{ key: 'archived', label: 'chat.shippingProcessing.groupHistoryRecords' },
] as const;
const expandedStatusGroups = ref(new Set<string>(['failed', 'waiting_human', 'processing']));
const expandedEmlTasks = ref(new Set<string>());
function statusGroupTasks(key: typeof statusGroupDefs[number]['key']) {
return conversationStatusGroups.value?.[key] || [];
}
function statusGroupLabel(key: typeof statusGroupDefs[number]['key']) {
const count = statusGroupTasks(key).length;
return t(statusGroupDefs.find((item) => item.key === key)!.label, { count });
}
function toggleStatusGroup(key: string) {
const next = new Set(expandedStatusGroups.value);
if (next.has(key)) next.delete(key); else next.add(key);
expandedStatusGroups.value = next;
}
function toggleEmlTask(taskNo: string) {
const next = new Set(expandedEmlTasks.value);
if (next.has(taskNo)) next.delete(taskNo); else next.add(taskNo);
expandedEmlTasks.value = next;
}
function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]; user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
if (task.aggregateChildren?.length) return task.aggregateChildren;
// [AUTHORITY] 新会话投影必须自带 EML 子文件;不能从 Run 快照或另一份 work_items 补齐,
// 否则左右面板会出现不同文件数、不同状态的同一封邮件。
if (hasConversationStatusGroups.value) return [];
const projection = statusTaskProjection(task);
if (!projection) return [];
if (projection?.aggregateChildren?.length) return projection.aggregateChildren;
// 后端未返回 aggregate_children 时只展示聚合摘要。禁止用 childOrderTasks 或
// 历史聊天 Run 快照重新推导附件、Candidate、阶段或按钮。
return [];
}
function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[]; file_count?: number | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
// 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 = 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 displayReason(
reason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null,
) {
return resolveShippingProcessingReasonLabel(reason, te, t);
}
/** 新投影有 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.uiState?.stage || child.userStage || child.stage || '').trim();
return resolveShippingProcessingStageLabel(stage, te, t);
}
function statusTaskProjection(task: { user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
const items = shippingWorkflow?.processingWorkItems.value || [];
const intakeNo = String(task.aggregateSummary?.intakeNo || '').trim();
if (intakeNo) {
const intakeMatch = items.find((item) => (
item.sourceType === 'eml'
&& String(item.intakeNo || '').trim() === intakeNo
));
if (intakeMatch) return intakeMatch;
}
return items.find((item) => (
(item.workItemType === 'order_task' || item.workItemType === 'order_intake')
&& String(item.workItemNo || '').trim() === String((task as any).user_task_no || '').trim()
)) || null;
}
function aggregateStatusLabelFromSummary(summary: NonNullable<import('../../types/shipping.api.types').ConversationProcessingUserTask['aggregateSummary']>) {
const parts: string[] = [];
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
return parts.join(' · ');
}
/**
* 当前 Run 对应的 EML Intake 聚合项。
*
* 右侧投影轮询是增量可见的:一次响应暂未带回该 Intake 不能让聊天消息卡
* 降级为旧 Run 卡。消息卡保留最后一次同 Run/用户任务命中的聚合快照,只有
* 同一绑定再次命中时才更新;右侧面板仍直接消费实时投影。
*/
const matchedEmlAggregate = computed(() => {
const runNo = String(props.runNo || props.state.runNo || '').trim();
const userTaskNo = String(props.state.userTaskNo || '').trim();
const items = shippingWorkflow?.processingWorkItems.value || [];
return items.find((item) => (
item.workItemType === 'order_task'
&& item.sourceType === 'eml'
&& Boolean(item.aggregateSummary)
&& (
String(item.runNo || '').trim() === runNo
|| (Boolean(userTaskNo) && String(item.rootOrderTaskNo || '').trim() === userTaskNo)
)
)) || null;
});
const lastMatchedEmlAggregate = ref<ShippingProcessingProjection | null>(null);
watch(matchedEmlAggregate, (item) => {
if (item) lastMatchedEmlAggregate.value = item;
}, { immediate: true });
const emlAggregate = computed(() => (
// [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.uiState ? item.uiState.stage : (item.userStage || item.stage || '')).trim();
return resolveShippingProcessingStageLabel(stage, te, t);
}
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
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 });
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
}
function aggregateSummaryLabel(item: ShippingProcessingProjection): string {
const summary = item.aggregateSummary;
if (!summary) return '';
const parts: string[] = [];
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
return parts.join(' · ');
}
const detailsOpen = ref(false);
const detailsLoading = ref(false);
@@ -57,7 +245,110 @@ const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
const displaySummary = computed(() => props.state.summary);
const handlingItems = computed(() => props.state.handlingItems || []);
/**
* 旧聊天消息中的 handlingItems 是当时的 Run 快照;实时会话投影已返回时,
* 绝不能把它重新展示成当前待办或用它决定 CTA。当前待办仅由后端 work_items
* 与其 ui_state 裁决,旧卡在此模式下只保留历史消息本身。
*/
const handlingItems = computed(() => (
hasConversationStatusGroups.value ? [] : (props.state.handlingItems || [])
));
const fileRows = computed(() => props.state.documents || []);
const isEmailRow = (row: ShippingOrderExtractionFileState) => (
row.documentType === 'email_body' || row.fileName?.toLowerCase().endsWith('.eml')
);
/**
* 返回当前 Run 快照中的唯一业务 PDF,隔离历史 Unit/Review Case 汇总。
* 核心逻辑:优先用稳定 documentId 去重;旧快照缺失时才回退 unitId 或文件名。
*/
const currentBusinessFileRows = computed(() => {
const seen = new Set<string>();
return fileRows.value.filter((row) => {
if (isEmailRow(row)) return false;
const key = row.documentId > 0
? `document:${row.documentId}`
: row.unitId > 0
? `unit:${row.unitId}`
: `filename:${String(row.fileName || '').trim().toLowerCase()}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
});
const hasCurrentBusinessFileRows = computed(() => currentBusinessFileRows.value.length > 0);
const emailRows = computed(() => fileRows.value.filter(isEmailRow));
const isFailedParseRow = (row: ShippingOrderExtractionFileState) => (
row.status === 'failed'
|| row.reasonCode === 'intake_parse_failed'
|| row.userVisibleStage === 'parse_failed'
);
const childRows = (email: ShippingOrderExtractionFileState) => fileRows.value.filter((row) => (
row.unitId !== email.unitId
&& row.intakeId != null
&& row.intakeId === email.intakeId
&& !isEmailRow(row)
));
const candidateEmailGroups = computed(() => emailRows.value
.map((parent) => ({ parent, children: childRows(parent) }))
.filter((group) => group.children.length > 0 && group.children.every((child) => child.status === 'candidate_ready')));
const emailHasFailedChild = (email: ShippingOrderExtractionFileState) => childRows(email).some(isFailedParseRow);
const emailIsCompleted = (email: ShippingOrderExtractionFileState) => {
const children = childRows(email);
return children.length > 0 && children.every((child) => child.status === 'candidate_ready');
};
const candidateEmailUnitIds = computed(() => new Set(
candidateEmailGroups.value.flatMap((group) => [group.parent.unitId, ...group.children.map((child) => child.unitId)]),
));
const candidateStandaloneRows = computed(() => fileRows.value.filter((row) => (
!isEmailRow(row)
&& row.status === 'candidate_ready'
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
)));
const candidateFileCount = computed(() => (
candidateEmailGroups.value.reduce((count, group) => count + group.children.length, 0)
+ candidateStandaloneRows.value.length
));
const activeEmailRows = computed(() => emailRows.value.filter((row) => !candidateEmailUnitIds.value.has(row.unitId)));
const standaloneRows = computed(() => fileRows.value.filter((row) => (
!isEmailRow(row)
&& row.status !== 'candidate_ready'
&& !isFailedParseRow(row)
&& !candidateEmailUnitIds.value.has(row.unitId)
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
)));
const failedRows = computed(() => fileRows.value.filter((row) => (
isFailedParseRow(row)
&& !candidateEmailUnitIds.value.has(row.unitId)
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
)));
const processedCount = computed(() => {
if (hasConversationStatusGroups.value) {
const summary = conversationProcessing.value?.summary;
// [AUTHORITY] “已处理/完成率”只表示已经完成通知生命周期的业务文件。
// waiting_human / failed 只是后端裁决出的待处理事项,不能借用历史 Run 的
// “处理过”口径累计为完成,否则会与批次进度中心的 completed_files 冲突。
return Math.max(0, Number(summary?.completed_files || 0));
}
// 当前 Run 仅表达抽取/候选状态,不能把 candidate_ready 或历史复核 Case 伪装成
// 已完成通知生命周期;生命周期完成数只由会话权威投影下发。
if (hasCurrentBusinessFileRows.value) return 0;
return emlAggregate.value?.aggregateSummary?.completed
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments);
});
const progressPercent = computed(() => {
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));
}
if (hasCurrentBusinessFileRows.value) return currentBusinessFileRows.value.length;
return Math.max(0, Number(emlAggregate.value?.sourceSummary.documentCount ?? props.state.summary.totalDocuments));
});
/**
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
@@ -83,26 +374,20 @@ const isCandidateConfirmationNotice = computed(() => (
)
));
const toneClass = computed(() => {
if (isDuplicateOnlyNotice.value) {
return 'border-violet-200 bg-violet-50/80 text-violet-950 dark:border-violet-800 dark:bg-violet-950/35 dark:text-violet-100';
}
if (isCandidateConfirmationNotice.value) {
return 'border-teal-200 bg-teal-50/80 text-teal-950 dark:border-teal-800 dark:bg-teal-950/35 dark:text-teal-100';
}
switch (props.state.status) {
case 'completed':
return 'border-emerald-200 bg-emerald-50/80 text-emerald-950 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100';
case 'partially_completed':
case 'review_required':
return 'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100';
case 'failed':
case 'cancelled':
return 'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100';
default:
return 'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100';
}
});
function rowStatusLabel(row: ShippingOrderExtractionFileState): string {
if (row.status === 'candidate_ready') return t('chat.shippingProcessing.candidateReady');
if (isFailedParseRow(row)) return t('chat.shippingProcessing.batchException');
if (row.status === 'review_required') return t('chat.shippingProcessing.waitingReview');
const stageKey = `chat.shippingOrderExtractionUserStage.${String(row.userVisibleStage || '').trim()}`;
if (row.userVisibleStage && te(stageKey)) return t(stageKey);
return t('chat.shippingProcessing.batchProcessing');
}
function rowStatusClass(row: ShippingOrderExtractionFileState): string {
if (row.status === 'candidate_ready') return 'text-emerald-500';
if (isFailedParseRow(row)) return 'text-rose-500';
return 'text-blue-500';
}
/**
* 将处理事项类别映射为一句过程通知文案。
@@ -126,6 +411,20 @@ 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');
if (status === 'failed' || status === 'retryable') return t('chat.shippingSessionSummary.processNoticeFailed');
if (status === 'waiting_human') return t('chat.shippingSessionSummary.processNoticeNeedsAction');
return t('chat.shippingProcessing.systemProcessing');
}
if (props.state.cancellation?.requested && !props.state.cancellation?.completedAt && !props.state.terminal) {
return t('chat.shippingOrderExtractionUserStage.cancellation_requested');
}
@@ -177,6 +476,9 @@ const handlingSummaryLine = computed(() => {
if (!first) return '';
const totalCount = items.reduce((sum, item) => sum + Math.max(0, Number(item.count || 0)), 0);
const count = totalCount > 0 ? totalCount : items.length;
// 旧 Run 的 Case 是跨版本历史记录。当前卡片已有 PDF 快照时,数目不一致即说明
// handling 来自另一集合,不能在“本批文件”标题下误导为当前待复核文件。
if (hasCurrentBusinessFileRows.value && count !== currentBusinessFileRows.value.length) return '';
return t('chat.shippingOrderExtractionHandling.summaryLine', {
title: handlingTitle(first),
count,
@@ -187,7 +489,7 @@ const handlingSummaryLine = computed(() => {
* 唯一主 CTA:失败→重试解析;需处理→继续处理;否则不展示。
*/
const primaryChatAction = computed((): { kind: 'retry' | 'continue'; label: string } | null => {
if (props.readonly) return null;
if (props.readonly || hasConversationStatusGroups.value) return null;
const actions = props.state.availableActions || [];
const canRetry = actions.includes('retry_failed_attachments')
|| actions.includes('retry_failed_documents')
@@ -261,7 +563,7 @@ async function loadDetailsDocuments() {
detailsLoading.value = true;
detailsLoadFailed.value = false;
try {
const docsRes = await listWorkspaceShippingOrderExtractionDocuments(runNo).catch(() => null);
const docsRes = await listWorkspaceShippingOrderExtractionDocuments(runNo, props.state.uploadBatchId).catch(() => null);
if (docsRes) {
detailsDocuments.value = Array.isArray(docsRes.items) ? docsRes.items : [];
} else {
@@ -286,7 +588,7 @@ async function loadDetailsProgress() {
progressLoading.value = true;
progressLoadFailed.value = false;
try {
const eventsRes = await listWorkspaceShippingOrderExtractionProgressEvents(runNo).catch(() => null);
const eventsRes = await listWorkspaceShippingOrderExtractionProgressEvents(runNo, props.state.uploadBatchId).catch(() => null);
if (eventsRes) {
progressEvents.value = Array.isArray(eventsRes.items) ? eventsRes.items : [];
} else {
@@ -347,25 +649,151 @@ async function onPrimaryChatAction() {
<template>
<div
class="mb-3 rounded-lg border px-3.5 py-2.5"
:class="toneClass"
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="flex items-start gap-3">
<LoaderCircle
v-if="state.status === 'queued' || state.status === 'processing'"
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
/>
<CircleCheck
v-else-if="state.status === 'completed' || isDuplicateOnlyNotice || isCandidateConfirmationNotice"
class="mt-0.5 h-4 w-4 shrink-0"
/>
<TriangleAlert
v-else-if="state.status === 'partially_completed' || state.status === 'review_required'"
class="mt-0.5 h-4 w-4 shrink-0"
/>
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
<div class="flex items-center justify-between gap-3">
<div class="flex items-center gap-2 text-lg font-semibold">
<LoaderCircle v-if="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: batchFileCount }) }}
</span>
</div>
<p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.batchStatusTitle') }} · {{ statusNotice }}</p>
<div v-for="tip in healthTips" :key="tip.code" class="mt-1 text-sm font-medium text-amber-600">{{ t(`chat.shippingOrderExtractionHealthTip.${tip.code}`) }}</div>
<div v-if="handlingSummaryLine" class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ handlingSummaryLine }}</div>
<div class="mt-4 flex items-end justify-between">
<span class="text-lg font-medium text-blue-600">{{ progressPercent }}% {{ t('chat.shippingProcessing.batchComplete') }}</span>
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ 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 && !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)">
<span class="text-sm font-semibold" :class="group.key === 'failed' ? 'text-rose-600' : group.key === 'waiting_human' ? 'text-amber-700' : group.key === 'completed' ? 'text-emerald-600' : 'text-slate-700 dark:text-slate-200'">{{ statusGroupLabel(group.key) }}</span>
<ChevronDown class="h-4 w-4 transition-transform" :class="expandedStatusGroups.has(group.key) ? 'rotate-180' : ''" />
</button>
<div v-if="expandedStatusGroups.has(group.key)" class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-700">
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="rounded-lg border border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-950/30" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
<div class="flex items-start gap-2">
<Mail class="mt-0.5 h-4 w-4 text-blue-600" />
<div class="min-w-0 flex-1">
<button type="button" class="flex w-full items-center justify-between gap-2 text-left" @click="toggleEmlTask(task.user_task_no)">
<span class="truncate text-sm font-medium">{{ 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="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" 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).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="taskReason(child)" class="text-[11px] text-rose-600">{{ displayReason(taskReason(child)) }}</div>
</div>
<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>
</div>
</article>
</div>
</section>
</template>
</div>
<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" />
<div class="min-w-0 flex-1">
<div class="flex items-center justify-between gap-3">
<span class="truncate font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ emlAggregate.sourceSummary.filename || emlAggregate.intakeNo }}</span>
<span class="rounded border px-2 py-0.5 text-xs" :class="emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emlAggregate.userStatus === 'waiting_human' ? 'border-amber-200 bg-amber-100/70 text-amber-700' : emlAggregate.userStatus === 'completed' ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">
{{ emlAggregate.userStatus === 'completed' ? t('chat.shippingProcessing.aggregate.completed', { count: emlAggregate.aggregateSummary?.completed || 0 }) : emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? t('chat.shippingProcessing.batchException') : emlAggregate.userStatus === 'waiting_human' ? t('chat.shippingProcessing.waitingReview') : t('chat.shippingProcessing.systemProcessing') }}
</span>
</div>
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ aggregateSummaryLabel(emlAggregate) }}</div>
<div v-if="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">
<span>{{ t('chat.shippingProcessing.taskFiles', { count: emlAggregate.sourceSummary.documentCount || 0 }) }}</span>
<ChevronDown class="h-4 w-4 transition-transform" :class="emlAggregateExpanded ? 'rotate-180' : ''" />
</button>
<div v-if="emlAggregateExpanded" class="space-y-1 border-t border-slate-200 px-3 py-2 dark:border-slate-700">
<div v-for="child in emlAggregateChildren" :key="child.workItemNo" class="flex items-center justify-between gap-3 py-1 text-sm">
<span class="min-w-0 truncate">{{ child.sourceSummary.filename || child.workItemNo }}</span>
<span class="shrink-0 text-xs" :class="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-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' : ''" />
</button>
<div v-if="completedExpanded && candidateFileCount" class="space-y-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm dark:border-slate-700 dark:bg-slate-900">
<div v-for="group in candidateEmailGroups" :key="`candidate-email-${group.parent.unitId}`" class="rounded-md border border-blue-100 bg-blue-50/50 px-3 py-2 dark:border-blue-900 dark:bg-blue-950/20">
<div class="flex items-center gap-2 font-medium text-slate-700 dark:text-slate-200"><Mail class="h-4 w-4 text-blue-600" />{{ t('chat.shippingProcessing.emailPrefix') }}{{ group.parent.fileName }}<span class="ml-auto text-emerald-500">{{ t('chat.shippingProcessing.batchExtracted') }}</span></div>
<div class="mt-1 space-y-1 border-l-2 border-blue-200 pl-3 dark:border-blue-800">
<div v-for="row in group.children" :key="`candidate-child-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
</div>
</div>
<div v-for="row in candidateStandaloneRows" :key="`candidate-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
</div>
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20"><Mail class="mt-0.5 h-5 w-5 text-blue-600" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-slate-500">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-blue-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
</div>
<div v-for="row in standaloneRows" :key="row.unitId" class="flex items-center justify-between gap-3 rounded-lg border border-slate-200 bg-white p-3 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900"><span class="flex min-w-0 items-center gap-3"><FileText class="h-5 w-5 text-slate-500" /><span class="truncate">{{ row.fileName }}</span></span><span class="flex items-center gap-2" :class="rowStatusClass(row)">{{ rowStatusLabel(row) }}<RefreshCw v-if="!isFailedParseRow(row)" class="h-4 w-4 animate-spin" /></span></div>
<div v-if="!fileRows.length" class="rounded-lg border border-slate-200 bg-white p-3 text-sm text-slate-500 dark:border-slate-700 dark:bg-slate-900">{{ t('chat.shippingProcessing.batchFilesUnavailable') }}</div>
<div v-for="row in failedRows" :key="`failed-${row.unitId}`" class="rounded-lg border border-rose-200 bg-rose-50 p-3 dark:border-rose-800 dark:bg-rose-950/30"><div class="flex items-center justify-between text-rose-600"><span class="flex items-center gap-2 font-medium"><AlertCircle class="h-5 w-5" />{{ row.fileName }}</span><span class="rounded bg-rose-100 px-2 py-0.5 text-xs">{{ t('chat.shippingProcessing.batchException') }}</span></div><p class="mt-2 pl-7 text-sm">{{ row.explainability?.message || t('chat.shippingProcessing.batchManualVerify') }}</p></div>
</div>
<div class="flex justify-end border-t border-slate-200 bg-indigo-50/60 p-3 dark:border-slate-700 dark:bg-indigo-950/20">
<div class="flex items-center gap-3">
<button
v-if="!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">
<CircleX class="mt-0.5 h-4 w-4 shrink-0" />
<div class="min-w-0 flex-1">
<div
v-if="readonly"
@@ -394,7 +822,7 @@ async function onPrimaryChatAction() {
class="mt-1 text-[11px] opacity-80"
data-testid="shipping-order-extraction-error-request-id"
>
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability.request_id }) }}
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability?.request_id }) }}
</p>
<div
@@ -424,12 +852,12 @@ async function onPrimaryChatAction() {
type="button"
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
data-testid="shipping-order-extraction-primary-action"
:disabled="primaryChatAction.kind === 'retry' && retrying"
:disabled="primaryChatAction?.kind === 'retry' && retrying"
@click="onPrimaryChatAction"
>
{{ primaryChatAction.kind === 'retry' && retrying
{{ primaryChatAction?.kind === 'retry' && retrying
? t('chat.shippingOrderExtractionRetrying')
: primaryChatAction.label }}
: primaryChatAction?.label }}
</button>
<button
v-if="String(props.runNo || '').trim()"
@@ -7,7 +7,7 @@
* 以模态对话框语义呈现(初始焦点、Tab 陷阱、Escape/关闭后焦点恢复);
* 文档与时间线加载失败分别提供就地重试;内部错误码不向普通用户展示。
*/
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { X } from 'lucide-vue-next';
import type { ShippingOrderExtractionState } from '../../types/chat.types';
@@ -42,6 +42,19 @@ const closeButtonRef = ref<HTMLButtonElement | null>(null);
let previouslyFocused: HTMLElement | null = null;
const timelineOpen = ref(false);
const timelineGroups = computed(() => {
const groups = new Map<string, { documentId: number | null; fileName: string; events: ShippingOrderExtractionProgressEvent[] }>();
for (const event of props.progressEvents) {
const documentId = event.document_id != null ? Number(event.document_id) : null;
const document = documentId == null ? null : props.documents.find((item) => Number(item.document_id) === documentId);
const key = documentId == null ? 'run' : `document-${documentId}`;
const group = groups.get(key) || { documentId, fileName: document?.file_name || (documentId == null ? t('chat.shippingOrderExtractionTimelineRunScope') : `Document ${documentId}`), events: [] };
group.events.push(event);
groups.set(key, group);
}
return [...groups.values()];
});
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
@@ -314,28 +327,18 @@ onBeforeUnmount(() => {
>
{{ t('chat.shippingOrderExtractionTimelineEmpty') }}
</div>
<ol v-else class="mt-3 space-y-3">
<li
v-for="event in progressEvents"
:key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`"
class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200"
>
<div class="flex flex-wrap items-center gap-2">
<span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">
{{ t(eventCategoryKey(event)) }}
</span>
<div class="font-medium text-slate-900 dark:text-slate-100">
{{ eventActivityLabel(event) }}
</div>
</div>
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">
{{ eventContextLabel(event) }}
</div>
<div class="mt-1 opacity-70">
{{ eventOccurredAtLabel(event.occurred_at) }}
</div>
</li>
</ol>
<div v-else class="mt-3 space-y-3">
<section v-for="group in timelineGroups" :key="group.documentId == null ? 'run' : group.documentId" class="rounded-md border border-slate-200 px-3 py-2 dark:border-slate-700">
<h4 class="text-xs font-semibold text-slate-900 dark:text-slate-100">{{ group.fileName }}</h4>
<ol class="mt-2 space-y-3">
<li v-for="event in group.events" :key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`" class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200">
<div class="flex flex-wrap items-center gap-2"><span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">{{ t(eventCategoryKey(event)) }}</span><div class="font-medium text-slate-900 dark:text-slate-100">{{ eventActivityLabel(event) }}</div></div>
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">{{ eventContextLabel(event) }}</div>
<div class="mt-1 opacity-70">{{ eventOccurredAtLabel(event.occurred_at) }}</div>
</li>
</ol>
</section>
</div>
</details>
</div>
</aside>
@@ -30,6 +30,7 @@ function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowI
current_run_no: 'SNER-9',
lifecycle_status: 'extracting',
current_stage: 'extracting',
available_actions: ['cancel'],
lock_version: 1,
events: [
{
@@ -113,11 +114,35 @@ describe('ShippingWorkflowItemDetailDrawer', () => {
wrapper.unmount();
});
it('does not infer any write or lifecycle entry from a local file status', () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({
lifecycle_status: 'pending_review',
available_actions: [],
}),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
// 空动作契约表示后端没有授予操作;状态名不得让前端补造入口。
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-action-open-review"]')).toBeNull();
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-item-drawer-reparse"]')).toBeNull();
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).toBeNull();
wrapper.unmount();
});
it('hides cancel for closed items and emits close', async () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({ lifecycle_status: 'closed', closed_reason: 'user_cancelled' }),
item: buildItem({
lifecycle_status: 'closed',
closed_reason: 'user_cancelled',
available_actions: [],
}),
},
global: { plugins: [i18n] },
attachTo: document.body,
@@ -52,17 +52,13 @@ const events = computed((): ShippingWorkflowEvent[] => (
const canCancel = computed(() => {
const actions = props.item?.available_actions;
if (Array.isArray(actions)) return actions.includes('cancel') || Boolean(props.item);
const status = String(props.item?.lifecycle_status || '').trim();
return Boolean(props.item) && !['closed', 'cancelled'].includes(status);
// [AUTHORITY] 文件动作只能由文档级 available_actions 授权;空数组就是明确无权限。
return Array.isArray(actions) && actions.includes('cancel');
});
const canReparse = computed(() => {
const actions = props.item?.available_actions;
if (Array.isArray(actions)) return actions.includes('reparse')
|| ['failed', 'reparse_failed'].includes(String(props.item?.lifecycle_status || '').trim());
// 无契约时 fail-closed,禁止仅凭 pending_review 展示。
return false;
return Array.isArray(actions) && actions.includes('reparse');
});
const reparseActionLabel = computed(() => {
@@ -75,13 +71,8 @@ const reparseActionLabel = computed(() => {
const canOpenReview = computed(() => {
if (!props.item) return false;
const actions = props.item.available_actions;
const status = String(props.item.lifecycle_status || '').trim();
if (Array.isArray(actions)) {
return actions.includes('view_details')
|| actions.includes('enter_manual_review')
|| status === 'pending_review';
}
return status === 'pending_review';
// 生命周期工作台是独立授权,详情/人工复核动作不得隐式升级为生命周期入口。
return Array.isArray(actions) && actions.includes('open_order_review');
});
const filename = computed(() => {
@@ -8,7 +8,7 @@
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
export type ShippingWorkflowReasonAction = 'cancel' | 'reparse';
export type ShippingWorkflowReasonAction = 'cancel' | 'reparse' | 'reparse_batch';
const props = withDefaults(defineProps<{
modelValue: boolean;
@@ -31,13 +31,17 @@ const reasonMissing = ref(false);
const reasonInputRef = ref<HTMLTextAreaElement | null>(null);
const title = computed(() => (
props.action === 'reparse'
props.action === 'reparse_batch'
? t('chat.shippingProcessing.reasonDialog.reparseBatchTitle')
: props.action === 'reparse'
? t('chat.shippingProcessing.reasonDialog.reparseTitle')
: t('chat.shippingProcessing.reasonDialog.cancelTitle')
));
const confirmLabel = computed(() => (
props.action === 'reparse'
props.action === 'reparse_batch'
? t('chat.shippingProcessing.reasonDialog.reparseBatchConfirm')
: props.action === 'reparse'
? t('chat.shippingProcessing.reasonDialog.reparseConfirm')
: t('chat.shippingProcessing.reasonDialog.cancelConfirm')
));
@@ -149,7 +153,7 @@ onBeforeUnmount(() => {
</p>
<label
v-if="action === 'reparse'"
v-if="action === 'reparse' || action === 'reparse_batch'"
class="mt-2 block text-xs text-secondary"
>
{{ t('chat.shippingProcessing.reasonDialog.commentOptional') }}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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> : {}),
@@ -185,6 +185,7 @@ const normalizeShippingOrderExtractionState = (
: null;
return {
status: status as ShippingOrderExtractionState['status'],
uploadBatchId: String(data.uploadBatchId || '').trim() || null,
summary: {
totalDocuments: Math.max(0, Number(rawSummary.totalDocuments || 0)),
pendingDocuments: Math.max(0, Number(rawSummary.pendingDocuments || 0)),
@@ -207,6 +208,27 @@ const normalizeShippingOrderExtractionState = (
: [],
}
: null,
documents: Array.isArray(data.documents)
? data.documents.map((item) => {
const row = item && typeof item === 'object' ? item as Record<string, unknown> : {};
return {
unitId: Math.max(0, Number(row.unitId || 0)),
documentId: Math.max(0, Number(row.documentId || 0)),
intakeId: row.intakeId != null ? Math.max(0, Number(row.intakeId || 0)) || null : null,
documentType: String(row.documentType || '').trim() || null,
fileName: String(row.fileName || '').trim() || null,
status: String(row.status || '').trim(),
userVisibleStage: String(row.userVisibleStage || '').trim() || null,
reasonCode: String(row.reasonCode || '').trim() || null,
explainability: row.explainability && typeof row.explainability === 'object'
? row.explainability as { message?: string | null }
: null,
emailSupplement: row.emailSupplement && typeof row.emailSupplement === 'object'
? row.emailSupplement as { status?: string | null }
: null,
};
})
: [],
selectionPlan: rawSelectionPlan
? {
selectionVersion: String(rawSelectionPlan.selectionVersion || '').trim() || null,
@@ -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;
@@ -722,18 +722,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
});
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
messages,
conversationId,
history,
isShippingNoticeAgent,
currentAgentId,
getActiveShippingTaskId,
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
loadHistory,
refreshShippingActions,
startChatTurn,
msg,
t,
refreshShippingActions,
msg,
t,
});
const {
@@ -970,7 +962,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
const {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
openShippingNoticePicker,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
@@ -1019,20 +1010,16 @@ export function useChatShipping(options: UseChatShippingOptions) {
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
isThinking,
currentAgentId,
getActiveShippingTaskId,
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
messages,
sendShippingMenuMessage,
openShippingInventoryPicker,
openShippingNoticePicker,
openShippingCustomerDialog,
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
startChatTurn,
msg,
t,
msg,
t,
});
const { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers({
@@ -1058,7 +1045,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
loadHistory,
sendShippingMenuMessage,
startChatTurn,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
handleShippingMenuAction,
@@ -0,0 +1,50 @@
/**
* features/chat/composables/useProcurementContractChat.spec.ts
* 用途:验证采购合同双文件选择后的即时可见状态。
* 依赖:Vitest、Vue refs、useProcurementContractChat。
* 逻辑:我方原合同选择后即展示本地文件名,FileAsset 上传仅补充可提交的资产编号。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
import { useProcurementContractChat } from './useProcurementContractChat';
const { uploadFileAsset } = vi.hoisted(() => ({ uploadFileAsset: vi.fn() }));
vi.mock('@/shared/api/file-assets.api', () => ({ uploadFileAsset }));
/** 构建只覆盖原合同选择流程的最小上下文。 */
function createProcurementChat() {
return useProcurementContractChat({
currentAgent: ref({ agent_code: 'procurement_contract_review' }),
currentAgentId: computed(() => 1),
attachments: ref([]),
messages: ref([]),
isThinking: ref(false),
isUploadingAttachments: ref(false),
input: ref(''),
clearAttachments: vi.fn(),
saveLocalMessageToBackend: vi.fn(async () => undefined),
loadHistory: vi.fn(async () => undefined),
msg: { warning: vi.fn(), success: vi.fn(), info: vi.fn() },
t: (key: string) => key,
});
}
describe('useProcurementContractChat original contract selection', () => {
it('shows the selected original contract before its FileAsset upload finishes', async () => {
let resolveUpload: ((value: { asset_no: string; original_filename: string }) => void) | undefined;
uploadFileAsset.mockImplementation(() => new Promise((resolve) => { resolveUpload = resolve; }));
const chat = createProcurementChat();
const file = new File(['original'], '我方原合同.md', { type: 'text/markdown' });
const selecting = chat.handleOriginalContractSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
// 断言上传尚未完成时 UI 仍能立刻渲染已选择的我方原合同。
expect(chat.originalContractName.value).toBe('我方原合同.md');
expect(chat.originalContractAssetNo.value).toBeNull();
resolveUpload?.({ asset_no: 'FA-ORIGINAL-1', original_filename: '我方原合同.md' });
await selecting;
expect(chat.originalContractAssetNo.value).toBe('FA-ORIGINAL-1');
});
});
@@ -131,12 +131,18 @@ export function useProcurementContractChat(options: ProcurementContractChatOptio
const file = input.files?.[0];
input.value = '';
if (!file) return;
// [STEP 1] 选择即展示,避免 FileAsset 网络上传期间输入栏看起来没有响应。
originalContractAssetNo.value = null;
originalContractName.value = file.name;
options.isUploadingAttachments.value = true;
try {
const asset = await uploadFileAsset(file);
// [STEP 2] 上传完成后才允许作为正式比对基准提交。
originalContractAssetNo.value = asset.asset_no;
originalContractName.value = asset.original_filename || file.name;
} catch (e: unknown) {
// 上传失败的临时卡片不可作为基准,必须移除,避免显示与提交状态不一致。
clearOriginalContract();
options.msg.warning(e instanceof Error ? e.message : options.t('chat.procurementContract.uploadFailed'));
} finally {
options.isUploadingAttachments.value = false;
@@ -15,7 +15,6 @@ export const SHIPPING_MENU_ACTION_SPECS: Record<
ShippingMenuAction,
{ id: string; label: string; message: string; variant: 'primary' | 'secondary' | 'danger' }
> = {
upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' },
retry_rpa: { id: 'retry_rpa', label: '重新获取库存', message: '重新获取库存', variant: 'secondary' },
confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' },
reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' },
@@ -5,6 +5,8 @@
* 逻辑:断言 1920/1440/1366 下主滚动唯一、底栏 sticky;默认浮窗不进网格;固定侧栏才用双栏 token。
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
/** 方案冻结的三档验收视口。 */
@@ -26,6 +28,12 @@ const PRIMARY_SCROLL_CLASS = 'overflow-y-auto';
/** 浮动证据面板默认锚点(避开 sticky 底栏)。 */
const FLOAT_ANCHOR = { bottomClass: 'bottom-20', zIndexClass: 'z-30' };
const lifecycleNavigationPath = resolve(
__dirname,
'../components/shipping-review/ReviewLifecycleStageNavigation.vue',
);
const reviewWorkbenchPath = resolve(__dirname, '../views/ShippingOrderReviewView.vue');
describe('shipping order review workbench viewport layout contract', () => {
it('freezes three desktop acceptance viewports from the layout plan', () => {
// 关键断言:验收矩阵不得悄悄缩减档位。
@@ -56,4 +64,16 @@ describe('shipping order review workbench viewport layout contract', () => {
expect(share1920).toBeGreaterThanOrEqual(0.65);
expect(share1440).toBeGreaterThanOrEqual(0.62);
});
it('keeps four lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
const lifecycleNavigation = readFileSync(lifecycleNavigationPath, 'utf8');
const reviewWorkbench = readFileSync(reviewWorkbenchPath, 'utf8');
// 关键断言:接收解析为第四阶段;必须断言真实导航组件,不能只验证 spec 内常量。
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-4"');
// sidebar/sidebar_search 是唯一允许预留 16rem 的模式;tabs/hidden/narrow 均落入 contents。
expect(reviewWorkbench).toMatch(/reviewDocumentNavigationMode\.value === 'sidebar'\s*\|\|\s*reviewDocumentNavigationMode\.value === 'sidebar_search'/);
expect(reviewWorkbench).toMatch(/:class="reviewDocumentNavigationUsesSidebar\s*\? 'grid gap-2 lg:grid-cols-\[16rem_minmax\(0,1fr\)\] lg:items-start lg:gap-3'\s*:\s*'contents'"/);
expect(reviewWorkbench).not.toMatch(/reviewDocumentNavigationMode\.value === '(?:tabs|hidden|narrow)'\s*\?\s*'[^']*16rem/);
});
});
@@ -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;
}
@@ -82,7 +82,6 @@ export function buildReviewWorkbenchDisplayCase(
build_eligibility: shellSource?.draft?.build_eligibility ?? undefined,
},
available_actions: [],
conversation_allowed_actions: [],
formal_editable_field_ids: [],
order_data_version: null,
llm_suggestions: [],
@@ -2,8 +2,7 @@
* features/chat/shipping-review/useShippingOrderReview.spec.ts
* 用途:阶段 3 复核页历史版本只读、草稿版本冲突、建单资格门禁、库存候选与路由恢复写入冒烟。
* 依赖:isReviewCaseHistorical / isDraftVersionMismatchError / summarizeDraftConflictDiff /
* isBuildConfirmBlocked / lineNeedsManualInventorySelection /
* lineHasPendingRoutingSuggestion / lineNeedsInventoryRoutingRecovery、useShippingOrderReview。
* isBuildConfirmBlocked / lineNeedsInventoryRoutingRecovery、useShippingOrderReview。
* 逻辑:断言 superseded 只读、版本冲突码识别、差异摘要、confirm 门禁、inventory PUT、
* reroute/adopt/keep 与 suggestion_pending 行筛选。
*/
@@ -18,8 +17,6 @@ import {
isReviewCaseHistorical,
isReviewReadOnly,
isReviewWorkItemClosed,
lineNeedsManualInventorySelection,
lineHasPendingRoutingSuggestion,
lineNeedsInventoryRoutingRecovery,
mapReviewContextLifecycleStatus,
REVIEW_BUILD_ELIGIBILITY_BLOCKED,
@@ -42,22 +39,25 @@ const api = vi.hoisted(() => ({
getRun: vi.fn(),
getQueue: vi.fn(),
getEvidence: vi.fn(),
getPreview: vi.fn(),
getIntakeParseContext: vi.fn(),
getExtractionRun: vi.fn(),
getProcessingWorkItem: vi.fn(),
reparseDocument: vi.fn(),
putInventoryCandidates: vi.fn(),
rerouteInventoryRouting: vi.fn(),
adoptInventoryRoutingSuggestion: vi.fn(),
keepManualInventoryRouting: vi.fn(),
confirmCase: vi.fn(),
validateDraft: vi.fn(),
}));
@@ -72,17 +72,18 @@ vi.mock('../api/shipping.api', () => ({
getWorkspaceShippingOrderReviewRun: api.getRun,
getWorkspaceShippingOrderReviewQueue: api.getQueue,
getWorkspaceShippingOrderReviewEvidence: api.getEvidence,
getWorkspaceShippingOrderReviewPreview: api.getPreview,
getWorkspaceShippingOrderReviewIntakeParseContext: api.getIntakeParseContext,
getWorkspaceShippingOrderExtractionRun: api.getExtractionRun,
getWorkspaceShippingProcessingWorkItem: api.getProcessingWorkItem,
putWorkspaceShippingOrderReviewInventoryCandidates: api.putInventoryCandidates,
postWorkspaceShippingOrderReviewInventoryRoutingReroute: api.rerouteInventoryRouting,
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion: api.adoptInventoryRoutingSuggestion,
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual: api.keepManualInventoryRouting,
confirmWorkspaceShippingOrderReviewCase: api.confirmCase,
@@ -96,7 +97,7 @@ vi.mock('../api/shipping.api', () => ({
deleteWorkspaceShippingOrderReviewLine: vi.fn(),
validateWorkspaceShippingOrderReviewDraft: vi.fn(),
validateWorkspaceShippingOrderReviewDraft: api.validateDraft,
createWorkspaceShippingOrderReviewManualDraft: vi.fn(),
@@ -335,36 +336,6 @@ describe('build eligibility helpers', () => {
it('detects lines needing manual inventory selection', () => {
expect(lineNeedsManualInventorySelection({ can_build: true })).toBe(false);
expect(lineNeedsManualInventorySelection({
can_build: false,
candidate_inventory_source_codes: ['DSV360_AWSDU'],
})).toBe(true);
expect(lineNeedsManualInventorySelection({
can_build: false,
block_reason: 'require_manual_review',
})).toBe(true);
expect(lineNeedsManualInventorySelection({
can_build: false,
block_reason: 'customer_unresolved',
})).toBe(false);
});
});
@@ -381,10 +352,26 @@ describe('useShippingOrderReview build eligibility writes', () => {
});
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{ case_no: 'CASE-1', document_id: 1, status: 'draft', issue_count: 0, available_actions: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockRejectedValue(new Error('preview unavailable'));
api.getIntakeParseContext.mockImplementation(async (caseNo: string) => ({
case_no: caseNo,
attachment: {
document_id: caseNo === 'CASE-2' ? 2 : 1,
filename: caseNo === 'CASE-2' ? 'second.pdf' : 'order.pdf',
mime_type: 'application/pdf',
preview_kind: 'pdf',
},
email: null,
}));
api.getProcessingWorkItem.mockRejectedValue(
Object.assign(new Error('not found'), { name: 'BusinessError', status: 404, code: 'NOT_FOUND' }),
);
@@ -403,7 +390,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
it('exposes buildEligibility and manualInventoryLines from active case draft', async () => {
it('exposes buildEligibility and automatic routing recovery lines from active case draft', async () => {
const review = useShippingOrderReview();
@@ -413,9 +400,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.canConfirmBuild.value).toBe(false);
expect(review.manualInventoryLines.value).toHaveLength(1);
expect(review.manualInventoryLines.value[0]?.line_key).toBe('line-1');
expect(review.routingRecoveryLines.value).toHaveLength(1);
expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-1');
});
@@ -436,6 +422,180 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.previewUrl.value).toMatch(/^blob:/);
});
it('applies the latest Case returned by save and validate', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
api.validateDraft.mockResolvedValue({
case: buildCase({
draft: { ...buildCase().draft!, draft_version: 3 },
}),
resume_outcome: { outcome: 'auto_create_enqueued' },
});
await review.validate();
expect(api.validateDraft).toHaveBeenCalledWith('CASE-1', 2);
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
});
it('refreshes the current Case silently without entering the PDF-switch loading state', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
const blob = new Blob(['%PDF'], { type: 'application/pdf' });
api.getPreview.mockResolvedValue(blob);
await review.ensurePreviewLoaded('CASE-1');
api.getCase.mockResolvedValue(buildCase({
draft: { ...buildCase().draft!, draft_version: 3 },
}));
await review.reloadLatestDraft();
// Gate 操作后的同步不能冒充 PDF 切换:保留工作面和已加载预览,不展示大骨架。
expect(review.caseSwitchLoading.value).toBe(false);
expect(review.caseSwitchFailed.value).toBe(false);
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
expect(review.previewCaseNo.value).toBe('CASE-1');
expect(review.previewUrl.value).toMatch(/^blob:/);
});
it('discards a stale preview success after Case A switches to Case B', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let resolveA: ((value: Blob) => void) | null = null;
let resolveB: ((value: Blob) => void) | null = null;
api.getPreview.mockImplementation((caseNo: string) => new Promise<Blob>((resolve) => {
if (caseNo === 'CASE-1') resolveA = resolve;
if (caseNo === 'CASE-2') resolveB = resolve;
}));
const previewA = review.ensurePreviewLoaded('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.selectCase('CASE-2');
// 关键断言:切换立即清除旧 URL;B 必须启动独立预览请求,不能复用 A in-flight。
expect(review.previewUrl.value).toBe('');
const previewB = review.ensurePreviewLoaded('CASE-2');
expect(api.getPreview).toHaveBeenNthCalledWith(1, 'CASE-1');
expect(api.getPreview).toHaveBeenNthCalledWith(2, 'CASE-2');
resolveA?.(new Blob(['A'], { type: 'application/pdf' }));
await expect(previewA).resolves.toBe(false);
expect(review.previewUrl.value).toBe('');
resolveB?.(new Blob(['B'], { type: 'application/pdf' }));
await expect(previewB).resolves.toBe(true);
expect(review.previewCaseNo.value).toBe('CASE-2');
expect(review.previewUrl.value).toMatch(/^blob:/);
});
it('discards a stale preview failure after Case A switches to Case B', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let rejectA: ((reason?: unknown) => void) | null = null;
let resolveB: ((value: Blob) => void) | null = null;
api.getPreview.mockImplementation((caseNo: string) => new Promise<Blob>((resolve, reject) => {
if (caseNo === 'CASE-1') rejectA = reject;
if (caseNo === 'CASE-2') resolveB = resolve;
}));
const previewA = review.ensurePreviewLoaded('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.selectCase('CASE-2');
const previewB = review.ensurePreviewLoaded('CASE-2');
rejectA?.(new Error('stale preview failure'));
await expect(previewA).resolves.toBe(false);
// 关键断言:A 的失败不能把 B 标为预览失败或清空 B 的进行态。
expect(review.previewLoadFailed.value).toBe(false);
expect(review.previewLoading.value).toBe(true);
resolveB?.(new Blob(['B'], { type: 'application/pdf' }));
await expect(previewB).resolves.toBe(true);
expect(review.previewCaseNo.value).toBe('CASE-2');
expect(review.previewLoadFailed.value).toBe(false);
});
it('loads intake parse context on demand for the active Case and clears it before a new Case resolves', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(api.getIntakeParseContext).not.toHaveBeenCalled();
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(api.getIntakeParseContext).toHaveBeenCalledWith('CASE-1');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
api.getCase.mockImplementation((caseNo: string) => caseNo === 'CASE-2'
? new Promise<ShippingOrderReviewCase>((resolve) => { resolveCase = resolve; })
: Promise.resolve(buildCase({ case_no: caseNo })));
const pending = review.selectCase('CASE-2');
// 关键断言:切换附件期间不得展示 CASE-1 的 EML/附件上下文。
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoading.value).toBe(false);
resolveCase?.(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await pending;
await review.ensureIntakeParseContextLoaded('CASE-2');
expect(api.getIntakeParseContext).toHaveBeenLastCalledWith('CASE-2');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-2');
});
it('does not retain an older intake context when the next Case context request fails', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.selectCase('CASE-2');
api.getIntakeParseContext.mockRejectedValueOnce(new Error('context unavailable'));
await expect(review.ensureIntakeParseContextLoaded('CASE-2')).resolves.toBe(false);
// 关键断言:失败只显示本次错误,不得回退为上一附件的邮件正文。
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoadFailed.value).toBe(true);
});
it('keeps the latest same-Case intake context when an older success resolves last', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let resolveFirst: ((value: Record<string, unknown>) => void) | null = null;
let resolveSecond: ((value: Record<string, unknown>) => void) | null = null;
api.getIntakeParseContext
.mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))
.mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
const first = review.ensureIntakeParseContextLoaded('CASE-1');
const second = review.ensureIntakeParseContextLoaded('CASE-1');
resolveSecond?.({ case_no: 'CASE-1', attachment: { document_id: 2, filename: 'latest.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
await second;
resolveFirst?.({ case_no: 'CASE-1', attachment: { document_id: 1, filename: 'stale.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
await first;
// 关键断言:同一 Case 的旧成功响应不可覆盖后发请求的附件/EML。
expect(review.intakeParseContext.value?.attachment.filename).toBe('latest.pdf');
expect(review.intakeParseLoadFailed.value).toBe(false);
});
it('keeps the latest same-Case success when an older request fails last', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let rejectFirst: ((reason?: unknown) => void) | null = null;
let resolveSecond: ((value: Record<string, unknown>) => void) | null = null;
api.getIntakeParseContext
.mockImplementationOnce(() => new Promise((_, reject) => { rejectFirst = reject; }))
.mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
const first = review.ensureIntakeParseContextLoaded('CASE-1');
const second = review.ensureIntakeParseContextLoaded('CASE-1');
resolveSecond?.({ case_no: 'CASE-1', attachment: { document_id: 2, filename: 'latest.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
await second;
rejectFirst?.(new Error('stale failure'));
await first;
// 关键断言:旧失败不得清空新成功结果或重新标记本次加载失败。
expect(review.intakeParseContext.value?.attachment.filename).toBe('latest.pdf');
expect(review.intakeParseLoadFailed.value).toBe(false);
expect(review.intakeParseLoading.value).toBe(false);
});
it('clears activeCase immediately while switching and keeps empty shell on failure (UI-01)', async () => {
// 关键断言:loading 期间不得保留旧 Case 业务对象;失败后也不得回显旧值。
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
@@ -509,76 +669,6 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.activeCase.value?.case_no).toBe('CASE-B');
});
it('submits inventory candidates via PUT and refreshes case', async () => {
const updated = buildCase({
draft: {
...buildCase().draft!,
draft_version: 3,
build_eligibility: {
can_build: true,
status: 'ready',
line_projections: [{
line_key: 'line-1',
line_index: 0,
can_build: true,
selection_mode: 'manual',
manual_reason: 'Confirmed with planner',
candidate_inventory_source_codes: ['DSV360_AWSDU'],
}],
},
},
});
api.putInventoryCandidates.mockResolvedValue(updated);
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.setLineInventoryCandidates('line-1', ['DSV360_AWSDU'], 'Confirmed with planner');
expect(api.putInventoryCandidates).toHaveBeenCalledWith('CASE-1', 'line-1', {
expected_draft_version: 2,
source_codes: ['DSV360_AWSDU'],
reason: 'Confirmed with planner',
});
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
expect(review.buildEligibility.value?.can_build).toBe(true);
expect(review.canConfirmBuild.value).toBe(true);
});
it('blocks confirm when build eligibility cannot build', async () => {
const review = useShippingOrderReview();
@@ -666,7 +756,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
vi.useRealTimers();
});
it('notifies the conversation workflow when auto progress reaches a retryable terminal state', async () => {
it('keeps polling after a recoverable RPA failure so a later callback can refresh the workflow', async () => {
vi.useFakeTimers();
const onWorkflowRefresh = vi.fn();
const readyCase: ShippingOrderReviewCase = {
@@ -681,7 +771,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
api.getPreview.mockResolvedValue({ preview_url: '' });
api.getProcessingWorkItem
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'building_order' })
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'retryable', retryable: true });
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'retryable', retryable: true })
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'completed' });
api.confirmCase.mockResolvedValue({
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
workflow_id: 'WF-1', case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' }, auto_progress_started: true,
@@ -694,6 +785,10 @@ describe('useShippingOrderReview build eligibility writes', () => {
await Promise.resolve();
expect(onWorkflowRefresh).toHaveBeenCalled();
// RPA 可重试失败不是工作流关闭;必须继续读取后续成功回调的 Projection。
expect(review.workflowProgressPolling.value).toBe(true);
await vi.advanceTimersByTimeAsync(2600);
await Promise.resolve();
expect(review.workflowProgressPolling.value).toBe(false);
review.stopWorkflowProgressPolling();
vi.useRealTimers();
@@ -719,7 +814,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(true);
});
it('leaves OT unset during reparse polling when candidate-bound case lacks order_task_no', async () => {
it('leaves OT unset while waiting for a reparse Case when candidate-bound case lacks order_task_no', async () => {
vi.useFakeTimers();
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
@@ -752,11 +847,11 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
review.stopReparseProgressPolling();
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
it('polls reparse progress and loads the new review version when ready', async () => {
it('loads the new review version when completed reparse has activated its Stream Case', async () => {
vi.useFakeTimers();
let reparsePollCount = 0;
api.reparseDocument.mockImplementation(async () => ({
@@ -765,17 +860,26 @@ describe('useShippingOrderReview build eligibility writes', () => {
}));
api.getRun.mockImplementation(async (runNo: string) => ({
run_no: runNo,
status: runNo === 'RUN-2' ? 'review_required' : 'review_required',
status: runNo === 'RUN-2' ? 'completed' : 'review_required',
summary: {},
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', status: 'draft', issue_count: 0 }],
}));
api.getQueue.mockImplementation(async (runNo: string) => ({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1',
document_id: 1,
source_run_no: runNo,
status: 'draft', issue_count: 0, available_actions: [],
}],
}));
api.getExtractionRun.mockImplementation(async (runNo: string) => {
reparsePollCount += 1;
const ready = runNo === 'RUN-2' && reparsePollCount >= 2;
return {
run_no: runNo,
status: ready ? 'review_required' : 'extracting',
current_activity: { user_visible_stage: ready ? 'review_required' : 'extracting' },
status: ready ? 'completed' : 'extracting',
current_activity: { user_visible_stage: ready ? 'completed' : 'extracting' },
};
});
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
@@ -787,19 +891,16 @@ describe('useShippingOrderReview build eligibility writes', () => {
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
expect(review.reparseProgressActive.value).toBe(true);
await vi.advanceTimersByTimeAsync(2600);
await Promise.resolve();
expect(review.reparseProgressStage.value).toBe('draft_ready');
expect(review.reparseProgressPolling.value).toBe(false);
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
review.stopReparseProgressPolling();
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
it('loads a partially completed reparse result and clears the read-only progress state', async () => {
it('loads a partially completed reparse result without a legacy read-only progress state', async () => {
vi.useFakeTimers();
api.reparseDocument.mockImplementation(async () => ({
run: { run_no: 'RUN-PARTIAL', items: [], summary: {} },
@@ -816,6 +917,15 @@ describe('useShippingOrderReview build eligibility writes', () => {
status: runNo === 'RUN-PARTIAL' ? 'partially_completed' : 'review_required',
current_activity: { user_visible_stage: 'review_required' },
}));
api.getQueue.mockImplementation(async (runNo: string) => ({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: runNo === 'RUN-PARTIAL' ? 'CASE-PARTIAL' : 'CASE-1',
document_id: 1,
source_run_no: runNo,
status: 'draft', issue_count: 0, available_actions: [],
}],
}));
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-PARTIAL' ? 'RUN-PARTIAL' : 'RUN-1',
@@ -829,59 +939,69 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.reviewRun.value?.run_no).toBe('RUN-PARTIAL');
expect(review.activeCase.value?.case_no).toBe('CASE-PARTIAL');
expect(review.reparseProgressStage.value).toBe('draft_ready');
expect(review.reparseProgressPolling.value).toBe(false);
expect(review.reparseProgressActive.value).toBe(false);
expect(review.isReadOnly.value).toBe(false);
expect(review.statusMessage.value).not.toBe('reparse_in_progress');
review.stopReparseProgressPolling();
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
it('resolves the replacement run when superseded_by_run_no is set', async () => {
it('opens the Stream current version instead of retaining a historical Case', async () => {
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{ case_no: 'CASE-2', document_id: 1, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }],
});
api.getRun.mockImplementation(async (runNo: string) => ({
run_no: runNo, summary: {},
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', document_id: 1, status: 'draft', issue_count: 0 }],
}));
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo, run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
review.reviewRun.value!.superseded_by_run_no = 'RUN-2';
api.getRun.mockResolvedValue({
run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', status: 'draft', issue_count: 0 }],
});
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2' }));
const target = await review.openCurrentVersion();
expect(target).toEqual({ runNo: 'RUN-2', caseNo: 'CASE-2' });
expect(review.activeCase.value?.case_no).toBe('CASE-2');
});
it('resolves the replacement run when the historical item still points at the open case', async () => {
it('does not jump to a different PDF when the Stream contains multiple documents', async () => {
api.getRun.mockImplementation(async (runNo: string) => runNo === 'RUN-1'
? {
run_no: 'RUN-1',
run_no: runNo,
summary: {},
items: [{ case_no: 'CASE-1', status: 'superseded', issue_count: 0 }],
}
: {
run_no: 'RUN-2',
run_no: runNo,
summary: {},
items: [{ case_no: 'CASE-2', status: 'draft', issue_count: 0 }],
items: [{ case_no: runNo === 'RUN-3' ? 'CASE-1-NEW' : 'CASE-2', status: 'draft', issue_count: 0 }],
});
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
status: caseNo === 'CASE-2' ? 'draft' : 'superseded',
run_no: caseNo === 'CASE-1-NEW' ? 'RUN-3' : caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
status: caseNo === 'CASE-1-NEW' || caseNo === 'CASE-2' ? 'draft' : 'superseded',
}));
api.getQueue.mockResolvedValue({
summary: { total: 2, needs_action: 2, processing: 0, completed: 0 },
items: [
{ case_no: 'CASE-1-NEW', document_id: 1, source_run_no: 'RUN-3', status: 'draft', issue_count: 0, available_actions: [] },
{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] },
],
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
review.reviewRun.value!.superseded_by_run_no = 'RUN-2';
const target = await review.openCurrentVersion();
expect(target).toEqual({ runNo: 'RUN-2', caseNo: 'CASE-2' });
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
expect(target).toEqual({ runNo: 'RUN-3', caseNo: 'CASE-1-NEW' });
expect(review.reviewRun.value?.run_no).toBe('RUN-3');
expect(review.activeCase.value?.case_no).toBe('CASE-1-NEW');
});
it('shows a terminal failed stage when reparse fails', async () => {
it('stops waiting when reparse fails without exposing a synthetic stage', async () => {
vi.useFakeTimers();
api.reparseDocument.mockResolvedValue({
run: { run_no: 'RUN-FAILED', items: [], summary: {} }, reused: false,
@@ -896,9 +1016,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
await vi.advanceTimersByTimeAsync(2600);
await Promise.resolve();
expect(review.reparseProgressStage.value).toBe('failed');
expect(review.reparseProgressPolling.value).toBe(false);
review.stopReparseProgressPolling();
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
@@ -932,24 +1051,14 @@ describe('inventory routing recovery', () => {
vi.clearAllMocks();
});
it('detects pending suggestion and recovery lines beyond manual selection', () => {
// 关键断言:suggestion_pending 即使 can_build true 也应进入恢复集合。
expect(lineHasPendingRoutingSuggestion({ suggestion_pending: true })).toBe(true);
expect(lineNeedsInventoryRoutingRecovery({
can_build: true,
suggestion_pending: true,
})).toBe(true);
it('detects automatic routing recovery lines', () => {
expect(lineNeedsInventoryRoutingRecovery({
can_build: true,
unavailable_source_codes: ['OFFLINE_SRC'],
})).toBe(true);
expect(lineNeedsManualInventorySelection({
can_build: true,
suggestion_pending: true,
})).toBe(false);
});
it('exposes routingRecoveryLines for suggestion_pending rows', async () => {
it('exposes routingRecoveryLines for blocked rule rows', async () => {
api.getCase.mockResolvedValue(buildCase({
draft: {
...buildCase().draft!,
@@ -959,8 +1068,8 @@ describe('inventory routing recovery', () => {
line_projections: [{
line_key: 'line-pending',
line_index: 0,
can_build: true,
suggestion_pending: true,
can_build: false,
block_reason: 'inventory_source_unavailable',
rule_suggestion_source_codes: ['DSV360_AWSDU'],
candidate_inventory_source_codes: ['DSV360_AWSHK'],
selection_mode: 'manual',
@@ -970,7 +1079,6 @@ describe('inventory routing recovery', () => {
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(review.manualInventoryLines.value).toHaveLength(0);
expect(review.routingRecoveryLines.value).toHaveLength(1);
expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-pending');
});
@@ -993,32 +1101,6 @@ describe('inventory routing recovery', () => {
uuidSpy.mockRestore();
});
it('adopts and keeps inventory routing suggestions via POST APIs', async () => {
const updated = buildCase({ draft: { ...buildCase().draft!, draft_version: 4 } });
api.adoptInventoryRoutingSuggestion.mockResolvedValue(updated);
api.keepManualInventoryRouting.mockResolvedValue(updated);
const uuidSpy = vi.spyOn(crypto, 'randomUUID')
.mockReturnValueOnce('idem-adopt-1')
.mockReturnValueOnce('idem-keep-1');
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.adoptInventoryRoutingSuggestion('line-1', 'use rule');
await review.keepManualInventoryRouting('line-1', 'keep manual');
expect(api.adoptInventoryRoutingSuggestion).toHaveBeenCalledWith('CASE-1', 'line-1', {
expected_draft_version: 2,
idempotency_key: 'idem-adopt-1',
reason: 'use rule',
});
expect(api.keepManualInventoryRouting).toHaveBeenCalledWith('CASE-1', 'line-1', {
expected_draft_version: 4,
idempotency_key: 'idem-keep-1',
reason: 'keep manual',
});
uuidSpy.mockRestore();
});
it('sets draftConflict on 409 VERSION_MISMATCH during reroute', async () => {
api.rerouteInventoryRouting.mockRejectedValue(
new BusinessError({ message: 'stale', code: REVIEW_DRAFT_VERSION_MISMATCH }),
@@ -5,23 +5,23 @@
* 逻辑:按 runNo 加载 Review Run/Case;合成 ShippingReviewProgressContext;
* OT 绑定 Case.order_task_no / Candidate;切换 Case 时清空 activeCase(纯 skeleton,禁止旧值 DOM);
* 409 REVIEW_DRAFT_VERSION_MISMATCH 冲突处理;build_eligibility 驱动 confirm/reroute;
* 重识别轮询 extraction-run;PDF Blob 由 ensurePreviewLoaded 按需加载。
* 重识别后刷新正式 Run/Case/Gate 投影;PDF Blob 由 ensurePreviewLoaded 按需加载。
*/
import { computed, getCurrentInstance, onBeforeUnmount, ref } from 'vue';
import { BusinessError } from '@/shared/api/client';
import {
addWorkspaceShippingOrderReviewLine,
createWorkspaceShippingOrderReviewManualDraft,
createWorkspaceShippingOrderReviewReplacementIntake,
createWorkspaceShippingOrderReviewReplacementRun,
copyWorkspaceShippingOrderReviewLine,
confirmWorkspaceShippingOrderReviewCase,
deleteWorkspaceShippingOrderReviewLine,
getWorkspaceShippingOrderReviewCase,
getWorkspaceShippingOrderReviewEvidence,
getWorkspaceShippingOrderReviewIntakeParseContext,
getWorkspaceShippingOrderReviewPreview,
getShippingNoticeIntake,
getWorkspaceShippingOrderReviewEmailEvidencePreview,
getWorkspaceShippingOrderReviewRun,
getWorkspaceShippingOrderReviewQueue,
getWorkspaceShippingOrderExtractionRun,
patchWorkspaceShippingOrderReviewHeaderField,
patchWorkspaceShippingOrderReviewLineField,
@@ -29,9 +29,6 @@ import {
updateWorkspaceShippingNoticeLine,
markWorkspaceShippingOrderReviewNonOrder,
markWorkspaceShippingOrderReviewQualityIssue,
putWorkspaceShippingOrderReviewInventoryCandidates,
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion,
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual,
postWorkspaceShippingOrderReviewInventoryRoutingReroute,
reparseWorkspaceShippingOrderReviewDocument,
validateWorkspaceShippingOrderReviewDraft,
@@ -46,15 +43,17 @@ import type {
ShippingOrderReviewCaseLoadingContext,
ShippingOrderReviewCaseSnapshot,
ShippingOrderReviewEvidence,
ShippingOrderReviewIntakeParseContext,
ShippingOrderReviewLlmAdjudicationPayload,
ShippingOrderReviewLlmSuggestion,
ShippingOrderExtractionRun,
ShippingOrderReviewRun,
ShippingOrderReviewQueue,
ShippingOrderReviewEmailEvidencePreview,
ShippingReviewProgressContext,
ShippingReviewProgressVersion,
ShippingWorkflowItemLifecycleStatus,
} from '../types/shipping.api.types';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import { useShippingProcessingWorkItem } from '../shipping/useShippingProcessingWorkItem';
/** ???????????? */
@@ -72,15 +71,6 @@ export const REVIEW_DRAFT_VERSION_MISMATCH = 'SHIPPING.REVIEW_DRAFT_VERSION_MISM
/** ?????????? confirm ????? */
export const REVIEW_BUILD_ELIGIBILITY_BLOCKED = 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED';
/** ????????????????????????? */
const INVENTORY_BLOCK_REASONS = new Set([
'require_manual_review',
'no_inventory_source_candidates',
'manual_inventory_source_reason_required',
'manual_inventory_source_invalid',
'inventory_source_unresolved',
]);
/** ????????????/??????????? Case ??? */
export type DraftVersionConflict = {
localVersion: number;
@@ -179,25 +169,6 @@ export function isBuildConfirmBlocked(eligibility?: ShippingOrderReviewBuildElig
* ????????????????????
* ??????? can_build ? false ????????????????
*/
export function lineNeedsManualInventorySelection(
line: ShippingOrderReviewBuildEligibilityLineProjection,
): boolean {
if (line.can_build !== false) return false;
const codes = line.candidate_inventory_source_codes || [];
if (codes.length > 0) return true;
return INVENTORY_BLOCK_REASONS.has(String(line.block_reason || '').trim());
}
/**
* ?????????????????????????????
* @param line - build_eligibility ???
*/
export function lineHasPendingRoutingSuggestion(
line: ShippingOrderReviewBuildEligibilityLineProjection,
): boolean {
return line.suggestion_pending === true;
}
/**
* ??????????????????? / ???? / ??????
* ?????suggestion_pending?unavailable_source_codes ??????????????
@@ -206,9 +177,8 @@ export function lineHasPendingRoutingSuggestion(
export function lineNeedsInventoryRoutingRecovery(
line: ShippingOrderReviewBuildEligibilityLineProjection,
): boolean {
if (lineHasPendingRoutingSuggestion(line)) return true;
if ((line.unavailable_source_codes || []).length > 0) return true;
return lineNeedsManualInventorySelection(line);
return line.can_build === false && Boolean(String(line.block_reason || '').trim());
}
/**
@@ -329,6 +299,7 @@ function synthesizeWorkItemFromReviewContext(params: {
export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void } = {}) {
const reviewRun = ref<ShippingOrderReviewRun | null>(null);
const reviewQueue = ref<ShippingOrderReviewQueue | null>(null);
const activeCase = ref<ShippingOrderReviewCase | null>(null);
const caseProjectionVersion = ref<number | null>(null);
const caseLoadingContext = ref<ShippingOrderReviewCaseLoadingContext | null>(null);
@@ -386,7 +357,16 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
const previewCaseNo = ref<string | null>(null);
const previewLoading = ref(false);
const previewLoadFailed = ref(false);
let previewInflight: Promise<boolean> | null = null;
const emailPreview = ref<ShippingOrderReviewEmailEvidencePreview | null>(null);
/** 接收解析工作面专用上下文;切换 Case 或重新加载时必须立即清空,禁止串附件/EML。 */
const intakeParseContext = ref<ShippingOrderReviewIntakeParseContext | null>(null);
const intakeParseLoading = ref(false);
const intakeParseLoadFailed = ref(false);
/** 接收解析上下文请求代次:同一 Case 的后发请求必须覆盖并作废前发请求。 */
let intakeParseRequestGeneration = 0;
/** PDF 预览请求代次:切换 Case 后旧 Blob/失败都不得写回当前附件。 */
let previewRequestGeneration = 0;
let previewInflight: { caseNo: string; promise: Promise<boolean> } | null = null;
/** Case 切换请求代次:快速切换时丢弃过期响应,禁止旧 Case 覆盖新 Case。 */
let caseLoadGeneration = 0;
/** 当前正在请求或已选定的 Case 编号(与 generation 双校验)。 */
@@ -398,34 +378,11 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
/** ?????????? Workflow ????? */
const showWorkflowProgress = ref(false);
const workflowProgressPolling = ref(false);
/** ??????? WorkflowItem ???????????????? */
const reparseProgressActive = ref(false);
const reparseProgressPolling = ref(false);
const reparseProgressRefreshFailed = ref(false);
const reparseProgressStage = ref<'submitted' | 'layout_parsing' | 'routing' | 'extracting' | 'validating' | 'draft_ready' | 'auto_confirming' | 'building_order' | 'inventory_matching' | 'generating_excel' | 'awaiting_manual_action' | 'completed' | 'failed' | 'interrupted'>('submitted');
/** ?????????????????/????????????????? */
const reparseLastStableStage = ref<'submitted' | 'layout_parsing' | 'routing' | 'extracting' | 'validating' | 'draft_ready' | 'auto_confirming' | 'building_order' | 'inventory_matching' | 'generating_excel' | 'awaiting_manual_action' | 'completed'>('submitted');
const reparseRunStatus = ref<string>('queued');
const reparseLastActivityAt = ref<string | null>(null);
/** ????????????????????????????????? */
const reparseLastRefreshedAt = ref<string | null>(null);
const reparseStalePolls = ref(0);
const reparsePendingReviewPolls = ref(0);
let contextConversationId = '';
let contextItemNo = '';
let progressPollTimer: ReturnType<typeof window.setInterval> | null = null;
let reparsePollTimer: ReturnType<typeof window.setInterval> | null = null;
let reparsePollTick: (() => Promise<void>) | null = null;
let reparseCaseRefreshTimer: ReturnType<typeof window.setInterval> | null = null;
const PROGRESS_POLL_MS = 2500;
/** ??????????????????reparse_kind ????????? */
const REPARSE_RUNNING_LIFECYCLES = new Set([
'layout_parsing', 'waiting_layout', 'routing', 'matching_profile',
'extracting', 'merging_supplement',
]);
/** ??????????? Run ?????????????????? Case? */
const REPARSE_REVIEW_READY_STATUSES = new Set([
'review_required', 'partially_completed',
]);
/**
* 应用后端返回的完整 Case 快照。
@@ -449,39 +406,26 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
workflowProgressPolling.value = false;
};
/** ?? PDF ?????????????????????? */
const stopReparseProgressPolling = () => {
if (reparsePollTimer != null) {
window.clearInterval(reparsePollTimer);
reparsePollTimer = null;
}
reparseProgressPolling.value = false;
reparsePollTick = null;
};
/**
* ? Extraction Run ?????????????? Case ????????
* @param runNo - reparse API ???? Run ???????? pending_review ??????
* 等待后端明确产出新复核 Case 后切换工作台,不将 Run 技术状态推断成另一条用户进度。
*
* AI 触发时机:用户发起“重新识别此 PDF”后调用。
* 核心逻辑:以会话级 Review Stream 队列中同一 document_id 的 source_run_no + case_no
* 触发 Case 加载;completed 也可能已生成可复核 Case,不能仅按 Run 技术终态停止。
* failed/cancelled 仅刷新正式投影并停止,失败原因由正式状态卡与 Gate 表达。
*
* Args:
* runNo: 重识别请求返回的后继 Run 编号。
*/
const startReparseProgressPolling = (runNo: string, restoreExisting = false) => {
stopReparseProgressPolling();
const startReparseCaseRefreshPolling = (runNo: string) => {
stopReparseCaseRefreshPolling();
const targetRunNo = String(runNo || '').trim();
const targetDocumentId = currentStreamDocumentId();
if (!targetRunNo) return;
reparseProgressActive.value = true;
reparseProgressPolling.value = true;
reparseProgressRefreshFailed.value = false;
if (!restoreExisting) {
reparseProgressStage.value = 'submitted';
reparseLastStableStage.value = 'submitted';
reparseRunStatus.value = 'queued';
reparseLastActivityAt.value = null;
reparseLastRefreshedAt.value = null;
reparseStalePolls.value = 0;
reparsePendingReviewPolls.value = 0;
}
const tick = async () => {
try {
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
const normalizedStatus = String(run.status || '').trim();
const synthesized = synthesizeWorkItemFromReviewContext({
reviewRun: reviewRun.value,
activeCase: activeCase.value,
@@ -490,112 +434,37 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
extractionRun: run,
});
if (synthesized) reviewProgressContext.value = synthesized;
reparseProgressRefreshFailed.value = false;
reparseStalePolls.value = 0;
reparseLastRefreshedAt.value = new Date().toISOString();
reparseRunStatus.value = String(run.status || '').trim() || 'queued';
reparseLastActivityAt.value = run.current_activity?.last_activity_at || run.last_activity_at || null;
const normalizedRunStatus = String(run.status || '').trim();
const runStage = String(run.current_activity?.user_visible_stage || run.user_visible_stage || '').trim();
const lifecycle = String(synthesized?.lifecycle_status || '').trim();
if (['review_required', 'partially_completed'].includes(normalizedRunStatus)) {
reparsePendingReviewPolls.value += 1;
} else {
reparsePendingReviewPolls.value = 0;
}
if (['queued', 'layout_parsing', 'waiting_layout'].includes(normalizedRunStatus)
|| ['queued', 'layout_parsing', 'waiting_layout'].includes(runStage)) {
reparseLastStableStage.value = 'layout_parsing';
} else if (['routing', 'matching_profile'].includes(normalizedRunStatus)
|| ['routing', 'matching_profile'].includes(runStage)) {
reparseLastStableStage.value = 'routing';
} else if (['extracting', 'merging_supplement'].includes(normalizedRunStatus)
|| ['extracting', 'merging_supplement'].includes(runStage)) {
reparseLastStableStage.value = 'extracting';
} else if (['review_required', 'partially_completed'].includes(normalizedRunStatus)) {
reparseLastStableStage.value = 'draft_ready';
} else if (['candidate_ready'].includes(normalizedRunStatus) || runStage === 'candidate_ready') {
reparseLastStableStage.value = 'validating';
} else if (['confirming', 'auto_confirming'].includes(normalizedRunStatus)
|| ['confirming', 'auto_confirming'].includes(runStage)) {
reparseLastStableStage.value = 'auto_confirming';
} else if (normalizedRunStatus === 'building_order' || runStage === 'building_order') {
reparseLastStableStage.value = 'building_order';
} else if (normalizedRunStatus === 'inventory_matching' || runStage === 'inventory_matching') {
reparseLastStableStage.value = 'inventory_matching';
} else if (normalizedRunStatus === 'generating_excel' || runStage === 'generating_excel') {
reparseLastStableStage.value = 'generating_excel';
} else if (['manual_upload_pending', 'upload_rpa_pending', 'upload_rpa_running'].includes(normalizedRunStatus)) {
reparseLastStableStage.value = 'awaiting_manual_action';
} else if (['completed', 'partially_completed'].includes(normalizedRunStatus)) {
reparseLastStableStage.value = 'completed';
}
reparseProgressStage.value = reparseLastStableStage.value;
if (['failed', 'cancelled'].includes(normalizedRunStatus) || lifecycle === 'reparse_failed') {
reparseProgressStage.value = 'failed';
stopReparseProgressPolling();
reparseProgressActive.value = false;
refreshStatusMessage();
return;
}
if (REPARSE_REVIEW_READY_STATUSES.has(normalizedRunStatus)) {
let currentCaseNo = '';
try {
const reviewRunDetail = await getWorkspaceShippingOrderReviewRun(targetRunNo);
currentCaseNo = String(
reviewRunDetail.items.find((item) => String(item.case_no || '').trim())?.case_no
|| reviewRunDetail.items[0]?.case_no
|| '',
).trim();
} catch {
/* Review Run ?????????? */
}
if (currentCaseNo) {
reparseProgressStage.value = 'draft_ready';
stopReparseProgressPolling();
await load(targetRunNo, currentCaseNo, {
if (['review_required', 'partially_completed', 'completed'].includes(normalizedStatus)) {
const target = await resolveCurrentStreamTarget(targetDocumentId, targetRunNo);
if (target) {
window.clearInterval(reparseCaseRefreshTimer!);
reparseCaseRefreshTimer = null;
await load(target.runNo, target.caseNo, {
conversationId: contextConversationId,
itemNo: contextItemNo || undefined,
restoreProgress: false,
});
reparseProgressActive.value = false;
refreshStatusMessage();
return;
}
}
if (['manual_upload_pending', 'upload_rpa_pending', 'upload_rpa_running', 'closed', 'cancelled'].includes(lifecycle)) {
stopReparseProgressPolling();
return;
}
reparseStalePolls.value = reparseStalePolls.value + 1;
if (reparseStalePolls.value >= 24) {
reparseProgressRefreshFailed.value = true;
}
} catch {
reparseProgressRefreshFailed.value = true;
reparseStalePolls.value = reparseStalePolls.value + 1;
if (reparseStalePolls.value >= 8) {
if (['failed', 'cancelled'].includes(normalizedStatus)) {
window.clearInterval(reparseCaseRefreshTimer!);
reparseCaseRefreshTimer = null;
refreshStatusMessage();
}
} catch {
// 轮询只承担恢复导航;临时网络失败由后续 tick 重试,禁止伪造业务进度。
}
};
reparsePollTick = tick;
void reparsePollTick();
reparsePollTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS);
void tick();
reparseCaseRefreshTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS);
};
/** ???????????????????????? tick ??? */
const refreshReparseProgress = async () => {
if (!reparsePollTick) return;
await reparsePollTick();
const stopReparseCaseRefreshPolling = () => {
if (reparseCaseRefreshTimer != null) {
window.clearInterval(reparseCaseRefreshTimer);
reparseCaseRefreshTimer = null;
}
};
/**
@@ -612,7 +481,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
if (!authoritativeOrderTaskNo.value && !targetRunNo) return;
showWorkflowProgress.value = true;
workflowProgressPolling.value = true;
const UNIFIED_TERMINAL = new Set(['completed', 'failed', 'cancelled', 'retryable', 'needs_review', 'waiting_human']);
// RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。
const UNIFIED_TERMINAL = new Set(['completed', 'cancelled']);
let lastUnifiedStatus = '';
const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']);
const tick = async () => {
@@ -628,7 +498,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
lastUnifiedStatus = unifiedStatus;
options.onWorkflowRefresh?.();
}
if (UNIFIED_TERMINAL.has(unifiedStatus) || unifiedStatus === 'waiting_review') {
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
stopWorkflowProgressPolling();
}
return;
@@ -660,7 +530,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
if (getCurrentInstance()) {
onBeforeUnmount(() => {
stopWorkflowProgressPolling();
stopReparseProgressPolling();
stopReparseCaseRefreshPolling();
stopShippingProcessing();
clearPreview();
});
@@ -677,10 +547,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
const isWorkItemClosed = computed(() => isReviewWorkItemClosed(reviewProgressContext.value));
/** ??/????????????????????????? */
const isReadOnly = computed(() => (
reparseProgressActive.value
|| isReviewReadOnly(activeCase.value, reviewProgressContext.value)
));
const isReadOnly = computed(() => isReviewReadOnly(activeCase.value, reviewProgressContext.value));
/**
* Draft ?????edit_draft ???????
@@ -732,10 +599,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
statusMessage.value = 'reparse_in_progress';
return;
}
if (reparseProgressActive.value) {
statusMessage.value = 'reparse_in_progress';
return;
}
if (isViewingHistoricalVersion.value || activeCase.value?.status === 'superseded') {
statusMessage.value = 'superseded';
return;
@@ -766,11 +629,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
&& !isBuildConfirmBlocked(buildEligibility.value)
));
/** ????????????????? */
const manualInventoryLines = computed(() =>
(buildEligibility.value?.line_projections || []).filter(lineNeedsManualInventorySelection),
);
/** ??????????????????????????? */
const routingRecoveryLines = computed(() =>
(buildEligibility.value?.line_projections || []).filter(lineNeedsInventoryRoutingRecovery),
@@ -816,14 +674,53 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
}
};
/** 当前工作台所对应的物理 PDF;版本切换必须固定此 ID,不能由 Run 中的首个 Case 推断。 */
const currentStreamDocumentId = (): number | null => {
const activeDocumentId = Number(activeCase.value?.document?.id || 0);
if (activeDocumentId > 0) return activeDocumentId;
const activeCaseNo = String(activeCase.value?.case_no || '').trim();
const summary = reviewRun.value?.items.find((item) => item.case_no === activeCaseNo);
const summaryDocumentId = Number(summary?.document_id || 0);
return summaryDocumentId > 0 ? summaryDocumentId : null;
};
/**
* 从会话级 Review Stream 队列解析当前 PDF 的权威版本。
*
* Queue 是跨 Run 的文件主线读模型;仅接受同 document_id 且有 source_run_no 的记录,
* 避免多 PDF 会话把另一个文件的首个 Case 当作当前版本。
*/
const resolveCurrentStreamTarget = async (
documentId: number | null,
anchorRunNo?: string | null,
): Promise<{ runNo: string; caseNo: string } | null> => {
const anchor = String(anchorRunNo || reviewRun.value?.run_no || activeCase.value?.run_no || '').trim();
if (!documentId || !anchor) return null;
const queue = await getWorkspaceShippingOrderReviewQueue(anchor);
reviewQueue.value = queue;
const item = queue.items.find((candidate) => (
Number(candidate.document_id || 0) === documentId
&& String(candidate.case_no || '').trim()
&& String(candidate.source_run_no || '').trim()
));
if (!item) return null;
return {
runNo: String(item.source_run_no).trim(),
caseNo: String(item.case_no).trim(),
};
};
/**
* ???? PDF ?? URL?????????
*/
const clearPreview = () => {
++previewRequestGeneration;
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
previewUrl.value = '';
previewCaseNo.value = null;
previewLoading.value = false;
previewLoadFailed.value = false;
previewInflight = null;
};
/**
@@ -834,32 +731,115 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
*/
const ensurePreviewLoaded = async (caseNo?: string | null): Promise<boolean> => {
const target = String(caseNo || activeCase.value?.case_no || '').trim();
if (!target) return false;
if (!target || activeCase.value?.case_no !== target) return false;
if (previewCaseNo.value === target && previewUrl.value) return true;
if (previewInflight) return previewInflight;
if (previewInflight?.caseNo === target) return previewInflight.promise;
const generation = caseLoadGeneration;
const requestGeneration = ++previewRequestGeneration;
previewLoading.value = true;
previewLoadFailed.value = false;
previewInflight = (async () => {
const promise = (async () => {
try {
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
previewUrl.value = '';
const blob = await getWorkspaceShippingOrderReviewPreview(target);
previewUrl.value = URL.createObjectURL(blob);
const url = URL.createObjectURL(blob);
if (
requestGeneration !== previewRequestGeneration
|| generation !== caseLoadGeneration
|| activeCase.value?.case_no !== target
) {
URL.revokeObjectURL(url);
return false;
}
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
previewUrl.value = url;
previewCaseNo.value = target;
previewLoadFailed.value = false;
return true;
} catch {
previewLoadFailed.value = true;
previewUrl.value = '';
previewCaseNo.value = null;
if (
requestGeneration === previewRequestGeneration
&& generation === caseLoadGeneration
&& activeCase.value?.case_no === target
) {
previewLoadFailed.value = true;
previewUrl.value = '';
previewCaseNo.value = null;
}
return false;
} finally {
previewLoading.value = false;
previewInflight = null;
if (
requestGeneration === previewRequestGeneration
&& generation === caseLoadGeneration
&& activeCase.value?.case_no === target
) {
previewLoading.value = false;
previewInflight = null;
}
}
})();
return previewInflight;
previewInflight = { caseNo: target, promise };
return promise;
};
/** 按当前证据 Document 读取邮件正文;PDF 证据仍使用受控 PDF Blob。 */
const ensureEmailEvidenceLoaded = async (caseNo: string, documentId: number, evidenceId?: string): Promise<boolean> => {
try {
emailPreview.value = await getWorkspaceShippingOrderReviewEmailEvidencePreview(caseNo, documentId, evidenceId);
return true;
} catch {
emailPreview.value = null;
return false;
}
};
/**
* 仅在用户打开接收解析工作面时按需读取当前 Case 的附件与邮件正文。
* Case/代次双校验避免迟到响应把旧附件或 EML 写回当前工作面;失败保持空上下文。
*/
const ensureIntakeParseContextLoaded = async (caseNo: string): Promise<boolean> => {
const target = String(caseNo || '').trim();
if (!target || activeCase.value?.case_no !== target) {
++intakeParseRequestGeneration;
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
return false;
}
const generation = caseLoadGeneration;
const requestGeneration = ++intakeParseRequestGeneration;
intakeParseContext.value = null;
intakeParseLoading.value = true;
intakeParseLoadFailed.value = false;
try {
const context = await getWorkspaceShippingOrderReviewIntakeParseContext(target);
if (
requestGeneration !== intakeParseRequestGeneration
|| generation !== caseLoadGeneration
|| activeCase.value?.case_no !== target
) return false;
intakeParseContext.value = context;
return true;
} catch {
if (
requestGeneration === intakeParseRequestGeneration
&& generation === caseLoadGeneration
&& activeCase.value?.case_no === target
) {
intakeParseContext.value = null;
intakeParseLoadFailed.value = true;
}
return false;
} finally {
if (
requestGeneration === intakeParseRequestGeneration
&& generation === caseLoadGeneration
&& activeCase.value?.case_no === target
) {
intakeParseLoading.value = false;
}
}
};
/** ?? Run ??????? URL ?? Case??????? PDF? */
@@ -868,6 +848,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
preferredCaseNo?: string,
options?: { conversationId?: string; itemNo?: string; restoreProgress?: boolean },
) => {
++caseLoadGeneration;
++intakeParseRequestGeneration;
loading.value = true;
loadFailed.value = false;
draftConflict.value = null;
@@ -883,16 +865,19 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
versions.value = [];
evidence.value = [];
llmSuggestions.value = [];
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
clearPreview();
try {
const run = await getWorkspaceShippingOrderReviewRun(runNo);
const [run, queue] = await Promise.all([
getWorkspaceShippingOrderReviewRun(runNo),
getWorkspaceShippingOrderReviewQueue(runNo),
]);
reviewRun.value = run;
// ? Run ???????????????? Case??????????????
if (run.superseded_by_run_no) {
await load(run.superseded_by_run_no, preferredCaseNo, options);
return;
}
const caseNo = preferredCaseNo || run.items[0]?.case_no;
reviewQueue.value = queue;
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
applyCaseSnapshot(caseSnapshot);
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
@@ -900,21 +885,12 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
clearPreview();
await refreshWorkItemContext(contextConversationId, contextItemNo);
// refreshWorkItemContext ????? ref???????? ref????? load ???????????
const restoredItem = (reviewProgressContext as { readonly value: ShippingReviewProgressContext | null }).value;
const restoredRunNo = String(restoredItem?.current_run_no || '').trim();
const restoredLifecycle = String(restoredItem?.lifecycle_status || '').trim();
const activeCaseStatus = String(caseSnapshot?.case?.status || '').trim();
const isReparseRunning = REPARSE_RUNNING_LIFECYCLES.has(restoredLifecycle)
|| activeCaseStatus === 'reparse_pending';
const isReparseFailed = ['reparse_failed', 'failed'].includes(restoredLifecycle);
if (options?.restoreProgress !== false && restoredRunNo && (isReparseRunning || isReparseFailed)) {
startReparseProgressPolling(restoredRunNo, true);
}
} catch {
loadFailed.value = true;
reviewRun.value = null;
activeCase.value = null;
reviewProgressContext.value = null;
reviewQueue.value = null;
versions.value = [];
statusMessage.value = null;
} finally {
@@ -928,6 +904,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
* 保留 reviewProgressContext(Run 级进度条按契约绑定整 Run,不随 PDF 跳变)。
*/
const resetCaseTransientState = () => {
++intakeParseRequestGeneration;
activeCase.value = null;
caseProjectionVersion.value = null;
caseLoadingContext.value = null;
@@ -940,6 +917,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
saveFailed.value = false;
loadFailed.value = false;
statusMessage.value = null;
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
clearPreview();
};
@@ -953,9 +933,15 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
const target = String(caseNo || '').trim();
if (!target) return;
const generation = ++caseLoadGeneration;
++intakeParseRequestGeneration;
requestedCaseNo.value = target;
caseSwitchLoading.value = true;
caseSwitchFailed.value = false;
// 切换请求一开始即撤销旧 Blob 并作废旧预览响应,禁止 A 的 PDF 留在 B 的工作面。
clearPreview();
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
try {
const [detail, result] = await Promise.all([
getWorkspaceShippingOrderReviewCase(target),
@@ -1108,21 +1094,21 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
};
/**
* ?????? Case ?????????????????????
* 门禁动作完成后静默同步当前 Case。
* 核心逻辑:这不是用户切换 PDF,故不能复用 selectCase;保留已加载预览、字段/证据焦点与 intake
* 上下文,仅在当前 Case 的快照和证据都返回后替换数据,再同步 Run 与 WorkflowItem 状态。
*/
const reloadLatestDraft = async () => {
if (!activeCase.value) return;
const caseNo = activeCase.value.case_no;
saving.value = true;
try {
if (draftConflict.value?.serverCase) {
activeCase.value = draftConflict.value.serverCase;
caseProjectionVersion.value = Date.now();
caseLoadingContext.value = null;
evidence.value = (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items;
} else {
await selectCase(caseNo);
}
const [detail, result] = await Promise.all([
getWorkspaceShippingOrderReviewCase(caseNo),
getWorkspaceShippingOrderReviewEvidence(caseNo),
]);
applyCaseSnapshot(detail);
evidence.value = result.items;
if (reviewRun.value && activeCase.value) {
const item = reviewRun.value.items.find((row) => row.case_no === caseNo);
if (item) {
@@ -1209,27 +1195,14 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
if (!activeCase.value) return;
validationInProgress.value = true;
try {
await save(() => validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version()));
await save(async () => (
await validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version())
).case);
} finally {
validationInProgress.value = false;
}
};
/**
* ????????????????? Case?
* @param lineKey - Draft ? line_key
* @param sourceCodes - ?????????????
* @param reason - ??????
*/
const setLineInventoryCandidates = (lineKey: string, sourceCodes: string[], reason: string) => {
if (!activeCase.value) return Promise.resolve();
return save(() => putWorkspaceShippingOrderReviewInventoryCandidates(activeCase.value!.case_no, lineKey, {
expected_draft_version: version(),
source_codes: sourceCodes,
reason,
}));
};
/**
* ?????????????????409 ????? markWriteFailure?
* @param lineKey - ???????? reroute
@@ -1244,44 +1217,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
}));
};
/**
* ???????????????
* @param lineKey - Draft ? line_key
* @param reason - ????
*/
const adoptInventoryRoutingSuggestion = (lineKey: string, reason?: string) => {
if (!activeCase.value) return Promise.resolve();
const trimmedReason = String(reason || '').trim();
return save(() => postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion(
activeCase.value!.case_no,
lineKey,
{
expected_draft_version: version(),
idempotency_key: crypto.randomUUID(),
...(trimmedReason ? { reason: trimmedReason } : {}),
},
));
};
/**
* ????????????????????
* @param lineKey - Draft ? line_key
* @param reason - ????
*/
const keepManualInventoryRouting = (lineKey: string, reason?: string) => {
if (!activeCase.value) return Promise.resolve();
const trimmedReason = String(reason || '').trim();
return save(() => postWorkspaceShippingOrderReviewInventoryRoutingKeepManual(
activeCase.value!.case_no,
lineKey,
{
expected_draft_version: version(),
idempotency_key: crypto.randomUUID(),
...(trimmedReason ? { reason: trimmedReason } : {}),
},
));
};
/** ????????????????? Task ??? Case??????? DTO? */
const confirm = async () => {
if (!activeCase.value) return null;
@@ -1367,7 +1302,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
await refreshWorkItemContext();
startReparseProgressPolling(response.run.run_no);
startReparseCaseRefreshPolling(response.run.run_no);
return response;
} catch (error) {
saveFailed.value = true;
@@ -1376,30 +1311,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
saving.value = false;
}
};
/** ???? PDF ????? Intake ?????????? Document ????? Run? */
const uploadReplacement = async (file: File) => {
if (!activeCase.value) return null;
const asset = await uploadFileAsset(file);
const intake = await createWorkspaceShippingOrderReviewReplacementIntake(activeCase.value.case_no, asset.asset_no);
for (let attempt = 0; attempt < 60; attempt += 1) {
const current = await getShippingNoticeIntake(intake.intake_no);
if (current.parse_status === 'parsed') return startReplacementRun(current.intake_no);
if (['parse_failed', 'cancelled', 'expired'].includes(current.parse_status)) {
throw new Error('Replacement PDF parsing failed');
}
await new Promise<void>((resolve) => window.setTimeout(resolve, 1000));
}
throw new Error('Replacement PDF parsing is still pending');
};
const startReplacementRun = async (intakeNo: string) => {
if (!activeCase.value) return null;
const response = await createWorkspaceShippingOrderReviewReplacementRun(activeCase.value.case_no, intakeNo);
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
await refreshWorkItemContext();
return response;
};
/**
* ?????????? LLM ?????????
*/
@@ -1495,47 +1406,12 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
return { runNo, caseNo };
};
/**
* ????????????????? Run ? Case?
* ??????? reviewRun.superseded_by_run_no ??? WorkItem ??????? Workflow API?
*/
/** 由 Workflow 当前 Case 打开文件级 Stream 当前版本;不再以批次 Run 后继关系跳转。 */
const openCurrentVersion = async (): Promise<{ runNo: string; caseNo: string } | null> => {
reviewProgressContext.value = synthesizeWorkItemFromReviewContext({
reviewRun: reviewRun.value,
activeCase: activeCase.value,
conversationId: contextConversationId,
itemNo: contextItemNo,
});
versions.value = [];
refreshStatusMessage();
const target = currentVersionTarget();
const activeRunNo = String(reviewRun.value?.run_no || '').trim();
const activeCaseNo = String(activeCase.value?.case_no || '').trim();
const targetIsCurrentView = Boolean(
target
&& target.runNo === activeRunNo
&& target.caseNo === activeCaseNo,
);
if (reviewRun.value?.superseded_by_run_no && (!target || targetIsCurrentView || activeCase.value?.status === 'superseded')) {
try {
const replacement = await getWorkspaceShippingOrderReviewRun(reviewRun.value.superseded_by_run_no);
const preferredCaseNo = String(reviewProgressContext.value?.current_case_no || '').trim();
const replacementCase = replacement.items.find((item) => String(item.case_no || '').trim() === preferredCaseNo)
|| replacement.items.find((item) => String(item.case_no || '').trim());
const replacementRunNo = String(replacement.run_no || '').trim();
const replacementCaseNo = String(replacementCase?.case_no || '').trim();
if (replacementRunNo && replacementCaseNo) {
await load(replacementRunNo, replacementCaseNo, {
conversationId: contextConversationId,
itemNo: contextItemNo || undefined,
});
return { runNo: replacementRunNo, caseNo: replacementCaseNo };
}
} catch {
/* ???????????????????????? */
}
}
const target = await resolveCurrentStreamTarget(currentStreamDocumentId());
if (!target) return null;
await load(target.runNo, target.caseNo, {
conversationId: contextConversationId,
@@ -1546,6 +1422,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
return {
reviewRun,
reviewQueue,
activeCase,
caseProjectionVersion,
caseLoadingContext,
@@ -1561,7 +1438,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
draftConflictDiffLines,
buildEligibility,
canConfirmBuild,
manualInventoryLines,
routingRecoveryLines,
isViewingHistoricalVersion,
isWorkItemClosed,
@@ -1577,22 +1453,19 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
focusedLineKey,
evidenceDrawerFocus,
previewUrl,
previewCaseNo,
previewLoading,
previewLoadFailed,
ensurePreviewLoaded,
ensureEmailEvidenceLoaded,
emailPreview,
intakeParseContext,
intakeParseLoading,
intakeParseLoadFailed,
ensureIntakeParseContextLoaded,
clearPreview,
showWorkflowProgress,
workflowProgressPolling,
reparseProgressActive,
reparseProgressPolling,
reparseProgressRefreshFailed,
reparseProgressStage,
reparseLastStableStage,
reparseRunStatus,
reparseLastActivityAt,
reparseLastRefreshedAt,
reparseStalePolls,
refreshReparseProgress,
loading,
loadFailed,
caseSwitchLoading,
@@ -1616,21 +1489,16 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
copyLine,
deleteLine,
validate,
setLineInventoryCandidates,
rerouteInventoryRouting,
adoptInventoryRoutingSuggestion,
keepManualInventoryRouting,
confirm,
startWorkflowProgressPolling,
stopWorkflowProgressPolling,
startReparseProgressPolling,
stopReparseProgressPolling,
startReparseCaseRefreshPolling,
stopReparseCaseRefreshPolling,
createManualDraft,
markNonOrder,
markQualityIssue,
reparseDocument,
uploadReplacement,
startReplacementRun,
focusSuggestionField,
setEvidenceDrawerFocus,
clearEvidenceDrawerFocus,
@@ -22,13 +22,38 @@ import {
buildTaskSemanticKey,
buildProcessingSemanticKey,
stabilizeTaskObjects,
flattenBusinessFileProjections,
businessFileKeys,
} from './conversationProcessingProjection';
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
import type {
ConversationProcessingProjection,
ShippingProcessingProjection,
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',
@@ -613,6 +638,94 @@ describe('conversationProcessingProjection', () => {
expect(projection?.summary.total_files).toBe(1);
});
it('aggregates mixed order tasks from one EML intake into one card', () => {
const base = {
sourceType: 'eml' as const,
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-eml',
submissionNo: 'SOS-EML',
intakeNo: 'INTAKE-EML-1',
progressVersion: 1,
currentGate: null,
childOrderTasks: [],
};
const items: ShippingProcessingProjection[] = [
{
...base, workItemType: 'order_task', workItemNo: 'OT-DONE', status: 'completed', stage: 'completed',
userStatus: 'completed', userStage: 'completed', lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
sourceSummary: { emailSubject: 'Shipment', filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
{
...base, workItemType: 'order_task', workItemNo: 'OT-RUN', status: 'processing', stage: 'inventory_matching',
userStatus: 'running', userStage: 'inventory_match', lastActivityAt: '2026-08-06T00:00:01Z', availableActions: [],
sourceSummary: { emailSubject: 'Shipment', filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
{
...base, workItemType: 'order_task', workItemNo: 'OT-FAIL', status: 'failed', stage: 'freight_uploading',
userStatus: 'failed', userStage: 'freight_upload', lastActivityAt: '2026-08-06T00:00:02Z', availableActions: [],
blockingReason: { code: 'upload_rpa_failed' },
sourceSummary: { emailSubject: 'Shipment', filename: 'c.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
];
const projection = projectConversationProcessingFromWorkItems(items);
expect(projection?.needs_action).toHaveLength(1);
expect(projection?.processing).toHaveLength(0);
expect(projection?.completed).toHaveLength(0);
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
intakeNo: 'INTAKE-EML-1', total: 3, completed: 1, processing: 1, needsAction: 1, failed: 1,
}));
expect(projection?.needs_action[0]?.file_count).toBe(3);
expect(projection?.needs_action[0]?.aggregateSummary?.reasonCodes).toContain('upload_rpa_failed');
});
it('does not reuse an empty EML task when a later poll returns aggregate children', () => {
const base = {
workItemType: 'order_task' as const, sourceType: 'eml' as const, rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null, conversationId: 'conv-stable', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
progressVersion: 1, currentGate: null, availableActions: [], status: 'processing' as const,
stage: 'document_parsing' as const, userStatus: 'running' as const, userStage: 'document_parsing' as const,
lastActivityAt: '2026-08-06T00:00:00Z',
sourceSummary: { emailSubject: 'mail', filename: 'stable.eml', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
};
const first = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [] }]);
const child = { ...base, workItemNo: 'OT-CHILD', sourceSummary: { ...base.sourceSummary, filename: 'attachment.pdf' } };
const second = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [child] }], first);
expect(second?.processing[0]?.aggregateChildren?.map((item) => item.sourceSummary.filename)).toEqual(['attachment.pdf']);
expect(second?.processing[0]).not.toBe(first?.processing[0]);
});
it('puts an EML with review-required children into needs_action even when parent says processing', () => {
const parent = {
workItemType: 'order_task' as const, workItemNo: 'INTAKE:SNI-STATUS', sourceType: 'eml' as const,
rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS',
status: 'processing' as const, stage: 'document_parsing' as const, userStatus: 'running' as const, userGroup: 'processing' as const,
userStage: 'document_parsing' as const, progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'mail.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
aggregateChildren: [
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'review_required', stage: 'review_required', userStatus: 'waiting_human', userStage: 'review_required', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'processing', stage: 'document_parsing', userStatus: 'running', userStage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
],
} as any;
const projection = projectConversationProcessingFromWorkItems([parent]);
expect(projection?.needs_action).toHaveLength(1);
expect(projection?.processing).toHaveLength(0);
});
it('does not aggregate direct PDFs with matching intake numbers', () => {
const common = {
workItemType: 'order_task' as const, rootOrderTaskNo: null, shippingNoticeNo: null,
conversationId: 'conv-pdf', submissionNo: 'SOS-PDF', intakeNo: 'INTAKE-SAME', progressVersion: 1,
currentGate: null, childOrderTasks: [], status: 'processing' as const, stage: 'document_parsing' as const,
userStatus: 'running' as const, userStage: 'document_parsing' as const, lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
};
const projection = projectConversationProcessingFromWorkItems([
{ ...common, workItemNo: 'OT-1', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
{ ...common, workItemNo: 'OT-2', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
]);
expect(projection?.processing).toHaveLength(2);
});
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
const workItems: ShippingProcessingProjection[] = [
{
@@ -693,11 +806,43 @@ describe('conversationProcessingProjection', () => {
const projection = resolveConversationProcessingFromUnified(workItems, embedded);
// 关键断言:兄弟 OT 仅出现在 work_items;embedded 缺 sibling 时不得覆盖任务列表。
expect(projection?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(projection?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
expect(projection?.processing).toEqual([]);
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
intakeNo: 'SNI-1', total: 2, completed: 0, processing: 1, needsAction: 1,
}));
expect(projection?.focused_task_no).toBe('OT-ROOT');
expect(projection?.recent_task_no).toBe('OT-SIBLING');
});
it('uses backend status_groups instead of rebuilding a file list from work_items', () => {
const workItems: ShippingProcessingProjection[] = [{
workItemType: 'order_task', workItemNo: 'OT-LIVE', sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-LIVE', shippingNoticeNo: null, conversationId: 'conv-live',
submissionNo: 'SOS-LIVE', intakeNo: 'SNI-LIVE', status: 'waiting_review',
stage: 'order_review', progressVersion: 9, lastActivityAt: '2026-08-16T00:00:00Z',
currentGate: null, availableActions: ['open_order_review'], childOrderTasks: [],
sourceSummary: { emailSubject: null, filename: 'live.pdf', documentCount: 1,
parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: 'PO-LIVE' },
}];
const backendProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
status_groups: {
failed: [], waiting_human: [{
user_task_no: 'OT-LIVE', group: 'needs_action', status_label: 'waiting_human',
file_count: 1, can_append: false,
}], processing: [], completed: [], cancelled: [], archived: [],
},
needs_action: [], processing: [{ user_task_no: 'OT-HISTORY', status_label: 'extracting' }],
completed: [], history: [], focused_task_no: null, recent_task_no: null,
};
const projection = resolveConversationProcessingFromUnified(workItems, backendProjection);
// 后端已排除的历史条目不允许被前端 work_items 重建回页面。
expect(projection?.needs_action.map((task) => task.user_task_no)).toEqual(['OT-LIVE']);
expect(projection?.processing).toEqual([]);
});
it('merges focus metadata from embedded onto work_items-derived projection', () => {
const derived = projectConversationProcessingFromWorkItems([{
workItemType: 'order_task',
@@ -800,6 +945,93 @@ 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: 后端撤销生命周期入口时必须改变签名', () => {
const shared = {
user_task_no: 'INTAKE:SNI-LIFECYCLE', group: 'needs_action' as const,
status_label: 'waiting_human', file_count: 1, can_append: false,
uiState: {
status: 'waiting_human', stage: 'waiting_review', blocking_reason: null,
primary_action: null, secondary_actions: [],
lifecycleEntries: [{ code: 'order_review' as const, state: 'current' as const, targetSurface: 'order_lifecycle_workbench' as const }],
},
};
const revoked = {
...shared,
uiState: { ...shared.uiState, lifecycleEntries: [] },
};
expect(buildTaskSemanticKey(shared)).not.toBe(buildTaskSemanticKey(revoked));
});
it('buildTaskSemanticKey: EML 子文件入口被撤销时必须替换聚合卡', () => {
const child = {
workItemNo: 'OT-LEAF-1',
intakeNo: 'SNI-LEAF',
status: 'waiting_human',
stage: 'order_review',
sourceSummary: { filename: 'leaf.pdf', documentId: 801 },
uiState: {
status: 'waiting_human', stage: 'order_review', blocking_reason: null,
primary_action: null, secondary_actions: [],
lifecycleEntries: [{
code: 'order_review' as const, state: 'current' as const,
targetSurface: 'order_lifecycle_workbench' as const,
}],
},
} as any;
const task = {
user_task_no: 'INTAKE:SNI-LEAF', group: 'needs_action' as const,
status_label: 'waiting_human', file_count: 1, can_append: false,
uiState: { status: 'waiting_human', stage: 'order_review', blocking_reason: null, primary_action: null, secondary_actions: [] },
aggregateChildren: [child],
} as any;
const revoked = {
...task,
aggregateChildren: [{
...child,
uiState: { ...child.uiState, lifecycleEntries: [] },
}],
};
expect(buildTaskSemanticKey(task)).not.toBe(buildTaskSemanticKey(revoked));
});
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,
@@ -972,6 +1204,210 @@ 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('normalizes backend lifecycle_entries in status groups without recreating entries', () => {
const backendProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null,
recent_task_no: null,
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-LIFECYCLE-SNAKE', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'field_completeness', lifecycle_stage: 'order_review',
lifecycle_entries: [{ code: 'intake_parse', state: 'available', target_surface: 'order_lifecycle_workbench' }, {
code: 'order_review', state: 'current', target_surface: 'order_lifecycle_workbench',
}],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const normalized = normalizeConversationProcessingProjection(backendProjection);
const task = normalized.status_groups!.waiting_human[0]!;
expect(task.uiState?.lifecycleStage).toBe('order_review');
expect(task.uiState?.lifecycleEntries).toEqual([
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
]);
});
it('normalizes embedded primary-action lifecycle navigation fields from backend snake_case', () => {
const embedded = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null, recent_task_no: null,
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-FULFILLMENT-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null,
primary_action: {
code: 'open_inventory_match_review', execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'fulfillment_prep',
}, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.primary_action!;
expect(action.executionMode).toBe('navigate');
expect(action.targetSurface).toBe('order_lifecycle_workbench');
expect(action.targetLifecycleStage).toBe('fulfillment_prep');
});
it('normalizes embedded secondary-action lifecycle navigation fields from backend snake_case', () => {
const embedded = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null, recent_task_no: null,
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-VIEW-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null, primary_action: null,
secondary_actions: [{
code: 'view_result', enabled: true, execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'fulfillment_prep',
}],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.secondary_actions[0]!;
// 次动作与主动作一样来自后端授权;缺失导航字段会使文件级查看结果静默失效。
expect(action.executionMode).toBe('navigate');
expect(action.targetSurface).toBe('order_lifecycle_workbench');
expect(action.targetLifecycleStage).toBe('fulfillment_prep');
});
it('fails closed for unsupported embedded primary-action navigation targets', () => {
const embedded = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null, recent_task_no: null,
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-INVALID-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null,
primary_action: {
code: 'open_inventory_match_review', execution_mode: 'unknown',
target_surface: 'unsupported_surface', target_lifecycle_stage: 'unsupported_stage',
}, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.primary_action!;
expect(action.executionMode).toBeUndefined();
expect(action.targetSurface).toBeNull();
expect(action.targetLifecycleStage).toBeNull();
});
it('keeps backend intake_parse primary-action target instead of dropping it', () => {
const normalized = normalizeShippingProcessingProjection({
work_item_no: 'OT-INTAKE-ACTION', source_type: 'direct_pdf', status: 'waiting_human',
stage: 'intake_parse', progress_version: 1, last_activity_at: '2026-08-16T00:00:00Z',
source_summary: {}, available_actions: [], child_order_tasks: [],
ui_state: {
status: 'waiting_human', stage: 'intake_parse', lifecycle_stage: 'intake_parse',
lifecycle_entries: [{ code: 'intake_parse', state: 'current', target_surface: 'order_lifecycle_workbench' }],
blocking_reason: null,
primary_action: {
code: 'open_intake_parse', parameters: {}, execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'intake_parse',
},
secondary_actions: [],
},
});
// 后端指定接收解析时,前端仅透传该目标,不得由现有三阶段白名单裁决或改写。
expect(normalized?.uiState?.primary_action?.targetLifecycleStage).toBe('intake_parse');
expect(normalized?.uiState?.lifecycleEntries).toEqual([
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
]);
});
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 },
@@ -1006,7 +1442,7 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
expect(result!.needs_action[0]!.title).toBe('b.pdf');
});
it('resolveConversationProcessingFromUnified: work_items 仅含 order_intake 时,仍走 embedded normalize 路径(过渡窗口不跳状态)', () => {
it('resolveConversationProcessingFromUnified: 仅含 EML order_intake 时,派生统一 processing 投影而非回退 embedded', () => {
const embedded: ConversationProcessingProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
focused_task_no: 'OT-LEG3',
@@ -1035,7 +1471,7 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
sourceType: 'eml',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
@@ -1061,13 +1497,16 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
];
const result = resolveConversationProcessingFromUnified(workItems, embedded);
expect(result).not.toBeNull();
// 过渡阶段:order_intake 不触发统一投影派生;embedded waiting_human 必须 normalize 成 waiting_review/needs_action
// EML 尚未创建 OT 时,也必须作为一张 EML 卡进入统一“系统处理中”区。
expect(result!.focused_task_no).toBe('OT-LEG3');
expect(result!.processing.length).toBe(0);
expect(result!.needs_action.length).toBe(1);
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
expect(result!.needs_action[0]!.title).toBe('c.pdf');
expect(result!.needs_action[0]!.group).toBe('needs_action');
expect(result!.needs_action).toHaveLength(0);
expect(result!.processing).toHaveLength(1);
expect(result!.processing[0]).toMatchObject({
user_task_no: 'SNI-1',
title: 'c.pdf',
group: 'processing',
status_label: 'processing',
});
});
it('resolveConversationProcessingFromUnified + IntakeOtStabilizer: 看到 order_task 后 2s 内暂缺 OT 保持 previousProjection(避免轮询抖动)', () => {
@@ -17,11 +17,52 @@ import type {
ConversationProcessingUserTask,
ShippingProcessingBlockingReason,
ShippingProcessingFacts,
ShippingProcessingLifecycleEntry,
ShippingProcessingPrimaryAction,
ShippingProcessingProjection,
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];
}
/**
* 标准化动作码列表:去空白、小写、去重、字典序排序。
@@ -50,6 +91,26 @@ export function buildTaskSemanticKey(
): string {
if (!task) return '';
const rawStatus = (task as ConversationProcessingUserTask & { userStatus?: string | null }).userStatus ?? task.status_label;
const aggregateChildren = (task.aggregateChildren || []).map((child) => ({
workItemNo: child.workItemNo,
intakeNo: child.intakeNo,
status: child.userStatus ?? child.status,
stage: child.userStage ?? child.stage,
uploadState: child.facts?.uploadState ?? null,
filename: child.sourceSummary?.filename ?? null,
reason: child.blockingReason?.code ?? child.sourceSummary?.failureReasonCode ?? null,
// EML 父卡会缓存其叶子对象。子文件的入口与按钮同样是后端裁决,
// 必须进入父卡语义签名;否则父卡引用被复用时会残留已撤销的入口。
primaryAction: child.uiState
? (child.uiState.primary_action?.code ?? null)
: (child.primaryAction?.code ?? null),
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
code: entry.code,
state: entry.state,
targetSurface: entry.targetSurface,
disabledReasonKey: entry.disabledReasonKey ?? null,
})) ?? [],
}));
return JSON.stringify({
taskNo: task.user_task_no,
group: task.group,
@@ -58,9 +119,20 @@ 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),
// 生命周期入口由后端独立裁决;入口被撤销/禁用时必须替换缓存对象,不能保留旧按钮。
lifecycleEntries: task.uiState?.lifecycleEntries?.map((entry) => ({
code: entry.code,
state: entry.state,
targetSurface: entry.targetSurface,
disabledReasonKey: entry.disabledReasonKey ?? null,
})) ?? [],
currentGate: (task as ConversationProcessingUserTask & {
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
blockingReason?: { code?: string } | null;
@@ -81,8 +153,13 @@ 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,
});
}
@@ -222,7 +299,6 @@ export function normalizeLifecycleStatus(
const HUMAN_ACTION_CODES = new Set([
'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate',
'open_order_review', 'open_order_processing', 'enter_manual_review',
'open_inventory_source_review', 'confirm_inventory_source',
'open_inventory_match_review', 'rematch', 'match_inventory',
'open_shortage_review', 'upload_inventory_file', 'open_manual_upload',
'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents',
@@ -791,7 +867,22 @@ export function groupConversationProcessingTasks(
export function mapShippingProcessingStatusToTaskGroup(
item: ShippingProcessingProjection,
): ConversationProcessingTaskGroup {
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
const userGroup = String(item.userGroup || '').trim().toLowerCase();
const status = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim());
const childStatuses = (item.aggregateChildren || []).map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
const childHasFailure = childStatuses.some((value) => value === 'failed');
const childNeedsHuman = childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready');
const childAllUploaded = childStatuses.length > 0
&& childStatuses.every((value, index) => value === 'completed' && item.aggregateChildren?.[index]?.facts?.uploadState === 'succeeded');
if (childHasFailure) return 'needs_action';
if (childNeedsHuman) return 'needs_action';
if (childAllUploaded) return 'completed';
// 子项真实状态优先于父级 userGroup,避免 review_required/failed 被旧 processing 覆盖。
if (status === 'failed' || status === 'waiting_review' || status === 'manual_upload_pending') return 'needs_action';
if (userGroup === 'failed' || userGroup === 'waiting_human') return 'needs_action';
if (userGroup === 'completed') return 'completed';
if (userGroup === 'cancelled' || userGroup === 'archived') return 'history';
if (userGroup === 'processing') return 'processing';
const gateAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase();
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
.map((value) => String(value || '').trim().toLowerCase())
@@ -838,8 +929,9 @@ export function mergeConversationProcessingFocusMetadata(
/**
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
* 核心逻辑:work_items 非空时始终由 order_task 工作项合成任务列表;禁止优先 embedded
* (兄弟 OT 仅出现在 work_items,embedded 可能缺 sibling)。
* 核心逻辑:新版 embedded.status_groups 是后端已完成“当前文件代表项 → EML 容器”
* 裁决的唯一列表读源,存在时绝不能再从 work_items 重建;否则旧 Run 会重新进入
* 文件清单。旧接口未返回 status_groups 时,才从 work_items 合成兼容任务列表。
* 语义稳定化:对比 previousProjection 的签名,复用未变的任务对象引用。
*
* @param workItems - unified.work_items
@@ -854,12 +946,22 @@ 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] conversation_processing.status_groups 与 four_stage_nodes / ui_state
// 同属后端一次裁决。即使顶层 work_items 非空,也不得前端二次聚合或用旧快照覆盖。
if (embedded && typeof embedded === 'object' && embedded.status_groups) {
return normalizeConversationProcessingProjection(embedded);
}
// [AUTHORITY] 新版接口已经由后端完成「状态 → EML → 业务文件」聚合。
// 会话卡与批次中心必须直接使用该结果;前端从 work_items 重建只保留给旧响应兼容。
// [TRANSITION] 只有统一投影里明确存在 order_task,才认为 OT 维度已经成形。
// 仅 order_intake 存在时视为过渡阶段:
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
const hasOrderTask = items.some((item) => item.workItemType === 'order_task');
const hasOrderTask = items.some((item) => (
item.workItemType === 'order_task'
|| (item.workItemType === 'order_intake' && item.sourceType === 'eml')
));
const convId = stabilizer?.conversationId;
if (hasOrderTask) {
stabilizer?.markSeen?.(convId);
@@ -891,85 +993,275 @@ 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 }>;
lifecycle_stage?: ConversationProcessingUserTask['uiState'] extends { lifecycleStage?: infer S } ? S : never;
lifecycle_entries?: Array<Record<string, unknown>>;
};
const normalizeAction = (
action: ShippingProcessingPrimaryAction | null | undefined,
): ShippingProcessingPrimaryAction | null => {
if (!action || typeof action !== 'object') return null;
const rawAction = action as ShippingProcessingPrimaryAction & {
i18n_key?: string | null;
execution_mode?: string | null;
target_surface?: string | null;
target_lifecycle_stage?: string | null;
};
return {
...rawAction,
i18nKey: rawAction.i18nKey ?? rawAction.i18n_key ?? null,
// embedded conversation_processing 与 work_items 同为后端 snake_case DTO;
// 跳转目标必须在 API 边界完整规范化,否则已授权的主按钮会点击无响应。
executionMode: (
rawAction.executionMode === 'navigate' || rawAction.executionMode === 'execute'
? rawAction.executionMode
: (rawAction.execution_mode === 'navigate' || rawAction.execution_mode === 'execute'
? rawAction.execution_mode
: undefined)
),
targetSurface: (
rawAction.targetSurface === 'order_lifecycle_workbench'
? rawAction.targetSurface
: (rawAction.target_surface === 'order_lifecycle_workbench'
? rawAction.target_surface
: null)
),
targetLifecycleStage: (
['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(
String(rawAction.targetLifecycleStage),
)
? rawAction.targetLifecycleStage
: (['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(
String(rawAction.target_lifecycle_stage),
)
? rawAction.target_lifecycle_stage
: null)
) as ShippingProcessingPrimaryAction['targetLifecycleStage'],
};
};
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),
// 次动作与主动作同属后端 ui_state 授权契约。若仅透传原始 snake_case,
// 文件行点击会看不到导航目标并错误落入旧兼容分支。
secondary_actions: (state.secondary_actions ?? state.secondaryActions ?? [])
.map((action) => {
const normalized = normalizeAction(action);
return normalized && 'code' in action && 'enabled' in action
? { ...normalized, code: String(action.code), enabled: action.enabled !== false }
: null;
})
.filter((action): action is ShippingProcessingPrimaryAction & { code: string; enabled: boolean } => Boolean(action)),
lifecycleStage: state.lifecycleStage ?? state.lifecycle_stage,
lifecycleEntries: Array.isArray(state.lifecycleEntries)
? state.lifecycleEntries.filter((entry) => Boolean(entry?.code && entry?.state && entry?.targetSurface))
: (Array.isArray(state.lifecycle_entries)
? state.lifecycle_entries.map((entry) => {
const rawEntry = entry as { code?: unknown; state?: unknown; target_surface?: unknown; targetSurface?: unknown };
return {
code: String(rawEntry.code || '') as ShippingProcessingLifecycleEntry['code'],
state: String(rawEntry.state || '') as ShippingProcessingLifecycleEntry['state'],
targetSurface: String(rawEntry.targetSurface ?? rawEntry.target_surface ?? '') as ShippingProcessingLifecycleEntry['targetSurface'],
};
}).filter((entry) => Boolean(entry.code && entry.state && entry.targetSurface))
: []),
};
};
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 || [],
unclassified_summary: projection.unclassified_summary || { count: 0 },
ui_state: projection.ui_state || undefined,
output_artifacts: projection.output_artifacts || [],
};
}
/**
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
* 从统一 work_items 合成 ConversationProcessingProjection(order_task 与 EML order_intake)。
*
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组;
* 核心逻辑:order_task 与 EML order_intake 均进入状态区;非 EML intake 不入组;
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
*
* @param workItems - 统一投影 work_items
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
* @returns 兼容投影;无 order_task 时返回 null
* @returns 兼容投影;无可展示任务时返回 null
*/
export function projectConversationProcessingFromWorkItems(
workItems: ShippingProcessingProjection[] | null | undefined,
previousProjection?: ConversationProcessingProjection | null,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
const orderTasks = items.filter((row) => row.workItemType === 'order_task');
const orderTasks = items.filter((row) => (
row.workItemType === 'order_task'
|| (row.workItemType === 'order_intake' && row.sourceType === 'eml')
));
if (!orderTasks.length) return null;
const rawTasks: ConversationProcessingUserTask[] = [];
const rawTaskEntries: Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }> = [];
for (const item of orderTasks) {
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
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;
@@ -1009,25 +1301,124 @@ 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,
primary_action: gateNextAction || normalizedActions[0] || null,
userStatus: item.userStatus ?? null,
userStage: item.userStage ?? null,
blockingReason: userBlocking,
primaryAction: userPrimaryAction,
facts: userFacts,
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
userGroup: item.userGroup ?? null,
userCurrentGateCode: item.userCurrentGateCode ?? null,
legacyStatus: item.legacyStatus ?? null,
legacyStage: item.legacyStage ?? null,
aggregateSummary: item.aggregateSummary ?? null,
aggregateChildren: item.aggregateChildren ?? [],
};
rawTasks.push(task);
rawTaskEntries.push({ task, item });
}
const rawTasks: ConversationProcessingUserTask[] = [];
const emlGroups = new Map<string, Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }>>();
for (const entry of rawTaskEntries) {
if (entry.item.sourceType !== 'eml' || !entry.item.intakeNo) {
rawTasks.push(entry.task);
continue;
}
const key = String(entry.item.intakeNo).trim();
const group = emlGroups.get(key) || [];
group.push(entry);
emlGroups.set(key, group);
}
for (const [intakeNo, entries] of emlGroups) {
if (entries.length === 1) {
rawTasks.push({
...entries[0]!.task,
aggregateChildren: entries[0]!.task.aggregateChildren?.length
? entries[0]!.task.aggregateChildren
: entries[0]!.item.aggregateChildren || [],
});
continue;
}
const completed = entries.filter(({ item }) => String(item.userStatus ?? item.status).toLowerCase() === 'completed').length;
const failed = entries.filter(({ item }) => ['failed', 'retryable'].includes(String(item.userStatus ?? item.status).toLowerCase())).length;
const needsAction = entries.filter(({ task }) => task.group === 'needs_action').length;
const processing = entries.filter(({ task }) => task.group === 'processing').length;
const stages = [...new Set(entries.flatMap(({ item }) => [item.userStage, item.stage].filter(Boolean).map(String)))];
const reasonCodes = [...new Set(entries.flatMap(({ item }) => [
item.blockingReason?.code,
item.sourceSummary?.failureReasonCode,
].filter(Boolean).map(String)))];
const entryGroups = entries.map(({ task, item }) => {
const children = item.aggregateChildren || [];
const childStatuses = children.map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
if (childStatuses.some((value) => value === 'failed')) return 'failed';
if (childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready')) return 'waiting_human';
if (childStatuses.length > 0 && childStatuses.every((value, index) => value === 'completed' && children[index]?.facts?.uploadState === 'succeeded')) return 'completed';
const explicit = String(item.userGroup || '').trim().toLowerCase();
if (explicit) return explicit;
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
if (status === 'failed' || status === 'retryable') return 'failed';
if (task.group === 'needs_action') return 'waiting_human';
if (task.group === 'completed' && status === 'completed') return 'completed';
if (task.group === 'history') return status === 'cancelled' ? 'cancelled' : 'archived';
return 'processing';
});
const aggregateUserGroup = entryGroups.includes('failed')
? 'failed'
: entryGroups.includes('waiting_human')
? 'waiting_human'
: entryGroups.includes('processing')
? 'processing'
: entryGroups.includes('completed') && entryGroups.every((value) => value === 'completed')
? 'completed'
: entryGroups.includes('cancelled')
? 'cancelled'
: entryGroups.includes('archived')
? 'archived'
: 'processing';
const group = aggregateUserGroup === 'failed' || aggregateUserGroup === 'waiting_human'
? 'needs_action'
: aggregateUserGroup === 'completed'
? 'completed'
: aggregateUserGroup === 'cancelled' || aggregateUserGroup === 'archived'
? 'history'
: 'processing';
const representative = entries[0]!.task;
const 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}`,
display_kind: fileCount > 1 ? 'multi_document_task' : representative.display_kind,
document_names: documentNames,
file_count: fileCount,
group,
available_actions: [...new Set(entries.flatMap(({ task }) => task.available_actions || []))].sort(),
aggregateSummary: {
intakeNo,
total: entries.length,
completed,
processing,
needsAction,
failed,
stages,
reasonCodes,
},
aggregateChildren,
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
});
}
if (!rawTasks.length) return null;
@@ -1045,14 +1436,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
@@ -1082,6 +1470,15 @@ export function projectConversationProcessingFromWorkItems(
stabilizedAll.filter((t) => t.group === 'history'),
);
const status_groups = {
failed: stabilizedAll.filter((task) => task.userGroup === 'failed'),
waiting_human: stabilizedAll.filter((task) => task.userGroup === 'waiting_human'),
processing: stabilizedAll.filter((task) => task.userGroup === 'processing'),
completed: stabilizedAll.filter((task) => task.userGroup === 'completed'),
cancelled: stabilizedAll.filter((task) => task.userGroup === 'cancelled'),
archived: stabilizedAll.filter((task) => task.userGroup === 'archived'),
};
return {
summary: {
total_tasks: active.length,
@@ -1097,5 +1494,6 @@ export function projectConversationProcessingFromWorkItems(
processing,
completed,
history,
status_groups,
};
}
@@ -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).toMatchObject({
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', () => {
@@ -6,6 +6,7 @@
*/
import type {
ConversationProcessingUiState,
OrderIntakeSourceType,
ProcessGateSummary,
ShippingInventoryPerSourceAttempt,
@@ -20,8 +21,12 @@ import type {
ShippingProcessingStageNodeStatus,
ShippingProcessingStatus,
ShippingProcessingWorkItemType,
ShippingProcessGateUserSummary,
} from '../types/shipping.api.types';
/** 后端可裁决并透传到订单生命周期工作台的阶段;前端不根据本地状态补造入口。 */
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
/**
* 读取原始对象上的字符串字段(兼容 snake / camel)。
*/
@@ -136,9 +141,40 @@ function normalizePrimaryAction(raw: unknown): ShippingProcessingPrimaryAction |
typeof item.parameters === 'object' && item.parameters != null
? (item.parameters as Record<string, unknown>)
: {},
executionMode: item.execution_mode === 'navigate' || item.executionMode === 'navigate'
? 'navigate'
: item.execution_mode === 'execute' || item.executionMode === 'execute'
? 'execute'
: undefined,
targetSurface: item.target_surface === 'order_lifecycle_workbench' || item.targetSurface === 'order_lifecycle_workbench'
? 'order_lifecycle_workbench'
: null,
targetLifecycleStage: lifecycleStages.includes(
String(item.target_lifecycle_stage ?? item.targetLifecycleStage ?? '') as typeof lifecycleStages[number],
)
? String(item.target_lifecycle_stage ?? item.targetLifecycleStage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
: null,
};
}
/** 规范后端生命周期入口,前端不得由候选数或当前阶段补造入口。 */
function normalizeLifecycleEntries(raw: unknown): NonNullable<ConversationProcessingUiState['lifecycleEntries']> {
if (!Array.isArray(raw)) return [];
return raw
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
.map((item) => ({
code: String(item.code ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['code'],
state: String(item.state ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['state'],
targetSurface: String(item.target_surface ?? item.targetSurface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
disabledReasonKey: item.disabled_reason_key != null
? String(item.disabled_reason_key)
: item.disabledReasonKey != null ? String(item.disabledReasonKey) : null,
}))
.filter((item) => lifecycleStages.includes(item.code as typeof lifecycleStages[number])
&& ['available', 'current', 'unavailable'].includes(item.state)
&& item.targetSurface === 'order_lifecycle_workbench');
}
/**
* [T9 用户态 Projection] 规范 facts(后端 snake_case 子状态字典;camelCase key)。
*/
@@ -230,9 +266,32 @@ function normalizeFacts(raw: unknown): ShippingProcessingFacts | undefined {
return out;
}
function normalizeAggregateSummary(
raw: unknown,
): ShippingProcessingProjection['aggregateSummary'] {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const array = (value: unknown): string[] => Array.isArray(value)
? value.map((entry) => String(entry || '').trim()).filter(Boolean)
: [];
const count = (key: string): number => Number(item[key] || 0) || 0;
const intakeNo = String(item.intake_no ?? item.intakeNo ?? '').trim();
if (!intakeNo) return null;
return {
intakeNo,
total: count('total'),
completed: count('completed'),
processing: count('processing'),
needsAction: count('needs_action') || count('needsAction'),
failed: count('failed'),
stages: array(item.stages),
reasonCodes: array(item.reason_codes ?? item.reasonCodes),
};
}
/**
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
* 注意:failed_sources 会进一步透传到 exhausted_sources 分开(二者互斥;仅 max_attempts 耗尽的源进 exhausted)。
* 注意:只投影当前准备结果;失败后由具体 Gate 动作决定下一步。
*/
function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparationSummary | null {
if (!raw || typeof raw !== 'object') return null;
@@ -249,7 +308,6 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
const preparedSources = toStrArr(item.prepared_sources ?? item.preparedSources);
const pendingSources = toStrArr(item.pending_sources ?? item.pendingSources);
const failedSources = toStrArr(item.failed_sources ?? item.failedSources);
const exhaustedSources = toStrArr(item.exhausted_sources ?? item.exhaustedSources);
const activeAttemptCount = Number(item.active_attempt_count ?? item.activeAttemptCount ?? 0) || 0;
const gateAttemptActive = Boolean(item.gate_attempt_active ?? item.gateAttemptActive ?? false);
const latestRaw = (item.latest_attempts ?? item.latestAttempts) as Record<string, unknown> | undefined;
@@ -289,7 +347,6 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
preparedSources,
pendingSources,
failedSources,
exhaustedSources,
activeAttemptCount,
gateAttemptActive,
latestAttempts: Object.keys(latestAttempts).length ? latestAttempts : undefined,
@@ -324,6 +381,12 @@ export function normalizeShippingProcessingProjection(
const stageNodes = Array.isArray(stageNodesRaw)
? stageNodesRaw.map(normalizeStageNode).filter((row): row is ShippingProcessingStageNode => Boolean(row))
: undefined;
const aggregateChildrenRaw = item.aggregate_children ?? item.aggregateChildren;
const aggregateChildren = Array.isArray(aggregateChildrenRaw)
? aggregateChildrenRaw
.map(normalizeShippingProcessingProjection)
.filter((entry): entry is ShippingProcessingProjection => Boolean(entry))
: undefined;
return {
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
@@ -343,6 +406,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'),
@@ -358,16 +422,18 @@ export function normalizeShippingProcessingProjection(
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
},
childOrderTasks: children,
// [T9 用户态 Projection 7 字段] 优先读后端 user_* / blocking_reason / retryable / primary_action / facts;
// [T9 用户态 Projection 6 字段] 优先读后端 user_* / blocking_reason / primary_action / facts;
// 缺省为 null(旧后端不会下发,旧前端不读取,完全兼容)。
userStatus: readNullableString(item, 'user_status', 'userStatus') as ShippingProcessingProjection['userStatus'],
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
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),
aggregateChildren: aggregateChildren?.length ? aggregateChildren : undefined,
legacyStatus: readNullableString(item, 'legacy_status', 'legacyStatus'),
legacyStage: readNullableString(item, 'legacy_stage', 'legacyStage'),
hasFormalOt:
@@ -378,6 +444,40 @@ 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) => {
const normalized = normalizePrimaryAction(item);
return normalized ? { ...normalized, enabled: item.enabled !== false } : null;
})
.filter((item): item is NonNullable<typeof item> => item !== null)
: [];
return {
status: (readString(state, 'status', 'status') || 'running') as NonNullable<ShippingProcessingProjection['userStatus']>,
stage: readString(state, 'stage', 'stage'),
lifecycleStage: readString(state, 'lifecycle_stage', 'lifecycleStage') as ConversationProcessingUiState['lifecycleStage'],
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries ?? state.lifecycleEntries),
blocking_reason: normalizeBlockingReason(state.blocking_reason ?? state.blockingReason),
primary_action: normalizePrimaryAction(state.primary_action ?? state.primaryAction),
secondary_actions: secondaryActions,
};
}
/**
* 将会话级统一投影响应中的 work_items 规范为数组。
*/
@@ -1,14 +1,43 @@
/**
* features/chat/shipping/shippingDownload.ts
* 用途:工作台发货 Excel 浏览器端下载(触发 a[download])。
* 依赖:shipping.api.workspaceShippingExportUrl、shared/utils/auth。
* 逻辑:useChatShippingSendHandler 在用户请求下载 Excel 时调用。
* 用途:工作台发货 Excel 与任务已关联库存快照的浏览器端受控下载(触发 a[download])。
* 依赖:shipping.api 的任务下载 URL、shared/utils/auth。
* 逻辑:聊天入口下载通知 Excel;通知准备工作面仅在后端声明库存文件可用时调用库存下载。
*/
import { workspaceShippingExportUrl } from '@/features/chat/api/shipping.api';
import {
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
workspaceShippingExportUrl,
workspaceShippingInventoryFileUrl,
workspaceShippingLineInventoryFileUrl,
} from '@/features/chat/api/shipping.api';
import { getAuthHeaders } from '@/shared/utils/auth';
export async function downloadWorkspaceShippingExcelFile(taskId: string): Promise<void> {
const url = workspaceShippingExportUrl(taskId);
await downloadWorkspaceShippingFile(workspaceShippingExportUrl(taskId), `${taskId}.xlsx`);
}
/**
* 下载当前任务活动关联的库存快照。
* 核心逻辑:浏览器只发起受控 URL;后端复核任务归属、active link 与物理文件,不按库存源猜测文件。
* @param taskId - 正式发货任务号,必须来自当前详情快照。
* @returns 下载完成后解析并触发浏览器保存。
*/
export async function downloadWorkspaceShippingInventoryFile(taskId: string): Promise<void> {
await downloadWorkspaceShippingFile(workspaceShippingInventoryFileUrl(taskId), `${taskId}-inventory.xlsx`);
}
/** 下载某订单行实际匹配的库存快照;后端复核该文件号是否为当前行事实。 */
export async function downloadWorkspaceShippingLineInventoryFile(
taskId: string,
inventoryFileNo: string,
): Promise<void> {
await downloadWorkspaceShippingFile(
workspaceShippingLineInventoryFileUrl(taskId, inventoryFileNo),
`${inventoryFileNo}.xlsx`,
);
}
async function downloadWorkspaceShippingFile(url: string, fallbackName: string): Promise<void> {
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
@@ -19,7 +48,7 @@ export async function downloadWorkspaceShippingExcelFile(taskId: string): Promis
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = objectUrl;
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || `${taskId}.xlsx`;
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || fallbackName;
try {
a.download = decodeURIComponent(rawName);
} catch {
@@ -30,3 +59,9 @@ export async function downloadWorkspaceShippingExcelFile(taskId: string): Promis
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
}
/** 批次 ZIP 下载只转发后端归档响应;选择和授权均不在前端重算。 */
export const downloadWorkspaceShippingExportArchive = (payload: {
batch_no?: string;
task_nos?: string[];
}) => requestShippingExportArchive(payload);
@@ -4,7 +4,6 @@
* 依赖:shippingMenu.resolveShippingNumericChoice、types/shipping.types。
* 逻辑:useChatShippingSendHandler 调用;覆盖手工上传、库存上传、Excel 生成/下载与切票。
*/
import { resolveShippingNumericChoice } from './shippingMenu';
import type { ShippingMenuAction } from '../types/shipping.types';
export interface ShippingTaskSwitchIntent {
@@ -27,20 +26,6 @@ export function isShippingManualUploadIntent(text: string): boolean {
].some((pattern) => pattern.test(normalized));
}
export function isShippingInventoryUploadIntent(text: string, assistantContext: string): boolean {
const normalized = text.trim();
if (!normalized) return false;
const choice = resolveShippingNumericChoice(normalized, assistantContext);
if (choice === 'upload') return true;
return [
/^上传库存$/,
/上传库存文件/,
/手工上传/,
/选择库存/,
/upload.*inventory/i,
].some((pattern) => pattern.test(normalized));
}
export function isShippingGenerateExcelIntent(text: string): boolean {
const normalized = text.trim();
if (!normalized) return false;
@@ -29,7 +29,6 @@ export function classifyShippingMenuLine(desc: string): ShippingMenuAction | nul
const normalized = String(desc || '').trim();
if (!normalized) return null;
if (/已确认/.test(normalized)) return null;
if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload';
if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa';
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
if (/驳回|取消|reject/i.test(desc)) return 'reject';
@@ -5,7 +5,9 @@
*/
import { describe, expect, it } from 'vitest';
import {
resolveShippingProcessingReasonLabel,
resolveShippingProcessingMessage,
resolveShippingProcessingStageLabel,
resolveShippingProcessingStatusLabel,
shippingProcessingStatusKey,
} from './shippingProcessingLabels';
@@ -17,6 +19,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';
@@ -30,6 +38,33 @@ describe('shippingProcessingLabels', () => {
expect(resolveShippingProcessingStatusLabel('pending_review', te, t)).toBe('待复核');
});
it('uses the safe unknown label instead of exposing an unrecognized status code', () => {
const te = (key: string) => key === 'chat.shippingProcessing.taskStatus.unknown';
const t = (key: string) => key.endsWith('.unknown') ? '状态待确认' : key;
expect(resolveShippingProcessingStatusLabel('internal_processing_state', te, t)).toBe('状态待确认');
});
it('uses the reason i18n key regardless of snake or camel case', () => {
const te = (key: string) => key === 'chat.shippingProcessing.reasonCode.generic_extraction_disabled';
const t = () => '当前文件不满足自动解析条件,需要人工复核';
expect(resolveShippingProcessingReasonLabel({
code: 'generic_extraction_disabled',
i18n_key: 'chat.shippingProcessing.reasonCode.generic_extraction_disabled',
}, te, t)).toBe('当前文件不满足自动解析条件,需要人工复核');
});
it('uses a safe reason label instead of exposing an unknown internal reason code', () => {
const te = (key: string) => key === 'chat.shippingProcessing.reasonCode.unknown';
const t = (key: string) => key.endsWith('.unknown') ? '当前步骤需要人工处理' : key;
expect(resolveShippingProcessingReasonLabel({ code: 'internal_gate_reason' }, te, t)).toBe('当前步骤需要人工处理');
});
it('uses a safe stage label instead of exposing an unknown internal stage code', () => {
const te = (key: string) => key === 'chat.shippingProcessing.stageLabel.waiting_system_start';
const t = (key: string) => key.endsWith('waiting_system_start') ? '等待系统启动' : key;
expect(resolveShippingProcessingStageLabel('internal_gate_stage', te, t)).toBe('等待系统启动');
});
it('resolves group messages from shippingProcessing', () => {
const te = (key: string) => key === 'chat.shippingProcessing.groupNeedsAction';
const t = (key: string, params?: Record<string, unknown>) => (
@@ -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',
@@ -41,7 +42,7 @@ export function shippingProcessingStatusKey(status: string): string {
* @param code - 后端 status / status_label
* @param te - i18n te
* @param t - i18n t
* @returns 本地化文案;皆无则回退原码
* @returns 本地化文案;未知状态统一显示“状态待确认”,禁止暴露内部码
*/
export function resolveShippingProcessingStatusLabel(
code: string,
@@ -54,7 +55,28 @@ export function resolveShippingProcessingStatusLabel(
if (te(processingKey)) return t(processingKey);
const taskStatusKey = `chat.shippingProcessing.taskStatus.${raw}`;
if (te(taskStatusKey)) return t(taskStatusKey);
return raw;
const unknownKey = 'chat.shippingProcessing.taskStatus.unknown';
return te(unknownKey) ? t(unknownKey) : '状态待确认';
}
/**
* 解析后端阻塞原因的用户文案。
* 核心逻辑:先消费后端 i18n_key(兼容 snake/camel case),再使用原因码专用键;
* 未知原因只显示安全兜底,内部原因码仍保留在响应中供审计使用。
*/
export function resolveShippingProcessingReasonLabel(
reason: { code?: string | null; i18nKey?: string | null; i18n_key?: string | null } | null | undefined,
te: (key: string) => boolean,
t: (key: string) => string,
): string {
if (!reason) return '';
const i18nKey = String(reason.i18nKey || reason.i18n_key || '').trim();
if (i18nKey && te(i18nKey)) return t(i18nKey);
const code = String(reason.code || '').trim();
const reasonCodeKey = code ? `chat.shippingProcessing.reasonCode.${code}` : '';
if (reasonCodeKey && te(reasonCodeKey)) return t(reasonCodeKey);
const unknownKey = 'chat.shippingProcessing.reasonCode.unknown';
return te(unknownKey) ? t(unknownKey) : '当前步骤需要人工处理';
}
/**
@@ -123,7 +145,7 @@ export function resolveShippingProcessingStageLabel(
// 禁止把码当文案:无键时回退通用等待文案,而非裸 code。
return te('chat.shippingProcessing.stageLabel.waiting_system_start')
? t('chat.shippingProcessing.stageLabel.waiting_system_start')
: code;
: '等待系统启动';
}
/**
@@ -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) {
@@ -1,24 +1,21 @@
/**
* features/chat/shipping/shippingTurnActions.spec.ts
* 用途:验证决策/冻结等 Chat Turn 映射(不含已下线的 create_batch)。
* 用途:验证聊天仅构造仍允许的非履约 Chat Turn。
*/
import { describe, expect, it } from 'vitest';
import { resolveShippingChatTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('maps freeze_order only with the version shown to the user', () => {
// 关键断言:缺版本不得构造 freeze Turn,避免乐观锁盲写。
it('does not map legacy fulfillment writes to Chat Turns', () => {
// 关键断言:冻结、库存源、匹配、Excel 与上传写入必须由正式 OT Gate 裁决。
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001')).toBeNull();
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001', { expectedOrderDataVersion: 7 })).toEqual({
actionType: 'shipping.freeze_order',
payload: { task_no: 'SN-FREEZE-001', expected_order_data_version: 7 },
});
expect(resolveShippingChatTurn('confirm_inventory_source', 'sn-source-001', { sourceCode: 'WH-A' })).toBeNull();
expect(resolveShippingChatTurn('match_inventory', 'sn-match-001')).toBeNull();
expect(resolveShippingChatTurn('generate_excel', 'sn-excel-001')).toBeNull();
expect(resolveShippingChatTurn('retry_upload', 'sn-upload-001')).toBeNull();
});
it('maps confirm decision to submit_decision', () => {
expect(resolveShippingChatTurn('confirm', 'sn-1')).toEqual({
actionType: 'shipping.submit_decision',
payload: { task_no: 'SN-1', decision: 'confirm' },
});
it('does not map a legacy confirm decision to a Chat Turn', () => {
expect(resolveShippingChatTurn('confirm', 'sn-1')).toBeNull();
});
});
@@ -1,11 +1,9 @@
/**
* features/chat/shipping/shippingTurnActions.ts
* 用途:将发货通知菜单/决策 action.id 映射为 Chat Turn action_type + payload。
* 依赖:constants/shipping。
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息;
* co8 后已移除 create_batch / switch_batch_focus Turn 构造器,上传改走 Intake + order extraction。
* 用途:仅构造仍允许的发货通知 Chat Turn。
* 依赖:无。
* 逻辑:履约写操作已统一迁入正式 OT Gate,本模块只保留非履约的聊天辅助 Turn。
*/
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
export interface ShippingChatTurnSpec {
actionType: string;
@@ -13,10 +11,10 @@ export interface ShippingChatTurnSpec {
}
/**
* 将发货 UI 动作 id 解析为平台 Chat Turn 规格。
* 将仍允许的 Chat 动作解析为平台 Turn 规格。
* @param actionId - 状态机 action_buttons.id
* @param taskNo - 任务编号
* @param extra - 额外参数,如 confirm_inventory_source 的 source_code
* @param extra - 保留参数,供调用方类型兼容;履约写不再使用。
* @returns Chat Turn 规格;无法映射时返回 null
*/
export function resolveShippingChatTurn(
@@ -29,59 +27,9 @@ export function resolveShippingChatTurn(
const id = String(actionId || '').trim();
if (!id) return null;
if (SHIPPING_DECISION_ACTIONS.has(id)) {
return {
actionType: 'shipping.submit_decision',
payload: { task_no: normalizedTaskNo, decision: id },
};
}
switch (id) {
case 'freeze_order':
const expectedOrderDataVersion = extra?.expectedOrderDataVersion;
if (!Number.isInteger(expectedOrderDataVersion) || !expectedOrderDataVersion || expectedOrderDataVersion < 1) return null;
return {
actionType: 'shipping.freeze_order',
payload: {
task_no: normalizedTaskNo,
expected_order_data_version: expectedOrderDataVersion,
},
};
case 'generate_excel':
return { actionType: 'shipping.generate_excel', payload: { task_no: normalizedTaskNo } };
case 'retry_upload':
return { actionType: 'shipping.retry_upload', payload: { task_no: normalizedTaskNo } };
case 'match_inventory':
return { actionType: 'shipping.match_inventory', payload: { task_no: normalizedTaskNo } };
case 'mark_manual_uploaded':
return { actionType: 'shipping.mark_manual_uploaded', payload: { task_no: normalizedTaskNo } };
case 'confirm_inventory_source': {
const sourceCode = String(extra?.sourceCode || '').trim().toUpperCase();
if (!sourceCode) return null;
return {
actionType: 'shipping.confirm_inventory_source',
payload: { task_no: normalizedTaskNo, source_code: sourceCode },
};
}
default:
return null;
}
}
/**
* 构造 submit_decision Chat Turn(文本/菜单决策共用)。
*/
export function buildShippingSubmitDecisionTurn(
taskNo: string,
decision: string,
): ShippingChatTurnSpec {
return {
actionType: 'shipping.submit_decision',
payload: {
task_no: String(taskNo || '').trim().toUpperCase(),
decision: String(decision || '').trim(),
},
};
void id;
void extra;
return null;
}
/**
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
@@ -1,102 +1,57 @@
/**
* features/chat/shipping/useChatShippingDecision.spec.ts
* 用途:验证发货通知决策处理器经 Chat Turn 发起,silent 模式不追加用户气泡。
* 用途:验证发货 Chat 不再承载履约写,操作只刷新权威 OT 投影。
* 依赖:vitest、vue refs、useChatShippingDecision。
* 逻辑:mock startChatTurn,覆盖 silent/普通决策与显式 taskId 分支。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision';
import type { ChatMessage } from '../types/chat.types';
const defaultStartChatTurn = vi.fn(async (options: {
hooks?: { onAssistantMessageFinished?: (msg: ChatMessage) => Promise<void> };
}) => {
await options?.hooks?.onAssistantMessageFinished?.(
{ role: 'assistant', content: 'mock assistant' },
);
return true;
});
const createContext = (
overrides: Partial<ShippingDecisionContext> = {},
): ShippingDecisionContext => ({
messages: ref([]),
conversationId: ref('conv-001'),
history: ref([{ conversation_id: 'conv-001' }]),
isShippingNoticeAgent: computed(() => true),
currentAgentId: computed(() => 42),
getActiveShippingTaskId: () => 'SN-FOCUS-001',
getActiveShippingBatchNo: () => 'BATCH-001',
loadHistory: vi.fn(async () => undefined),
refreshShippingActions: vi.fn(async () => undefined),
startChatTurn: defaultStartChatTurn,
msg: {
warning: vi.fn(),
success: vi.fn(),
},
t: (key: string) => key,
...overrides,
});
describe('useChatShippingDecision', () => {
beforeEach(() => {
defaultStartChatTurn.mockClear();
});
it('does not append local chat messages when decision runs in silent mode', async () => {
it('does not dispatch a Chat Turn for a legacy decision', async () => {
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('reparse_inventory', '重新上传库存', { silent: true });
expect(ok).toBe(true);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
inputType: 'action',
actionType: 'shipping.submit_decision',
payload: { task_no: 'SN-FOCUS-001', decision: 'reparse_inventory' },
silent: true,
}),
);
expect(ctx.messages.value).toEqual([]);
expect(ok).toBe(false);
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('delegates normal decisions to startChatTurn with display text', async () => {
it('does not dispatch a Chat Turn for a normal legacy decision', async () => {
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('confirm', '确认');
expect(ok).toBe(true);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
actionType: 'shipping.submit_decision',
displayText: expect.stringContaining('SN-FOCUS-001'),
payload: { task_no: 'SN-FOCUS-001', decision: 'confirm' },
}),
);
expect(ok).toBe(false);
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('does not show success toast for retry_rpa inside shipping agent workspace', async () => {
it('refreshes authoritative actions when Chat decision is rejected', async () => {
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('retry_rpa', '重新获取库存');
expect(ok).toBe(true);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
payload: { task_no: 'SN-FOCUS-001', decision: 'retry_rpa' },
}),
);
expect(ctx.msg.success).not.toHaveBeenCalled();
expect(ok).toBe(false);
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('prefers explicit taskId for workspace retry decisions', async () => {
it('does not dispatch even when a legacy decision supplies an explicit taskId', async () => {
const ctx = createContext({
getActiveShippingTaskId: () => '',
});
@@ -104,22 +59,14 @@ describe('useChatShippingDecision', () => {
const ok = await executeShippingDecision('retry_rpa', '重新获取库存', { taskId: 'sn-target-009' });
expect(ok).toBe(true);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
payload: { task_no: 'SN-TARGET-009', decision: 'retry_rpa' },
}),
);
expect(ctx.msg.warning).not.toHaveBeenCalled();
expect(ok).toBe(false);
});
it('returns false when startChatTurn reports failure', async () => {
const ctx = createContext({
startChatTurn: vi.fn(async () => false),
});
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
it('does not dispatch manual upload through Chat', async () => {
const ctx = createContext();
const { executeShippingManualUpload } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('confirm', '确认');
const ok = await executeShippingManualUpload('SN-FOCUS-001');
expect(ok).toBe(false);
});
@@ -1,28 +1,13 @@
/**
* features/chat/shipping/useChatShippingDecision.ts
* 用途:封装人工决策提交与手工上传标记逻辑,统一走 Chat Turn SSE。
* 依赖:shippingTurnActions、chat-turn.types、chat.types。
* 逻辑:由 useChatShipping 调用;所有决策/手工上传经 startChatTurn,不再 push 本地消息或直调 workspace API。
* 用途:阻止 Chat 提交已迁入正式 OT Gate 的履约写操作。
* 依赖:chat.types。
* 逻辑:历史聊天指令只刷新权威投影并提示进入任务处理页;不再构造 Chat Turn 或上传凭据。
*/
import { buildShippingSubmitDecisionTurn, buildShippingTurnRefs } from './shippingTurnActions';
import { reportShippingDebugEvent } from './shippingDebugReporter';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
export interface ShippingDecisionContext {
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
history: Ref<ChatSessionItem[]>;
isShippingNoticeAgent: ComputedRef<boolean>;
currentAgentId: ComputedRef<number>;
getActiveShippingTaskId: () => string;
getActiveShippingBatchNo: () => string;
loadHistory: () => Promise<void>;
refreshShippingActions: () => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
msg: { warning: (text: string) => void; success: (text: string) => void };
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
@@ -34,139 +19,36 @@ export interface ExecuteShippingDecisionOptions {
/**
* 创建发货通知决策处理器。
*
* 核心逻辑:构造 shipping.submit_decision Chat Turn,由平台 SSE 统一渲染 user/assistant 与 ChatLog。
* 核心逻辑:Chat 不再有履约写执行权,只刷新后端 Gate 投影。
* @param ctx - 决策处理上下文
* @returns 人工决策与手工上传确认处理函数
*/
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
const manualUploadInFlightTaskIds = new Set<string>();
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
reportShippingDebugEvent('useChatShippingDecision.ts', hypothesisId, msg, data);
const syncHistoryIfNeeded = async () => {
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
await ctx.loadHistory();
} else if (ctx.conversationId.value) {
const exists = ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value);
if (!exists) await ctx.loadHistory();
}
};
const afterDecisionTurn = async () => {
await syncHistoryIfNeeded();
void ctx.refreshShippingActions();
};
/**
* 在 Chat 操作中选择并上传人工货代回执,返回当前用户私有的 FileAsset 编号。
* 取消选择不会提交“已手工上传”动作,确保后端的证据门禁没有绕过路径。
*/
const selectManualUploadEvidence = () => new Promise<File | null>((resolve) => {
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = 'image/*,.pdf';
picker.style.display = 'none';
document.body.appendChild(picker);
let settled = false;
const finish = (file: File | null) => {
if (settled) return;
settled = true;
picker.remove();
resolve(file);
};
picker.addEventListener('change', () => finish(picker.files?.[0] || null), { once: true });
picker.addEventListener('cancel', () => finish(null), { once: true });
// 部分浏览器不会触发 cancel;窗口重新获得焦点后仍未选择文件即视为取消。
window.addEventListener('focus', () => setTimeout(() => finish(picker.files?.[0] || null), 0), { once: true });
picker.click();
});
/**
* 提交发货人工决策,经 Chat Turn 统一 SSE 返回。
*/
/** 历史 Chat 决策只刷新 Gate 投影,禁止绕过正式 OT。 */
const executeShippingDecision = async (
decision: string,
displayText?: string,
options?: ExecuteShippingDecisionOptions,
) => {
const taskId = String(options?.taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
void reportRetryRpaDebug('D', 'executeShippingDecision entry', {
decision,
taskId,
conversationId: ctx.conversationId.value,
silent: Boolean(options?.silent),
});
void decision;
void displayText;
void options;
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return false;
}
const userText = (displayText || decision).trim();
const turnSpec = buildShippingSubmitDecisionTurn(taskId, decision);
try {
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: options?.silent ? userText : `${userText}\n任务编号:${taskId}`,
actionType: turnSpec.actionType,
payload: turnSpec.payload,
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
silent: options?.silent,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
void assistantMsg;
await afterDecisionTurn();
},
},
});
return ok;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.streamError.generic');
ctx.msg.warning(errorMessage);
return false;
}
await ctx.refreshShippingActions();
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return false;
};
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
if (!normalizedTaskId || manualUploadInFlightTaskIds.has(normalizedTaskId)) return false;
manualUploadInFlightTaskIds.add(normalizedTaskId);
const userText = (displayText || '我已在货代系统完成上传').trim();
try {
const evidenceFile = await selectManualUploadEvidence();
if (!evidenceFile) {
ctx.msg.warning('请先选择货代上传截图或回执文件');
return false;
}
const evidence = await uploadFileAsset(evidenceFile);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: userText,
actionType: 'shipping.mark_manual_uploaded',
payload: { task_no: normalizedTaskId, evidence_asset_no: evidence.asset_no },
refs: buildShippingTurnRefs(normalizedTaskId, ctx.getActiveShippingBatchNo()),
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
assistantMsg.shipping_actions_used = true;
assistantMsg.shipping_actions = undefined;
ctx.messages.value.forEach((rawMsg) => {
if (rawMsg.role === 'assistant') {
rawMsg.shipping_actions = undefined;
}
});
void ctx.refreshShippingActions();
},
},
});
return ok;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
ctx.msg.warning(errorMessage);
return false;
} finally {
manualUploadInFlightTaskIds.delete(normalizedTaskId);
}
void taskId;
void displayText;
await ctx.refreshShippingActions();
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return false;
};
return { executeShippingDecision, executeShippingManualUpload };
@@ -8,23 +8,10 @@ import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createShippingMenuHandlers, type ShippingMenuHandlerContext } from './useChatShippingMenuHandler';
const {
confirmWorkspaceShippingInventorySource,
getWorkspaceShippingTask,
} = vi.hoisted(() => ({
confirmWorkspaceShippingInventorySource: vi.fn(),
getWorkspaceShippingTask: vi.fn(),
}));
const { downloadWorkspaceShippingExcelFile } = vi.hoisted(() => ({
downloadWorkspaceShippingExcelFile: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
confirmWorkspaceShippingInventorySource,
getWorkspaceShippingTask,
}));
vi.mock('./shippingDownload', () => ({
downloadWorkspaceShippingExcelFile,
}));
@@ -54,12 +41,10 @@ const createContext = (
describe('useChatShippingMenuHandler', () => {
beforeEach(() => {
confirmWorkspaceShippingInventorySource.mockReset();
getWorkspaceShippingTask.mockReset();
downloadWorkspaceShippingExcelFile.mockReset();
});
it('uses explicit taskId for retry_rpa workspace actions', async () => {
it('does not execute retry_rpa from a Chat menu', async () => {
const ctx = createContext();
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
@@ -69,16 +54,8 @@ describe('useChatShippingMenuHandler', () => {
{ taskId: 'sn-target-009' },
);
expect(ctx.executeShippingDecision).toHaveBeenCalledWith(
'retry_rpa',
'重新获取库存',
{ taskId: 'SN-TARGET-009' },
);
expect(ctx.executeShippingDecision).not.toHaveBeenCalledWith(
'retry_rpa',
'重新获取库存',
{ taskId: 'SN-ACTIVE-001' },
);
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
expect(ctx.refreshShippingActions).toHaveBeenCalledOnce();
});
it('does not dispatch legacy generate_excel Chat Turn', async () => {
@@ -109,8 +86,7 @@ describe('useChatShippingMenuHandler', () => {
expect(ctx.refreshShippingActions).toHaveBeenCalled();
});
it('reads the displayed order version before freezing through Chat Turn', async () => {
getWorkspaceShippingTask.mockResolvedValue({ order_data_version: 9 });
it('does not dispatch a legacy freeze action through Chat Turn', async () => {
const ctx = createContext();
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
@@ -120,10 +96,7 @@ describe('useChatShippingMenuHandler', () => {
{ taskId: 'sn-freeze-901' },
);
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
actionType: 'shipping.freeze_order',
payload: { task_no: 'SN-FREEZE-901', expected_order_data_version: 9 },
}));
expect(ctx.startChatTurn).not.toHaveBeenCalled();
});
it('passes explicit taskId into inventory picker actions', async () => {
@@ -1,26 +1,19 @@
/**
* features/chat/shipping/useChatShippingMenuHandler.ts
* 用途:分发聊天气泡动作按钮点击;业务动作统一走 Chat Turn SSE。
* 依赖:shippingTurnActions、shipping.api(只读 task 详情)、shippingDownload、chat.types。
* 逻辑:可映射为 action_type 的按钮走 startChatTurn;纯 UI(下载/选文件/表单)仍走本地行为。
* 用途:分发聊天气泡的只读与导航辅助操作。
* 依赖:shippingDownload、chat.types。
* 逻辑:履约写只由正式 OT Gate 执行;历史聊天写动作仅刷新,不再创建 Chat Turn。
*/
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import { buildShippingTurnRefs, resolveShippingChatTurn } from './shippingTurnActions';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingActionButton } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
import type { Ref } from 'vue';
export interface ShippingMenuHandlerContext {
isThinking: Ref<boolean>;
currentAgentId: ComputedRef<number>;
getActiveShippingTaskId: () => string;
getActiveShippingBatchNo: () => string;
messages: Ref<ChatMessage[]>;
sendShippingMenuMessage: (message: string) => Promise<void>;
openShippingInventoryPicker: (taskId?: string) => boolean;
openShippingNoticePicker: (taskId?: string) => boolean;
openShippingCustomerDialog: (taskId: string) => Promise<void>;
executeShippingDecision: (
@@ -30,7 +23,6 @@ export interface ShippingMenuHandlerContext {
) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string, ...args: unknown[]) => string;
}
@@ -43,78 +35,6 @@ export interface HandleShippingMenuActionOptions {
* 创建发货通知动作菜单处理器。
*/
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
const normalizeInventorySourceText = (value: string) =>
String(value || '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '');
const recentInventorySourceHint = () => {
const parts: string[] = [];
for (let i = ctx.messages.value.length - 1; i >= 0 && parts.length < 6; i -= 1) {
const content = String(ctx.messages.value[i]?.content || '').trim();
if (content) parts.push(content);
}
return parts.join('\n');
};
const resolveInventorySourceCodeFromContext = async (taskId: string): Promise<string> => {
const detail = await getWorkspaceShippingTask(taskId);
const resolution = detail.inventory_source_resolution;
const candidates = resolution && typeof resolution === 'object'
? (resolution as { candidates?: unknown }).candidates
: null;
if (!Array.isArray(candidates) || candidates.length === 0) return '';
if (candidates.length === 1) {
const only = candidates[0];
return only && typeof only === 'object'
? String((only as { source_code?: unknown }).source_code || '').trim().toUpperCase()
: '';
}
const hint = normalizeInventorySourceText(recentInventorySourceHint());
if (!hint) return '';
const matches = candidates.filter((item) => {
if (!item || typeof item !== 'object') return false;
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
const values = [
source.source_code,
source.display_name,
source.warehouse_code,
source.program_name,
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
return values.some((value) => hint.includes(value) || value.includes(hint));
});
if (matches.length !== 1) return '';
return String((matches[0] as { source_code?: unknown }).source_code || '').trim().toUpperCase();
};
const runShippingActionTurn = async (
action: ShippingActionButton | { id?: string; message: string; label?: string },
taskId: string,
extra?: { sourceCode?: string; expectedOrderDataVersion?: number },
) => {
const actionId = String(action.id || '').trim();
const turnSpec = resolveShippingChatTurn(actionId, taskId, extra);
if (!turnSpec) return false;
const displayBase = String(action.message || actionId || '操作').trim();
const displayText = actionId === 'confirm_inventory_source'
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmWithTask', { taskId })
: ctx.t('chat.shippingNoticeUi.inventorySource.actionWithTask', { message: displayBase, taskId });
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText,
actionType: turnSpec.actionType,
payload: turnSpec.payload,
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
hooks: {
onAssistantMessageFinished: async () => {
void ctx.refreshShippingActions();
},
},
});
return true;
};
const handleShippingMenuAction = async (
action: ShippingActionButton | { id?: string; message: string },
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
@@ -152,105 +72,17 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
return;
}
// 旧匹配/Excel 动作仅保留历史文案兼容;业务执行必须由 Projection
// 下发的正式 Gate Action 驱动,Chat 不得再创建 legacy Turn。
if (action.id === 'match_inventory' || action.id === 'generate_excel') {
await ctx.refreshShippingActions();
ctx.msg.info(ctx.t('chat.shippingNoticeRefreshDone'));
return;
}
const chatTurnActionIds = new Set([
'freeze_order',
'generate_excel',
'retry_upload',
'match_inventory',
'mark_manual_uploaded',
'confirm_inventory_source',
]);
if (action.id && chatTurnActionIds.has(action.id)) {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
try {
let sourceCode = '';
let expectedOrderDataVersion: number | undefined;
if (action.id === 'freeze_order') {
const detail = await getWorkspaceShippingTask(taskId);
const version = Number(detail.order_data_version);
if (!Number.isInteger(version) || version < 1) {
ctx.msg.warning(ctx.t('chat.shippingNoticeRefreshRequired'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
expectedOrderDataVersion = version;
}
if (action.id === 'confirm_inventory_source') {
sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
if (!sourceCode) {
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
}
if (!sourceCode) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.inventorySource.inputHint'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
}
if (action.id === 'mark_manual_uploaded') {
await ctx.executeShippingManualUpload(taskId, '我已在货代系统完成上传');
return;
}
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
const displayMessage = action.id === 'confirm_inventory_source'
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label: label || sourceCode })
: action.message;
await runShippingActionTurn(
{ ...action, message: displayMessage },
taskId,
sourceCode ? { sourceCode } : { expectedOrderDataVersion },
);
} catch (e: unknown) {
ctx.msg.warning(e instanceof Error ? e.message : '操作失败');
if (chatMsg) chatMsg.shipping_actions_used = false;
}
return;
}
if (action.id === 'retry_resolve_inventory_source') {
await ctx.refreshShippingActions();
ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone'));
return;
}
if (action.id === 'upload_inventory_file') {
ctx.openShippingInventoryPicker(resolveTaskId());
return;
}
if (action.id === 'replace_notice_file') {
ctx.openShippingNoticePicker(resolveTaskId());
return;
}
if (action.id === 'reparse_inventory') {
if (chatMsg?.shipping_actions_used) return;
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
if (chatMsg) chatMsg.shipping_actions_used = true;
const ok = await ctx.executeShippingDecision('reparse_inventory', action.message, { silent: true, taskId });
if (ok) ctx.openShippingInventoryPicker(taskId);
return;
}
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
await ctx.executeShippingDecision(action.id, action.message, { taskId: resolveTaskId() });
if (action.id && [
'freeze_order', 'match_inventory', 'rematch',
'generate_excel', 'retry_upload', 'mark_manual_uploaded', 'reparse_inventory',
'confirm', 'retry_rpa', 'reject', 'reparse',
].includes(action.id)) {
await ctx.refreshShippingActions();
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return;
}
if (chatMsg?.shipping_actions_used) return;
@@ -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;
}
});
};
@@ -4,15 +4,11 @@
* 依赖:shipping.api(任务详情)、shippingIntents、shippingMenu、shippingDownload、chat.types。
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;co8 后切票不再调用 shipping_batches API,改提示用户使用 processing 工作台。
*/
import {
getWorkspaceShippingTask,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import {
isShippingDownloadExcelIntent,
isShippingGenerateExcelIntent,
isShippingInventoryUploadIntent,
isShippingManualUploadIntent,
parseShippingTaskSwitchIntent,
} from './shippingIntents';
@@ -56,7 +52,6 @@ export interface ShippingSendHandlerContext {
loadHistory: () => Promise<void>;
sendShippingMenuMessage: (message: string) => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
openShippingInventoryPicker: () => boolean;
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise<void>;
@@ -95,55 +90,6 @@ export interface ShippingSendHandlerContext {
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
*/
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const normalizeInventorySourceText = (value: string) =>
String(value || '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '');
const tryConfirmInventorySourceFromText = async (content: string): Promise<boolean> => {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) return false;
const normalized = normalizeInventorySourceText(content);
if (!normalized) return false;
try {
const detail = await getWorkspaceShippingTask(taskId);
if (detail.pending_human_reason !== 'inventory_source_unresolved') return false;
const resolution = detail.inventory_source_resolution;
const candidates = resolution && typeof resolution === 'object'
? (resolution as { candidates?: unknown }).candidates
: null;
if (!Array.isArray(candidates) || candidates.length === 0) return false;
const hit = candidates.find((item) => {
if (!item || typeof item !== 'object') return false;
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
const values = [
source.source_code,
source.display_name,
source.warehouse_code,
source.program_name,
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
return values.some((value) => normalized === value || normalized.includes(value) || value.includes(normalized));
}) as { source_code?: unknown; display_name?: unknown } | undefined;
const sourceCode = String(hit?.source_code || '').trim().toUpperCase();
if (!sourceCode) return false;
if (typeof content !== 'string') return false;
ctx.input.value = '';
ctx.attachments.value = [];
const label = String(hit?.display_name || sourceCode).trim();
await ctx.handleShippingMenuAction({
id: 'confirm_inventory_source',
message: ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label }),
label,
source_code: sourceCode,
});
return true;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUi.inventorySource.confirmFailed');
ctx.msg.warning(errorMessage);
return true;
}
};
/**
* 拦截切票/切任务意图(co8 已下线批次 API)。
*
@@ -280,11 +226,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.attachments.value = [];
return true;
}
if (await tryConfirmInventorySourceFromText(content)) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
return true;
}
const assistantCtx = ctx.lastAssistantMessageContent();
const numericText = content.trim();
if (/^[1-91-9](?:[\.\、\)::]?)$/.test(numericText)) {
@@ -303,9 +244,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
if (menuChoice) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
if (menuChoice === 'upload') {
if (ctx.openShippingInventoryPicker()) return true;
} else if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
const spec = SHIPPING_MENU_ACTION_SPECS[menuChoice];
await ctx.executeShippingDecision(menuChoice, spec?.label || spec?.message || menuChoice);
return true;
@@ -320,32 +259,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
if (await ctx.executeShippingDecision(shippingDecision, content.trim())) return true;
}
if (isShippingManualUploadIntent(content)) {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning('未找到任务编号,请先完成前面的步骤');
return true;
}
ctx.resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.executeShippingManualUpload(taskId, content.trim());
return true;
}
if (isShippingInventoryUploadIntent(content, assistantCtx)) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
if (ctx.openShippingInventoryPicker()) return true;
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return true;
}
if (isShippingGenerateExcelIntent(content)) {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning('未找到任务编号,请先完成解析与库存匹配');
return true;
}
ctx.resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.handleShippingMenuAction({ id: 'generate_excel', message: content.trim() });
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return true;
}
if (isShippingDownloadExcelIntent(content)) {
@@ -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',
@@ -311,7 +324,7 @@ describe('useShippingNoticeWorkflow', () => {
ctl.stop();
});
it('derives sibling OT tasks from work_items when embedded conversation_processing omits them', async () => {
it('aggregates sibling EML OT work_items into one highest-attention Intake card', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [
@@ -397,7 +410,12 @@ describe('useShippingNoticeWorkflow', () => {
await Promise.resolve();
expect(ctl.processing.value?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(ctl.processing.value?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
expect(ctl.processing.value?.processing).toEqual([]);
expect(ctl.processing.value?.needs_action[0]?.aggregateSummary).toMatchObject({
intakeNo: 'SNI-1',
total: 2,
processing: 1,
});
expect(ctl.processing.value?.focused_task_no).toBe('OT-ROOT');
expect(ctl.processing.value?.recent_task_no).toBe('OT-SIBLING');
ctl.stop();
@@ -413,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();
@@ -445,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;空则停轮询并清空。 */
@@ -49,7 +69,7 @@ export type UseShippingNoticeWorkflowOptions = {
};
export type UseShippingNoticeWorkflowReturn = {
/** 后端 conversation_processing / 由 work_items 合成。 */
/** 后端 conversation_processing;仅旧接口缺状态组时由 work_items 兼容合成。 */
processing: Ref<ConversationProcessingProjection | null>;
/** 统一 ShippingProcessing work_items。 */
processingWorkItems: Ref<ShippingProcessingProjection[]>;
@@ -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,96 @@ 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,
lifecycleEntries: item.uiState?.lifecycleEntries?.map((entry) => ({
code: entry.code,
state: entry.state,
targetSurface: entry.targetSurface,
disabledReasonKey: entry.disabledReasonKey ?? 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,
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
code: entry.code,
state: entry.state,
targetSurface: entry.targetSurface,
disabledReasonKey: entry.disabledReasonKey ?? null,
})) ?? [],
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 +281,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;
}
@@ -201,7 +305,7 @@ export function useShippingNoticeWorkflow(
/**
* 仅拉取统一 shipping-processing 投影。
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
* 核心逻辑:后端 status_groups 存在时直接使用;仅旧响应缺状态组才由 work_items 合成;
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据;
* 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。
*
@@ -214,22 +318,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 +354,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 +411,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 +430,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 +439,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 +548,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 +572,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 +585,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 +623,9 @@ export function useShippingNoticeWorkflow(
initialLoading,
manualRefreshing,
polling,
isFetching,
isRefreshing,
snapshotUpdatedAt,
error,
refresh,
focusConversationTask,
@@ -136,6 +136,80 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
harness.runs.stopPolling();
});
it('merges sibling Runs from one upload batch into one chat status card', async () => {
const first = Object.assign(run({
run_no: 'SNER-BATCH-1',
conversation_id: 'conv-batch',
intake_nos: ['SNI-BATCH-1'],
summary: {
total_documents: 1,
pending_documents: 1,
processing_documents: 0,
completed_documents: 0,
review_required_documents: 0,
failed_documents: 0,
candidate_count: 0,
},
documents: [{
unit_id: 1,
document_id: 101,
file_name: 'notice-a.pdf',
status: 'queued',
line_count: 0,
email_supplement: { status: 'none', relation_codes: [] },
available_actions: [],
}],
}), { upload_batch_id: 'upload-batch-1' });
const second = Object.assign(run({
run_no: 'SNER-BATCH-2',
conversation_id: 'conv-batch',
intake_nos: ['SNI-BATCH-2'],
summary: {
total_documents: 1,
pending_documents: 0,
processing_documents: 1,
completed_documents: 0,
review_required_documents: 0,
failed_documents: 0,
candidate_count: 0,
},
documents: [{
unit_id: 2,
document_id: 102,
file_name: 'notice-b.pdf',
status: 'processing',
line_count: 0,
email_supplement: { status: 'none', relation_codes: [] },
available_actions: [],
}],
}), { upload_batch_id: 'upload-batch-1' });
api.createSubmission.mockResolvedValue({
decision: 'created',
user_task_no: null,
run_no: first.run_no,
created_new: true,
operation_id: 'op-batch',
});
api.getRun.mockResolvedValue(first);
api.listRuns.mockResolvedValue({ items: [first, second] });
const harness = createHarness();
await harness.runs.startRun('', ['SNI-BATCH-1', 'SNI-BATCH-2'], [], 'upload-batch-1');
const cards = harness.messages.value.filter((message) => message.shipping_order_extraction_state);
expect(cards).toHaveLength(1);
expect(cards[0]?.shipping_order_extraction_state?.summary).toMatchObject({
totalDocuments: 2,
pendingDocuments: 1,
processingDocuments: 1,
});
expect(cards[0]?.shipping_order_extraction_state?.documents?.map((item) => item.fileName)).toEqual([
'notice-a.pdf',
'notice-b.pdf',
]);
harness.runs.stopPolling();
});
it('keeps an appended submission in the user message and the existing Run state card only', async () => {
const queued = run({
run_no: 'SNER-APPENDED',
@@ -54,6 +54,69 @@ const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
/**
* 将同一上传批次的独立 Run 合成单张聊天状态卡。
*
* 核心逻辑:Run 仍按 Intake 独立执行、审计和复核;仅把同会话同 upload_batch_id
* 的用户态摘要相加,保证一次文件选择在聊天区只出现一个卡片。
*/
function mergeUploadBatchRuns(primary: ShippingOrderExtractionRun, runs: ShippingOrderExtractionRun[]): ShippingOrderExtractionRun {
const batchId = String(primary.upload_batch_id || '').trim();
if (!batchId) return primary;
const members = runs.filter((item) => (
item.conversation_id === primary.conversation_id
&& String(item.upload_batch_id || '').trim() === batchId
));
if (members.length <= 1) return primary;
const activeMembers = members.filter((item) => ACTIVE_RUN_STATUSES.has(item.status));
const status = activeMembers.some((item) => item.status === 'processing')
? 'processing'
: activeMembers.length > 0
? 'queued'
: members.some((item) => item.status === 'failed')
? 'failed'
: members.some((item) => item.status === 'review_required')
? 'review_required'
: members.some((item) => item.status === 'partially_completed')
? 'partially_completed'
: 'completed';
const failedParseMembers = members.filter((item) => (
item.documents || []
).some((document) => document.reason_code === 'intake_parse_failed' || String(document.user_visible_stage || '') === 'parse_failed'));
const effectiveStatus = failedParseMembers.length > 0 && activeMembers.length === 0 ? 'failed' : status;
const summaryKeys = [
'total_documents', 'pending_documents', 'processing_documents', 'completed_documents',
'review_required_documents', 'failed_documents', 'cancelled_documents', 'candidate_count',
'opened_existing_documents',
] as const;
const summary = summaryKeys.reduce((result, key) => {
result[key] = members.reduce((total, item) => total + Number(item.summary?.[key] || 0), 0);
return result;
}, {} as ShippingOrderExtractionRun['summary']);
const documentIds = new Set<number>();
const documents = members.flatMap((item) => item.documents || []).filter((item) => {
const id = Number(item.document_id || 0);
if (id && documentIds.has(id)) return false;
if (id) documentIds.add(id);
return true;
});
const mostRecent = [...members].sort((left, right) => String(right.last_activity_at || '').localeCompare(String(left.last_activity_at || '')))[0] || primary;
return {
...primary,
status: effectiveStatus,
phase: effectiveStatus,
intake_nos: [...new Set(members.flatMap((item) => item.intake_nos || []))],
summary,
documents,
current_activity: mostRecent.current_activity || primary.current_activity,
available_actions: [...new Set(members.flatMap((item) => item.available_actions || []))],
handling_items: members.flatMap((item) => item.handling_items || []),
health_tips: members.flatMap((item) => item.health_tips || []),
progress_version: Math.max(...members.map((item) => Number(item.progress_version || 0))),
last_activity_at: mostRecent.last_activity_at || primary.last_activity_at,
};
}
/** 按页面可见性选择轮询间隔;后台放慢,失败退避另算。 */
function resolvePollIntervalMs(failureCount = 0): number {
if (failureCount > 0) {
@@ -72,6 +135,7 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
userTaskNo: run.user_task_no || null,
submissionOrdinal: run.submission_ordinal ?? null,
composerContextId: run.composer_context_id || null,
uploadBatchId: run.upload_batch_id || null,
runNo: run.run_no,
sourceRunNo: run.reparse?.source_run_no || null,
supersedingRunNo: run.reparse?.superseding_run_no || null,
@@ -110,6 +174,20 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
lastActivityAt: run.current_activity.last_activity_at || null,
}
: null,
documents: Array.isArray(run.documents)
? run.documents.map((item) => ({
unitId: Number(item.unit_id || 0),
documentId: Number(item.document_id || 0),
intakeId: item.intake_id != null ? Number(item.intake_id || 0) || null : null,
documentType: item.document_type || null,
fileName: item.file_name || null,
status: String(item.status || ''),
userVisibleStage: item.user_visible_stage || null,
reasonCode: item.reason_code || null,
explainability: item.explainability ? { message: item.explainability.message || null } : null,
emailSupplement: item.email_supplement ? { status: item.email_supplement.status || null } : null,
}))
: [],
selectionPlan: run.selection_plan
? {
selectionVersion: run.selection_plan.selection_version || null,
@@ -218,6 +296,22 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
return composerContextId;
}
/**
* 读取同批次兄弟 Run 后生成聊天展示快照。
*
* 仅在服务端已返回 upload_batch_id 时查询;旧 Run 或重识别 Run 保持原有单卡逻辑。
*/
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => {
if (!String(run.upload_batch_id || '').trim()) return run;
try {
const response = await listWorkspaceShippingOrderExtractionRuns(run.conversation_id, 100);
return mergeUploadBatchRuns(run, response.items || []);
} catch {
// 聚合读失败时宁可显示本 Run 的真实状态,也不阻断轮询或误改业务状态。
return run;
}
};
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
const stopPolling = () => {
if (pollTimer) clearTimeout(pollTimer);
@@ -260,10 +354,18 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
): Promise<ChatMessage> => {
const formId = `shipping-order-extraction-run:${run.run_no}`;
const state = mapOrderExtractionRunToMessageState(run);
const uploadBatchId = String(run.upload_batch_id || '').trim();
const stateCards = options.messages.value.filter((item) => {
if (item.role !== 'assistant') return false;
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
return payload.formId === formId || payload.order_extraction_run_no === run.run_no;
const cardBatchId = String(
payload.shipping_order_extraction_upload_batch_id
|| item.shipping_order_extraction_state?.uploadBatchId
|| '',
).trim();
return payload.formId === formId
|| payload.order_extraction_run_no === run.run_no
|| Boolean(uploadBatchId && cardBatchId === uploadBatchId);
});
let message = stateCards.find((item) => {
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
@@ -287,6 +389,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
message.payload = {
formId,
order_extraction_run_no: run.run_no,
shipping_order_extraction_upload_batch_id: run.upload_batch_id || null,
shipping_order_extraction_state: state,
order_extraction_reparse: run.reparse || null,
shipping_order_extraction_review: reviewAttachments || [],
@@ -386,18 +489,20 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const request = createRequestController(generation);
const run = await getWorkspaceShippingOrderExtractionRun(runNo, request.signal).finally(request.release);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
const displayRun = await loadDisplayRun(run);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
pollFailureCount = 0;
setRunRefreshFailed(run.run_no, false);
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
const reviewAttachments = await refreshTerminalFacts(run);
setRunRefreshFailed(displayRun.run_no, false);
if (!ACTIVE_RUN_STATUSES.has(displayRun.status)) {
const reviewAttachments = await refreshTerminalFacts(displayRun);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
stopPolling();
await upsertRunMessage(run, reviewAttachments);
await acknowledgeTerminalRunWhenVisible(run);
await upsertRunMessage(displayRun, reviewAttachments);
await acknowledgeTerminalRunWhenVisible(displayRun);
return;
}
await upsertRunMessage(run);
await acknowledgeTerminalRunWhenVisible(run);
await upsertRunMessage(displayRun);
await acknowledgeTerminalRunWhenVisible(displayRun);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
pollTimer = setTimeout(() => void pollRun(run.run_no, generation), resolvePollIntervalMs(0));
} catch {
@@ -456,7 +561,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
focused_user_task_no: focusedUserTaskNo,
});
// 统一提交只返回决策摘要;再拉 Run 投影供状态卡与轮询。
const run = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
const submittedRun = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
const run = await loadDisplayRun(submittedRun);
if (!options.conversationId.value) {
options.conversationId.value = run.conversation_id;
composerBoundConversationId = run.conversation_id;
@@ -487,7 +593,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
await options.onConversationResolved(run.conversation_id);
options.onWorkflowRefresh?.();
if (ACTIVE_RUN_STATUSES.has(run.status)) {
beginPolling(run.run_no, 1000);
beginPolling(submittedRun.run_no, 1000);
} else {
const reviewAttachments = await refreshTerminalFacts(run);
await upsertRunMessage(run, reviewAttachments);
@@ -524,7 +630,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const normalizedRunNo = String(runNo || '').trim();
if (!normalizedRunNo) return false;
try {
const run = await getWorkspaceShippingOrderExtractionRun(normalizedRunNo);
const fetchedRun = await getWorkspaceShippingOrderExtractionRun(normalizedRunNo);
const run = await loadDisplayRun(fetchedRun);
setRunRefreshFailed(run.run_no, false);
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
const reviewAttachments = await refreshTerminalFacts(run);
@@ -533,7 +640,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
return true;
}
await upsertRunMessage(run);
if (activeRunNo !== run.run_no || !pollTimer) beginPolling(run.run_no, FOREGROUND_POLL_MS);
if (activeRunNo !== fetchedRun.run_no || !pollTimer) beginPolling(fetchedRun.run_no, FOREGROUND_POLL_MS);
return true;
} catch (error) {
setRunRefreshFailed(normalizedRunNo, true);
@@ -662,15 +769,16 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const latest = items[0];
if (!latest) return;
activeRunNo = latest.run_no;
const reviewAttachments = ACTIVE_RUN_STATUSES.has(latest.status)
const displayRun = mergeUploadBatchRuns(latest, items);
const reviewAttachments = ACTIVE_RUN_STATUSES.has(displayRun.status)
? undefined
: await refreshTerminalFacts(latest);
: await refreshTerminalFacts(displayRun);
if (options.conversationId.value !== conversationId) return;
await upsertRunMessage(latest, reviewAttachments);
await acknowledgeTerminalRunWhenVisible(latest);
await upsertRunMessage(displayRun, reviewAttachments);
await acknowledgeTerminalRunWhenVisible(displayRun);
options.onWorkflowRefresh?.();
if (options.conversationId.value !== conversationId) return;
if (ACTIVE_RUN_STATUSES.has(latest.status)) {
if (ACTIVE_RUN_STATUSES.has(displayRun.status)) {
beginPolling(latest.run_no, 1000);
}
} catch {
@@ -23,7 +23,6 @@ import { normalizeShippingProcessingProjection } from './normalizeShippingProces
const DEFAULT_POLL_MS = 3000;
const TERMINAL_STATUSES = new Set([
'completed',
'failed',
'cancelled',
]);
@@ -77,6 +77,20 @@ export interface ShippingOrderExtractionCurrentActivityState {
lastActivityAt?: string | null;
}
/** 聊天批处理卡按文件展示的只读状态;业务真相仍由 Run/Unit 后端投影提供。 */
export interface ShippingOrderExtractionFileState {
unitId: number;
documentId: number;
intakeId?: number | null;
documentType?: string | null;
fileName?: string | null;
status: string;
userVisibleStage?: string | null;
reasonCode?: string | null;
explainability?: { message?: string | null } | null;
emailSupplement?: { status?: string | null } | null;
}
export interface ShippingOrderExtractionSelectionPlanState {
selectionVersion?: string | null;
maxInitialAttachments?: number;
@@ -143,6 +157,8 @@ export interface ShippingOrderExtractionState {
submissionOrdinal?: number | null;
/** 当前输入区短生命周期上下文;发送决策用,非业务主键 */
composerContextId?: string | null;
/** 同一次文件选择的聊天卡聚合键;绝不参与业务写入或任务路由。 */
uploadBatchId?: string | null;
/** Run 版本谱系;由后端投影,供历史消息只读隔离。 */
runNo?: string | null;
sourceRunNo?: string | null;
@@ -151,6 +167,7 @@ export interface ShippingOrderExtractionState {
readOnlyReason?: string | null;
summary: ShippingOrderExtractionStateSummary;
currentActivity?: ShippingOrderExtractionCurrentActivityState | null;
documents?: ShippingOrderExtractionFileState[];
selectionPlan?: ShippingOrderExtractionSelectionPlanState | null;
unitSummary?: ShippingOrderExtractionUnitSummaryState | null;
availableActions: string[];
@@ -87,11 +87,11 @@ export type ShippingProcessingActionIntent =
| 'confirm_customer'
| 'resolve_field_conflicts'
| 'adjudicate_duplicate'
| 'open_inventory_source_review'
| 'open_inventory_match_review'
| 'open_shortage_review'
| 'upload_inventory_file'
| 'retry'
| 'reparse_batch'
| 'refresh'
| 'regenerate_excel'
| 'download_excel'
@@ -156,6 +156,21 @@ export interface ShippingProcessingPrimaryAction {
code: string;
i18nKey?: string | null;
parameters?: Record<string, unknown>;
/** 后端裁决为跳转时,前端只按目标工作面路由,不重新推断阶段。 */
executionMode?: 'navigate' | 'execute';
targetSurface?: 'order_lifecycle_workbench' | null;
targetLifecycleStage?: LifecycleWorkbenchStage | null;
}
/** 订单生命周期工作台的后端目标阶段。 */
export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
/** 文件级生命周期入口;状态、目标均由后端裁决。 */
export interface ShippingProcessingLifecycleEntry {
code: LifecycleWorkbenchStage;
state: 'available' | 'current' | 'unavailable';
targetSurface: 'order_lifecycle_workbench';
disabledReasonKey?: string | null;
}
/**
@@ -326,7 +341,7 @@ export interface ShippingProcessingProjection {
assetStatus?: string | null;
};
childOrderTasks: ShippingOrderTaskSummary[];
// ============== [T8 用户态 Projection 7 字段] ==============
// ============== [T8 用户态 Projection 6 字段] ==============
// 后端 apply_user_projection_fields 下发;旧客户端不识别会直接忽略(安全);
// 新前端优先用本字段停止本地推导。
/** 用户态 status(6 枚举:running / waiting_human / retryable / failed / completed / cancelled)。 */
@@ -337,12 +352,23 @@ export interface ShippingProcessingProjection {
userCurrentGateCode?: string | null;
/** 阻断原因:{code, i18nKey, details};status=waiting_human / retryable / failed 时非空。 */
blockingReason?: ShippingProcessingBlockingReason | null;
/** 技术失败是否可重试;业务阻断(waiting_human)通常 false。 */
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 的用户可见全局分组;由后端按子附件最高关注级别裁决。 */
userGroup?: 'failed' | 'waiting_human' | 'processing' | 'completed' | 'cancelled' | 'archived' | null;
/** 同一 EML Intake 的后端聚合摘要;子附件仍以 aggregate_children 保留在服务端。 */
aggregateSummary?: ConversationProcessingUserTask['aggregateSummary'];
/** EML Intake 聚合卡的真实子附件工作项;仅展示,不作为写操作目标。 */
aggregateChildren?: ShippingProcessingProjection[];
/** 旧 status 备份(T8 apply_user_projection_fields.legacy_status);调试用。 */
legacyStatus?: string | null;
/** 旧 stage 备份(T8 apply_user_projection_fields.legacy_stage);调试用。 */
@@ -359,7 +385,7 @@ export interface ShippingProcessingProjection {
/**
* 题4A & 7A:逐源 inventory 准备状态(ShippingProcessingProjection.inventoryPreparation)。
* 按实际冻结源 required_sources 为基准分类,failed/exhausted 拆分暴露。
* 按实际冻结源 required_sources 为基准分类并暴露当前成功、等待和失败事实。
*/
export interface ShippingInventoryPreparationSummary {
/** 实际任务级冻结源(task.task_frozen_inventory_source_codes),顺序以冻结记录为准。 */
@@ -368,17 +394,15 @@ export interface ShippingInventoryPreparationSummary {
preparedSources: string[];
/** RPA 正在跑或入队中(queued / running);active_attempt_count > 0 的对应源集合。 */
pendingSources: string[];
/** 最近一次失败状态(attempt.status == failed)但未耗尽自动次数的源。 */
/** 最近一次失败状态(attempt.status == failed)的源。 */
failedSources: string[];
/** 题7A:自动重试 max_attempts 已耗尽但允许人工 user_retry 继续的源;独立于 failed,便于 UI 提示。 */
exhaustedSources: string[];
/** 全表当前 queued+running Attempt 总数(>= pendingSources.length,存在 Gate 活动 Attempt 时会更高)。 */
activeAttemptCount: number;
/** 题2B:Process Gate 是否有 queued/running 状态的 inventory 批次;作为全局 running 额外保护。 */
gateAttemptActive?: boolean;
/**
* 按冻结源逐源最近 Attempt 摘要(source_code → 结构化记录)。
* 用于 UI tooltip/详情;按钮禁用不直接读本字典,读上面的 required/prepared/pending/failed/exhausted 集合。
* 用于 UI tooltip/详情;按钮禁用不直接读本字典,读上面的 required/prepared/pending/failed 集合。
*/
latestAttempts?: Record<string, ShippingInventoryPerSourceAttempt>;
}
@@ -390,9 +414,9 @@ export interface ShippingInventoryPreparationSummary {
export interface ShippingInventoryPerSourceAttempt {
sourceCode: string;
attemptNo: number;
/** queued | running | consumed | failed | exhausted | skipped */
/** queued | running | consumed | failed | skipped */
status: string;
/** 失败/耗尽:人工可继续;running/queued:false */
/** 失败:用户可选择明确恢复动作;running/queued:false */
manualRetryable?: boolean;
/** attempt.error_message 或 业务错误摘要,供 tooltip。 */
message?: string | null;
@@ -578,11 +602,27 @@ export interface ConversationProcessingUserTask {
userStage?: ShippingUserProcessingStage | null;
userCurrentGateCode?: string | null;
blockingReason?: ShippingProcessingBlockingReason | null;
retryable?: boolean;
primaryAction?: ShippingProcessingPrimaryAction | null;
facts?: ShippingProcessingFacts;
/** EML Intake 的用户可见全局分组;前端只消费,不从附件状态自行推导。 */
userGroup?: ShippingProcessingProjection['userGroup'];
legacyStatus?: string | null;
legacyStage?: string | null;
/** 同一 EML Intake 聚合后的子任务状态,仅供展示,不作为写操作事实。 */
aggregateSummary?: {
intakeNo: string;
total: number;
completed: number;
processing: number;
needsAction: number;
failed: number;
stages: string[];
reasonCodes: string[];
} | null;
/** EML 聚合内的真实邮件/附件子项;仅用于展开明细展示。 */
aggregateChildren?: ShippingProcessingProjection[];
/** 后端已裁决的节点级用户态;状态、原因及按钮均以此为准。 */
uiState?: ConversationProcessingUiState;
}
/**
@@ -592,6 +632,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;
/** 识别完成且尚未查看的成功通知数 */
@@ -625,6 +669,55 @@ export interface ConversationProcessingProjection {
/** 成功完成待查看;与 needs_action 异常态分离 */
completed?: ConversationProcessingUserTask[];
history: ConversationProcessingUserTask[];
/** 按 EML Intake 唯一归组后的六类用户状态;同一 EML 只允许出现一次。 */
status_groups?: {
failed: ConversationProcessingUserTask[];
waiting_human: ConversationProcessingUserTask[];
processing: ConversationProcessingUserTask[];
completed: ConversationProcessingUserTask[];
cancelled: ConversationProcessingUserTask[];
archived: ConversationProcessingUserTask[];
};
/** 会话批次主进度;后端已将技术阶段折叠为四个业务节点。 */
four_stage_nodes?: Array<{
code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
label_key: string;
status: 'passed' | 'running' | 'blocked' | 'pending';
/** 批次阶段摘要由后端按完整叶子工作项裁决,禁止页面从筛选结果反算。 */
summary?: {
total: number;
completed: number;
needs_action: number;
processing: number;
failed: number;
blocking_reason?: ShippingProcessingBlockingReason | null;
};
}>;
/** 后端无法归类到四阶段的业务文件数量;页面只提示,不擅自归类。 */
unclassified_summary?: { count: number };
/** 批次级用户态:状态、问题与可操作动作必须来自同一次后端裁决。 */
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;
/** 后端从技术节点裁决的四阶段业务编码,批次中心与工作台共同消费。 */
lifecycleStage?: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
lifecycleEntries?: ShippingProcessingLifecycleEntry[];
blocking_reason: ShippingProcessingBlockingReason | null;
primary_action: ShippingProcessingPrimaryAction | null;
/** 次动作同样可由后端指定生命周期目标,前端不能将其降级为无目标的查看结果。 */
secondary_actions: Array<ShippingProcessingPrimaryAction & { code: string; enabled: boolean }>;
}
/**
@@ -665,14 +758,14 @@ export type InventorySourceStatus =
| 'unresolved'
| 'ambiguous'
| 'resolved'
| 'user_confirmed'
| 'candidates_frozen'
| 'invalid'
| 'conflicted';
export type InventorySourceMethod =
| 'rule_exact'
| 'rule_combined'
| 'user_confirmed'
| 'rule_evaluation_freeze'
| 'legacy_migrated';
export interface ShippingInventorySourceCandidate {
@@ -688,6 +781,7 @@ export interface ShippingInventorySourceResolution {
status?: InventorySourceStatus | null;
method?: InventorySourceMethod | null;
reason?: string | null;
release_field_values?: Record<string, string>;
candidates?: ShippingInventorySourceCandidate[];
destination_candidates?: string[];
evidence?: Record<string, unknown>[];
@@ -731,7 +825,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;
@@ -772,8 +865,6 @@ export interface ShippingTaskSummary {
inventory_source_method?: InventorySourceMethod | null;
inventory_source_config_version?: string | null;
inventory_routing_fingerprint?: string | null;
inventory_source_confirmed_at?: string | null;
inventory_source_confirmed_by?: number | null;
inventory_snapshot?: ShippingInventorySnapshot | null;
created_at?: string | null;
updated_at?: string | null;
@@ -945,16 +1036,12 @@ export type ShippingProcessGateActionCode =
| 'adjudicate_duplicate'
| 'resolve_field_conflicts'
| 'retry_with_latest_rules'
| 'open_inventory_source_review'
| 'adopt_rule_suggestion'
| 'keep_manual_inventory_decision'
| 'recheck_freeze_readiness'
| 'retry_task_creation'
| 'retry_inventory_preparation'
| 'poll_inventory_preparation'
| 'upload_inventory_file'
| 'retry_inventory_field_mapping'
| 'confirm_inventory_field_mapping'
| 'retry_inventory_matching'
| 'retry_inventory_from_preparation'
| 'retry_inventory_from_field_mapping'
@@ -966,7 +1053,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 =
@@ -1005,7 +1093,10 @@ export interface ShippingProcessGateActionPresentation {
code: string;
label_key: string;
kind: 'current_gate' | 'recovery' | 'view' | string;
dispatch: 'navigation' | 'mutation' | 'refresh' | string;
dispatch: 'navigation' | 'mutation' | 'refresh' | 'view' | 'dialog' | string;
ui_handler?: string | null;
target_surface?: ShippingActionTargetSurface | null;
target_anchor?: ShippingActionTargetAnchor | null;
}
/** 服务端 RecoveryPlan 只读目标;target_gate 由后端合同推导,客户端不得提交覆盖。 */
@@ -1029,6 +1120,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;
@@ -1310,12 +1404,101 @@ 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;
/** 正式任务与批次中心同源的生命周期入口,前端仅投影。 */
lifecycle_stage?: ShippingBusinessStage | null;
lifecycle_entries?: ShippingProcessingLifecycleEntry[];
/** 无有效 Candidate 时的独立接收解析处置授权;不是订单生命周期入口。 */
intake_parse_authorized?: boolean;
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[];
};
/** 四阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */
stage_context?: {
preparation?: {
status?: 'processing' | 'blocked' | 'ready' | string;
reason_code?: string | null;
frozen_order?: { task_no?: string | null; snapshot_id?: number | null } | null;
/** 冻结订单行始终可读;不依赖库存文件或匹配结果。 */
frozen_order_lines?: Array<{
line_key?: string | null;
reservation_id?: string | null;
part_number?: string | null;
required_qty?: string | number | null;
}>;
inventory_source_code?: string | null;
/** 库存准备源仅表达文件获取进度,不能替代行级匹配源。 */
inventory_sources?: Array<{
source_code?: string | null;
status?: string | null;
inventory_file_id?: number | null;
}>;
/** 仅当前任务活动关联的库存快照才可下载。 */
inventory_file?: { available?: boolean; file_name?: string | null } | null;
match_status?: string | null;
has_match_result?: boolean;
lines?: Array<{
line_key?: string | null;
reservation_id?: string | null;
part_number?: string | null;
required_qty?: string | number | null;
available_qty?: string | number | null;
shortage_qty?: string | number | null;
source_code?: string | null;
status?: string | null;
}>;
artifact?: { file_name?: string | null; status?: string | null } | null;
} | null;
upload?: {
outcome?: 'not_started' | 'running' | 'awaiting_manual' | 'succeeded' | 'failed' | 'unknown' | string;
latest_attempt?: {
id?: number | null;
status?: string | null;
mode?: string | null;
freight_ref_no?: string | null;
error_code?: string | null;
finished_at?: string | null;
} | null;
} | null;
} | null;
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;
@@ -1343,15 +1526,45 @@ 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;
}
/** 后端 Gate / Artifact 声明的生命周期工作面;未知值不得由前端猜测归属。 */
export type ShippingActionTargetSurface =
| 'intake_parse'
| 'order_review'
| 'fulfillment_prep'
| 'upload_complete'
| string;
/** 后端 Gate / Artifact 声明的页面内动作槽位。 */
export type ShippingActionTargetAnchor =
| 'excel_artifact'
| 'freight_upload'
| 'manual_upload'
| string;
export interface ShippingUnifiedAction {
code: string;
label?: string | null;
kind: ShippingActionKind | string;
/** 后端 Gate 裁决的执行分派,客户端只负责调用对应宿主能力。 */
dispatch: 'navigation' | 'mutation' | 'refresh' | 'view' | 'dialog' | string;
/** 后端声明的既有页面宿主能力;不用于动作展示或授权。 */
ui_handler?: string | null;
enabled: boolean;
requires_confirmation: boolean;
target_surface?: ShippingActionTargetSurface | null;
target_anchor?: ShippingActionTargetAnchor | null;
disabled_reason?: string | null;
expected_gate_version?: number | null;
}
/**
* `shipping_ui_state` SSE 与历史回放共用的恢复契约。
* 核心逻辑:任务锚点 `task_no` 是 open_existing 场景恢复聊天工作台的最小必需字段;
@@ -1662,6 +1875,8 @@ export interface ShippingOrderExtractionEmailSupplementResult {
export interface ShippingOrderExtractionDocumentResult {
unit_id: number;
document_id: number;
intake_id?: number | null;
document_type?: string | null;
file_name?: string | null;
status: ShippingOrderExtractionDocumentStatus;
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
@@ -1718,6 +1933,8 @@ export interface ShippingOrderExtractionRun {
status: ShippingOrderExtractionRunStatus;
phase: string;
intake_nos: string[];
/** 同一次文件选择的展示聚合键;不是 user_task_no,不能用于业务写入。 */
upload_batch_id?: string | null;
schema_version_id: number;
schema_version?: number | null;
schema_checksum?: string | null;
@@ -1764,6 +1981,7 @@ export interface ShippingOrderExtractionRun {
technical_failure_reason_codes?: string[];
} | null;
current_activity?: ShippingOrderExtractionCurrentActivity | null;
documents?: ShippingOrderExtractionDocumentResult[];
available_actions: string[];
/** Run 级处理事项;聊天卡与右侧「本次处理」按类别展示。 */
handling_items?: Array<{
@@ -1958,6 +2176,8 @@ export interface ReviewWorkbenchAuditContext {
document_id?: number | null;
field_id?: string | null;
line_key?: string | null;
/** header | line | line_unassigned | unscoped;相同 field_code 在订单头和明细行是不同业务字段。 */
scope?: 'header' | 'line' | 'line_unassigned' | 'unscoped' | string | null;
page_no?: number | null;
evidence_ref?: string | null;
draft_version?: number | null;
@@ -2018,12 +2238,24 @@ export interface ShippingOrderReviewDraftLine {
export interface ShippingOrderReviewCaseSummary {
case_no: string;
/** 文件级复核主线;主队列以此而非 Run/Case 历史去重。 */
stream_id?: number | null;
revision_no?: number | null;
stream_state?: 'active' | 'reparsing' | 'confirmed' | 'closed' | 'conflict' | string | null;
document_id: number;
file_name?: string | null;
status: string;
/** 工作台队列的后端只读摘要;不允许由当前 Case 草稿补造。 */
po_number?: string | null;
lifecycle_stage?: LifecycleWorkbenchStage | null;
/** Run/Queue 也下发的后端授权入口;工作台不可用 stage 推断。 */
lifecycle_entries?: ShippingProcessingLifecycleEntry[];
/** 无有效 Candidate 时的独立接收解析处置授权;不是订单生命周期入口。 */
intake_parse_authorized?: boolean;
draft_version?: number | null;
issue_count: number;
available_actions: string[];
source_run_no?: string | null;
}
export interface ShippingOrderReviewRun {
@@ -2033,6 +2265,48 @@ export interface ShippingOrderReviewRun {
items: ShippingOrderReviewCaseSummary[];
}
export interface ShippingOrderReviewQueue {
conversation_id?: string | null;
summary: {
total: number;
needs_action: number;
processing: number;
completed: number;
};
items: ShippingOrderReviewCaseSummary[];
}
/** 当前复核 Case 的受控接收解析上下文;附件与邮件正文严格按 Case 归属返回。 */
export interface ShippingOrderReviewIntakeParseContext {
case_no: string;
attachment: {
document_id: number;
filename: string;
mime_type: string | null;
preview_kind: 'pdf' | 'unsupported';
};
email: {
document_id: number;
filename: string;
/** 安全 HTML 命中快照时为 safe_html;其它情况降级为 text。 */
render_kind: 'safe_html' | 'text';
/** 后端签发的短时单用途 HTML 预览地址;只能放进 sandbox iframe。 */
preview_url?: string;
text: string;
} | null;
}
/** 当前字段的同 Intake EML 证据预览;HTML 必须在无权限 sandbox iframe 中渲染。 */
export interface ShippingOrderReviewEmailEvidencePreview {
document_id: number;
document_type: 'email_body';
filename: string;
text: string;
render_kind: 'safe_html' | 'text';
preview_url?: string;
highlighted?: boolean;
}
/** 库存路由规则版本摘要(行级投影 / 规则建议内复用)。 */
export interface ShippingOrderReviewInventoryRuleVersion {
rule_id?: number;
@@ -2183,12 +2457,6 @@ export interface ShippingOrderReviewBuildEligibility {
auto_create_failure_reasons?: Array<{ code: string; message: string }>;
}
export interface ShippingOrderReviewInventoryCandidatesWrite {
expected_draft_version: number;
source_codes: string[];
reason: string;
}
/** 整单或行级重新匹配库存路由写请求。 */
export interface ShippingOrderReviewInventoryRoutingRerouteWrite {
expected_draft_version: number;
@@ -2196,13 +2464,6 @@ export interface ShippingOrderReviewInventoryRoutingRerouteWrite {
line_key?: string;
}
/** 采纳规则建议 / 保留人工路由写请求。 */
export interface ShippingOrderReviewInventoryRoutingDecisionWrite {
expected_draft_version: number;
idempotency_key?: string;
reason?: string;
}
/** 建单前客户识别投影(复核工作台固定客户区)。 */
export interface ShippingOrderReviewCustomerResolution {
resolved: boolean;
@@ -2250,6 +2511,8 @@ export interface ShippingOrderReviewFieldConflict {
field_code: string;
line_index?: number | null;
line_key?: string | null;
/** header | line | line_unassigned | unscoped;相同 field_code 在订单头和明细行是不同业务字段。 */
scope?: 'header' | 'line' | 'line_unassigned' | 'unscoped' | string | null;
severity?: string;
reason: string;
options: ShippingOrderReviewFieldConflictOption[];
@@ -2280,6 +2543,8 @@ export interface ShippingOrderReviewCase {
customer_resolution?: ShippingOrderReviewCustomerResolution | null;
/** 建单前字段冲突;有开放项时工作台侧栏展示裁决区 */
field_conflicts?: ShippingOrderReviewFieldConflict[] | null;
/** 关键字段证据缺失;与多来源取值冲突分区展示,不提供重复填值入口。 */
evidence_issues?: ShippingOrderReviewFieldConflict[] | null;
/** 建单前重复检测;needs_adjudication 时侧栏展示裁决区 */
duplicate?: ShippingOrderReviewDuplicate | null;
/** 建单前文档模板匹配只读摘要 */
@@ -2307,7 +2572,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;
@@ -2341,7 +2605,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;
@@ -2369,11 +2632,6 @@ export interface ShippingOrderReviewCase {
build_eligibility?: ShippingOrderReviewBuildEligibility;
} | null;
available_actions: string[];
/** 对话级可执行动作(与对话处理 GET 同源);仅 retryable 对象计入。 */
conversation_allowed_actions?: Array<{
code: string;
eligible_count: number;
}>;
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
formal_editable_field_ids?: string[];
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
@@ -2480,6 +2738,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;
@@ -2600,7 +2861,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[];
@@ -2635,7 +2895,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[];
@@ -2778,6 +3037,7 @@ export interface ShippingOrderReviewLineFulfillmentDecision {
line_status?: string;
is_active?: boolean;
reason?: string | null;
release_field_values?: Record<string, string>;
required_qty?: string | null;
available_qty?: string | null;
reservation_id?: string | null;
@@ -2794,7 +3054,8 @@ export type ShippingOrderReviewLineFulfillmentDecisionCode =
| 'close_unfulfillable'
| 'reopen'
| 'use_new_inventory_file'
| 'change_inventory_source';
| 'change_inventory_source'
| 'release_inventory_shortage';
/** 行级履约与库存缺口投影行(含 OT 匹配事实与 allowed_actions)。 */
export interface ShippingOrderReviewLineFulfillmentLine {
@@ -2840,6 +3101,18 @@ export interface ShippingOrderReviewLineFulfillmentLine {
inventory_allowed_actions?: string[];
line_allowed_actions?: string[];
auto_fulfill_error_message?: string | null;
/** 短缺放行前必须人工确认的模板实际消费字段(含 Header/Line 库存字段与系统事实)。 */
release_required_fields?: Array<{ field_id: string; display_name: string }>;
/** 发货模板实际消费字段;唯一受控快照或任务事实只读,其他项要求人工补录。 */
release_template_fields?: Array<{
field_id: string;
display_name: string;
value?: string | null;
value_source?: 'inventory_snapshot' | 'manual_required' | string;
requires_manual?: boolean;
}>;
/** 字段无法受控解析时的稳定错误码;UI 必须隐藏放行入口。 */
release_field_resolution_error?: string | null;
decision?: ShippingOrderReviewLineFulfillmentDecision | null;
block_reason?: string | null;
}
@@ -9,7 +9,7 @@ import type { ShippingFieldAdjudication, ShippingOrderCustomerMatch } from './sh
export type ShippingActionVariant = 'primary' | 'secondary' | 'danger';
export type ShippingMenuAction = 'upload' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject';
export type ShippingMenuAction = 'retry_rpa' | 'confirm' | 'reparse' | 'reject';
export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
@@ -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 {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff