feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -9,7 +9,6 @@
|
||||
*/
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
|
||||
import {
|
||||
normalizeShippingProcessingProjection,
|
||||
normalizeShippingProcessingWorkItems,
|
||||
@@ -32,6 +31,7 @@ import type {
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingOrderReviewQueue,
|
||||
ShippingOrderReviewEmailEvidencePreview,
|
||||
ShippingOrderReviewIntakeParseContext,
|
||||
OrderExtractionSubmissionRequest,
|
||||
OrderExtractionSubmissionResponse,
|
||||
@@ -51,8 +51,6 @@ import type {
|
||||
ShippingDuplicateAction,
|
||||
ShippingOrderReviewDraftWrite,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewInventoryCandidatesWrite,
|
||||
ShippingOrderReviewInventoryRoutingDecisionWrite,
|
||||
ShippingOrderReviewInventoryRoutingRerouteWrite,
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
@@ -94,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({
|
||||
@@ -128,11 +104,6 @@ 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?: {
|
||||
lifecycle_status?: string;
|
||||
page?: number;
|
||||
@@ -182,6 +153,10 @@ export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
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', {
|
||||
@@ -379,6 +354,20 @@ 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, uploadBatchId?: string | null) =>
|
||||
requestJson<ShippingOrderExtractionDocumentsResponse>(
|
||||
@@ -455,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 后重跑资格校验。
|
||||
@@ -497,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 当前库存候选版本与历史摘要。
|
||||
*/
|
||||
@@ -536,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)。
|
||||
*/
|
||||
@@ -721,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 二进制继续由受控同源预览接口提供;坐标缺失不影响字段值。
|
||||
@@ -857,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<{
|
||||
@@ -943,10 +843,10 @@ export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Pr
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
/** 读取当前 Case 同 Intake 的已解析邮件正文证据;不暴露原始 EML 或附件。 */
|
||||
export const getWorkspaceShippingOrderReviewEmailEvidencePreview = (caseNo: string, documentId: number) =>
|
||||
requestJson<{ document_id: number; document_type: 'email_body'; filename: string; text: string }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/email-evidence-preview/${documentId}`,
|
||||
/** 读取当前 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 邮件正文;仅在接收解析工作面打开时调用。 */
|
||||
@@ -1030,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' });
|
||||
@@ -1139,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 }
|
||||
@@ -1202,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 - 发货任务编号
|
||||
@@ -1391,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"
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
-87
@@ -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>
|
||||
+31
-3
@@ -18,6 +18,13 @@ const i18n = createI18n({
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
processGate: {
|
||||
actionCodes: {
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
},
|
||||
inventoryActions: {
|
||||
retryInventoryMatching: '重新库存匹配',
|
||||
retryInventoryPreparation: '重新获取库存',
|
||||
},
|
||||
reasons: {
|
||||
inventory_shortage_review_required: '存在库存缺口,需要人工处理',
|
||||
},
|
||||
@@ -171,7 +178,7 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
expect(nextStep).not.toContain('inventory_shortage_review_required');
|
||||
});
|
||||
|
||||
it('renders server-provided recovery actions without duplicating the primary action', async () => {
|
||||
it('hides internal inventory recovery targets while retaining the stable primary action', async () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_matching',
|
||||
@@ -185,7 +192,28 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
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', {}],
|
||||
]);
|
||||
});
|
||||
});
|
||||
+13
-18
@@ -8,7 +8,7 @@
|
||||
-->
|
||||
<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,
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
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;
|
||||
@@ -51,8 +52,6 @@ const props = defineProps<{
|
||||
showAdminDiagnosis?: boolean;
|
||||
retrying?: boolean;
|
||||
locating?: boolean;
|
||||
/** 题7A:自动次数已耗尽但允许人工继续的源;不为空时按钮语义提示「人工继续」+ tooltip 列名。 */
|
||||
retryExhaustedSources?: string[] | null;
|
||||
/** 仅 UI 展示的 running 文案(如 inventory_preparation 正在跑时主卡按钮 loading 附加信息)。 */
|
||||
automation?: {
|
||||
status?: string | null;
|
||||
@@ -231,6 +230,7 @@ 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;
|
||||
@@ -240,12 +240,10 @@ const showBusinessAction = computed(() => {
|
||||
});
|
||||
|
||||
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 '';
|
||||
@@ -268,14 +266,7 @@ const businessActionLabel = computed(() => {
|
||||
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');
|
||||
@@ -284,9 +275,10 @@ 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();
|
||||
if (!code || isNonTaskCapabilityAction(code)) return false;
|
||||
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
|
||||
if (code === String(props.primaryAction?.code || '').trim()) return false;
|
||||
const key = String(
|
||||
action.i18nKey
|
||||
@@ -297,6 +289,8 @@ const recoveryActions = computed(() => (props.recoveryActions || []).filter((act
|
||||
}));
|
||||
|
||||
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
|
||||
@@ -445,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) }"
|
||||
/>
|
||||
|
||||
+15
@@ -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);
|
||||
|
||||
+11
-2
@@ -44,7 +44,7 @@ const props = defineProps<{
|
||||
docked: boolean;
|
||||
floatSide: 'right' | 'left';
|
||||
src: string;
|
||||
emailPreview?: { document_id: number; filename: string; text: string } | null;
|
||||
emailPreview?: { document_id: number; filename: string; text: string; render_kind: 'safe_html' | 'text'; preview_url?: string } | null;
|
||||
evidence: ShippingOrderReviewEvidence | null;
|
||||
evidenceList: ShippingOrderReviewEvidence[];
|
||||
fieldLabel?: string;
|
||||
@@ -730,7 +730,16 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
|
||||
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
|
||||
<div v-if="emailPreview" class="min-h-0 overflow-auto whitespace-pre-wrap p-4 font-mono text-xs leading-6 text-slate-700 dark:text-slate-200" data-testid="review-email-evidence-preview">
|
||||
<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
|
||||
|
||||
+3
-2
@@ -104,11 +104,12 @@ describe('ReviewDocumentNavigation', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:生命周期四阶段兼容不能改变既有的强制侧栏与编号折叠轨交互。
|
||||
// 关键断言:收起后仍保留文件身份摘要,不能退化成无法识别的纯编号轨。
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
|
||||
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('2');
|
||||
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', () => {
|
||||
|
||||
@@ -48,6 +48,7 @@ const props = defineProps<{
|
||||
const emit = defineEmits<{
|
||||
select: [caseNo: string];
|
||||
'mode-change': [mode: ReviewDocumentNavMode];
|
||||
'collapse-change': [collapsed: boolean];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -93,6 +94,7 @@ const mode = computed<ReviewDocumentNavMode>(() => {
|
||||
});
|
||||
|
||||
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);
|
||||
@@ -181,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
|
||||
@@ -244,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
|
||||
@@ -287,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)"
|
||||
@@ -304,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
|
||||
|
||||
+19
@@ -26,6 +26,8 @@ const i18n = createI18n({
|
||||
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: '字段冲突' },
|
||||
@@ -38,6 +40,23 @@ const i18n = createI18n({
|
||||
});
|
||||
|
||||
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',
|
||||
|
||||
@@ -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 / 辅助 / 邮件正文)。
|
||||
*/
|
||||
@@ -170,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 }) }}
|
||||
@@ -276,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>
|
||||
+37
-26
@@ -36,7 +36,6 @@ const i18n = createI18n({
|
||||
markNonOrder: '标记为非订单',
|
||||
markQualityIssue: '文件质量异常',
|
||||
reparse: '重新识别此 PDF',
|
||||
uploadReplacement: '上传替代 PDF',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -54,6 +53,7 @@ const emailPdfContext: ShippingOrderReviewIntakeParseContext = {
|
||||
email: {
|
||||
document_id: 7,
|
||||
filename: 'source.eml',
|
||||
render_kind: 'text',
|
||||
text: 'approved body text',
|
||||
},
|
||||
};
|
||||
@@ -76,11 +76,6 @@ function mountPanel(props: Record<string, unknown>) {
|
||||
loadFailed: false,
|
||||
previewUrl: null,
|
||||
previewLoading: false,
|
||||
saving: false,
|
||||
canMarkNonOrder: false,
|
||||
canMarkQualityIssue: false,
|
||||
canReparse: false,
|
||||
canUploadReplacement: false,
|
||||
...props,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
@@ -96,6 +91,35 @@ describe('ReviewIntakeParsePanel', () => {
|
||||
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 });
|
||||
|
||||
@@ -105,35 +129,22 @@ describe('ReviewIntakeParsePanel', () => {
|
||||
expect(wrapper.get('[data-testid="intake-parse-no-email"]').text()).toContain('无邮件上下文');
|
||||
});
|
||||
|
||||
it('emits parse disposition intent without executing Case commands', async () => {
|
||||
it('does not render parse disposition controls inside the scrolling intake panel', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: emailPdfContext,
|
||||
canMarkNonOrder: true,
|
||||
canMarkQualityIssue: true,
|
||||
canReparse: true,
|
||||
canUploadReplacement: true,
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="intake-parse-mark-non-order"]').trigger('click');
|
||||
await wrapper.get('[data-testid="intake-parse-mark-quality-issue"]').trigger('click');
|
||||
await wrapper.get('[data-testid="intake-parse-reparse"]').trigger('click');
|
||||
await wrapper.get('[data-testid="intake-parse-upload-replacement"] input').trigger('change');
|
||||
|
||||
expect(wrapper.emitted('mark-non-order')).toHaveLength(1);
|
||||
expect(wrapper.emitted('mark-quality-issue')).toHaveLength(1);
|
||||
expect(wrapper.emitted('reparse')).toHaveLength(1);
|
||||
expect(wrapper.emitted('upload-replacement')).toHaveLength(1);
|
||||
// 关键断言:按钮由父级固定底栏统一承载,面板滚动时不得随内容离开视口。
|
||||
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 infer replacement permission from another disposition permission', () => {
|
||||
it('does not render deprecated parse disposition controls inside the scrolling panel', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: emailPdfContext,
|
||||
canMarkQualityIssue: true,
|
||||
canUploadReplacement: false,
|
||||
});
|
||||
|
||||
// 关键断言:父级必须显式授予替代上传,不能因质量异常动作可用而显示上传入口。
|
||||
expect(wrapper.get('[data-testid="intake-parse-mark-quality-issue"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="intake-parse-upload-replacement"]').exists()).toBe(false);
|
||||
// 关键断言:处置由固定底栏承载,滚动内容区不得遗留重复入口。
|
||||
expect(wrapper.find('[data-testid="intake-parse-reparse"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -16,20 +16,11 @@ const props = defineProps<{
|
||||
loadFailed: boolean;
|
||||
previewUrl: string | null;
|
||||
previewLoading: boolean;
|
||||
saving: boolean;
|
||||
canMarkNonOrder: boolean;
|
||||
canMarkQualityIssue: boolean;
|
||||
canReparse: boolean;
|
||||
canUploadReplacement: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'retry-context': [];
|
||||
'load-preview': [];
|
||||
'mark-non-order': [];
|
||||
'mark-quality-issue': [];
|
||||
reparse: [];
|
||||
'upload-replacement': [event: Event];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -83,7 +74,17 @@ watch(
|
||||
<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>
|
||||
@@ -98,24 +99,16 @@ watch(
|
||||
</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">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.attachment') }}</h2>
|
||||
<dl class="mt-3 grid gap-2 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="text-xs text-slate-500">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.fileName') }}</dt>
|
||||
<dd class="mt-0.5 break-all">{{ context.attachment.filename }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-slate-500">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.fileType') }}</dt>
|
||||
<dd class="mt-0.5 break-all">{{ context.attachment.mime_type || '-' }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<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-4"
|
||||
class="mt-3"
|
||||
data-testid="intake-parse-attachment-preview"
|
||||
>
|
||||
<h3 class="text-xs font-medium text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.preview') }}</h3>
|
||||
<p
|
||||
v-if="previewLoading"
|
||||
class="mt-2 text-sm text-slate-500"
|
||||
@@ -148,53 +141,6 @@ watch(
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div class="flex flex-wrap gap-2" data-testid="intake-parse-disposition-actions">
|
||||
<button
|
||||
v-if="canMarkNonOrder"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300"
|
||||
data-testid="intake-parse-mark-non-order"
|
||||
@click="emit('mark-non-order')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.markNonOrder') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canMarkQualityIssue"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200"
|
||||
data-testid="intake-parse-mark-quality-issue"
|
||||
@click="emit('mark-quality-issue')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.markQualityIssue') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canReparse"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300"
|
||||
data-testid="intake-parse-reparse"
|
||||
@click="emit('reparse')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.reparse') }}
|
||||
</button>
|
||||
<label
|
||||
v-if="canUploadReplacement"
|
||||
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300"
|
||||
:class="saving ? 'pointer-events-none opacity-50' : ''"
|
||||
data-testid="intake-parse-upload-replacement"
|
||||
>
|
||||
<input
|
||||
class="sr-only"
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
:disabled="saving"
|
||||
@change="emit('upload-replacement', $event)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.uploadReplacement') }}
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
+6
-13
@@ -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);
|
||||
});
|
||||
});
|
||||
+3
-194
@@ -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>
|
||||
|
||||
+2
-1
@@ -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>
|
||||
+12
-2
@@ -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>
|
||||
|
||||
@@ -24,6 +24,24 @@ const i18n = createI18n({
|
||||
});
|
||||
|
||||
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: {
|
||||
|
||||
@@ -38,6 +38,8 @@ const props = withDefaults(defineProps<{
|
||||
flowBusy?: boolean;
|
||||
/** 解析处置入口由接收解析工作面承载时,订单复核底栏隐藏四项解析操作。 */
|
||||
showParseDispositions?: boolean;
|
||||
/** 保存并校验只属于订单复核表单,接收解析阶段必须隐藏。 */
|
||||
showValidate?: boolean;
|
||||
}>(), {
|
||||
unsavedCount: 0,
|
||||
flowPresentation: null,
|
||||
@@ -49,13 +51,13 @@ const props = withDefaults(defineProps<{
|
||||
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': [];
|
||||
@@ -130,20 +132,6 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
|
||||
</button>
|
||||
<label
|
||||
v-if="showParseDispositions && 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
|
||||
@@ -184,7 +172,7 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
|
||||
</p>
|
||||
<template v-if="!automating && canWriteCaseActions">
|
||||
<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"
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
<!--
|
||||
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<{
|
||||
@@ -21,28 +19,15 @@ const props = defineProps<{
|
||||
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 showRetry = computed(() => (
|
||||
Boolean(props.showConversationRetry)
|
||||
&& Number(props.conversationRetryEligibleCount || 0) > 0
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -63,34 +48,6 @@ const showRetry = computed(() => (
|
||||
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"
|
||||
|
||||
+24
-10
@@ -94,7 +94,7 @@ type WorkbenchFileRow = {
|
||||
po_number?: string | null;
|
||||
projection?: ShippingProcessingProjection;
|
||||
};
|
||||
const LIFECYCLE_STAGE_CODES = ['order_review', 'fulfillment_prep', 'upload_complete'] as const;
|
||||
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',
|
||||
@@ -479,14 +479,9 @@ function lifecycleEntryState(file: WorkbenchFileRow, target: LifecycleStageCode)
|
||||
}
|
||||
|
||||
function lifecycleEntryLabel(file: WorkbenchFileRow, target: LifecycleStageCode): string {
|
||||
const stage = t(`chat.shippingNoticeUi.stage.${LIFECYCLE_STAGE_LABEL_KEYS[target]}`);
|
||||
const state = lifecycleEntryState(file, target);
|
||||
const stateKey = state === 'current'
|
||||
? 'chat.shippingOrderReview.lifecycle.current'
|
||||
: state === 'available'
|
||||
? 'chat.shippingOrderReview.lifecycle.available'
|
||||
: 'chat.shippingOrderReview.lifecycle.blocked';
|
||||
return `${stage} · ${t(stateKey)}`;
|
||||
void file;
|
||||
// 阶段状态由按钮颜色和 disabled 表达,避免重复的“当前可处理/前置未完成”文案挤占文件行。
|
||||
return t(`chat.shippingNoticeUi.stage.${LIFECYCLE_STAGE_LABEL_KEYS[target]}`);
|
||||
}
|
||||
|
||||
function onOpenLifecycleStage(file: WorkbenchFileRow, lifecycleStage: LifecycleStageCode) {
|
||||
@@ -591,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(实心按钮);处理记录只读卡不调用。
|
||||
*/
|
||||
@@ -875,8 +880,17 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
v-if="visibleWaitingHumanTasks.length"
|
||||
data-testid="shipping-processing-group-waiting_human"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
<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
|
||||
|
||||
@@ -149,6 +149,46 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
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',
|
||||
|
||||
@@ -257,6 +257,25 @@ 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'
|
||||
@@ -310,6 +329,9 @@ const processedCount = computed(() => {
|
||||
// “处理过”口径累计为完成,否则会与批次进度中心的 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);
|
||||
});
|
||||
@@ -324,6 +346,7 @@ 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));
|
||||
});
|
||||
|
||||
@@ -453,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,
|
||||
|
||||
@@ -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') }}
|
||||
|
||||
@@ -25,14 +25,18 @@ vi.mock('vue-router', () => ({
|
||||
const api = vi.hoisted(() => ({
|
||||
cancelRun: vi.fn(async () => ({})),
|
||||
cancelDocument: vi.fn(async () => ({})),
|
||||
reparseCase: vi.fn(async () => ({})),
|
||||
reparseRun: vi.fn(async () => ({})),
|
||||
reparseBatch: vi.fn(async () => ({ created: [], excluded: [] })),
|
||||
retryRun: vi.fn(async () => ({})),
|
||||
retryIntake: vi.fn(async () => ({})),
|
||||
}));
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
cancelWorkspaceShippingOrderExtractionRun: api.cancelRun,
|
||||
cancelWorkspaceShippingOrderExtractionDocument: api.cancelDocument,
|
||||
reparseWorkspaceShippingOrderReviewDocument: api.reparseCase,
|
||||
reparseWorkspaceShippingOrderExtractionRun: api.reparseRun,
|
||||
reparseWorkspaceShippingOrderExtractionBatch: api.reparseBatch,
|
||||
retryWorkspaceShippingOrderExtractionRun: api.retryRun,
|
||||
retryShippingNoticeIntake: api.retryIntake,
|
||||
}));
|
||||
@@ -107,6 +111,9 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
document.body.innerHTML = '';
|
||||
routerPush.mockClear();
|
||||
api.cancelDocument.mockClear();
|
||||
api.reparseCase.mockClear();
|
||||
api.reparseRun.mockClear();
|
||||
api.reparseBatch.mockClear();
|
||||
});
|
||||
|
||||
it('renders backend-owned four-stage summaries and the authorized download toolbar', async () => {
|
||||
@@ -266,7 +273,7 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it('opens the reparse confirmation for a file action without requiring a parent task-number match', async () => {
|
||||
it('executes a file reparse only through the backend-projected Case', async () => {
|
||||
const file = fileProjection({
|
||||
uiState: {
|
||||
status: 'failed', stage: 'document_parsing', lifecycleStage: 'intake_parse',
|
||||
@@ -283,8 +290,139 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// DOCUMENT:<id> 不会匹配 OT 父任务号;已授权的叶子 Run 仍必须能打开重识别确认。
|
||||
// DOCUMENT:<id> 不会匹配 OT 父任务号;已授权叶子只能使用其后端投影 Case。
|
||||
expect(document.querySelector('[data-testid="shipping-workflow-reason-dialog"]')).not.toBeNull();
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
if (input) {
|
||||
input.value = 'field_mapping_error';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
document.querySelector<HTMLElement>('[data-testid="shipping-workflow-reason-confirm"]')?.click();
|
||||
await flushPromises();
|
||||
expect(api.reparseCase).toHaveBeenCalledWith('CASE-1', 'field_mapping_error', undefined);
|
||||
expect(api.reparseRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses the backend-projected Run only when a failed file has no Review Case', async () => {
|
||||
const file = fileProjection({
|
||||
caseNo: null,
|
||||
uiState: {
|
||||
status: 'failed', stage: 'document_parsing', lifecycleStage: 'intake_parse',
|
||||
lifecycleEntries: [], blocking_reason: null,
|
||||
primary_action: { code: 'reparse', i18nKey: null, parameters: {} }, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountTimeline(processingProjection(), [file]);
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'retry', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
});
|
||||
await flushPromises();
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
if (input) {
|
||||
input.value = 'document_quality';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
document.querySelector<HTMLElement>('[data-testid="shipping-workflow-reason-confirm"]')?.click();
|
||||
await flushPromises();
|
||||
|
||||
expect(api.reparseRun).toHaveBeenCalledWith('RUN-1', {
|
||||
reason: 'document_quality', comment: undefined,
|
||||
});
|
||||
expect(api.reparseCase).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps batch reparse available in order review and submits the dedicated batch command', async () => {
|
||||
const file = fileProjection({
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'waiting_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [], blocking_reason: null,
|
||||
primary_action: { code: 'reparse_batch', i18nKey: null, parameters: {} }, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountTimeline(processingProjection(), [file]);
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'reparse_batch', actionCode: 'reparse_batch', labelKey: 'chat.shippingProcessing.action.reparse_batch' },
|
||||
});
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
if (input) {
|
||||
input.value = 'rule_updated';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
document.querySelector<HTMLElement>('[data-testid="shipping-workflow-reason-confirm"]')?.click();
|
||||
await flushPromises();
|
||||
|
||||
expect(api.reparseBatch).toHaveBeenCalledWith('RUN-1', {
|
||||
reason: 'rule_updated', comment: undefined,
|
||||
});
|
||||
expect(api.reparseCase).not.toHaveBeenCalled();
|
||||
expect(api.reparseRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders the authorized batch reparse button beside waiting-human files and submits its Run', async () => {
|
||||
const task = {
|
||||
...processingProjection().processing[0],
|
||||
group: 'needs_action',
|
||||
userStatus: 'waiting_human',
|
||||
available_actions: ['reparse_batch'],
|
||||
primary_action: 'reparse_batch',
|
||||
};
|
||||
const processing = processingProjection({
|
||||
needs_action: [task],
|
||||
processing: [],
|
||||
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection({
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'waiting_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
})]);
|
||||
await flushPromises();
|
||||
|
||||
const batchButton = wrapper.get('[data-testid="shipping-processing-batch-reparse"]');
|
||||
expect(batchButton.text()).toBe('重新解析本批次');
|
||||
await batchButton.trigger('click');
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
if (input) {
|
||||
input.value = 'rule_updated';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
document.querySelector<HTMLElement>('[data-testid="shipping-workflow-reason-confirm"]')?.click();
|
||||
await flushPromises();
|
||||
|
||||
expect(api.reparseBatch).toHaveBeenCalledWith('RUN-1', {
|
||||
reason: 'rule_updated', comment: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not render batch reparse when authorization exists outside waiting-human files', async () => {
|
||||
const task = {
|
||||
...processingProjection().processing[0],
|
||||
group: 'processing',
|
||||
userStatus: 'processing',
|
||||
available_actions: ['reparse_batch'],
|
||||
primary_action: 'reparse_batch',
|
||||
};
|
||||
const processing = processingProjection({
|
||||
needs_action: [],
|
||||
processing: [task],
|
||||
status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] },
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection({
|
||||
uiState: {
|
||||
status: 'processing', stage: 'document_parsing', lifecycleStage: 'intake_parse',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
})]);
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-processing-batch-reparse"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('retries a file generic-retry action by its backend run instead of silently treating it as intake retry', async () => {
|
||||
|
||||
@@ -26,7 +26,9 @@ import { useShippingProcessGateRecovery } from '@/features/shipping-process-gate
|
||||
import {
|
||||
cancelWorkspaceShippingOrderExtractionRun,
|
||||
cancelWorkspaceShippingOrderExtractionDocument,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
reparseWorkspaceShippingOrderExtractionRun,
|
||||
reparseWorkspaceShippingOrderExtractionBatch,
|
||||
retryWorkspaceShippingOrderExtractionRun,
|
||||
retryShippingNoticeIntake,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
@@ -100,6 +102,8 @@ const reasonDialogOpen = ref(false);
|
||||
const reasonDialogAction = ref<ShippingWorkflowReasonAction>('cancel');
|
||||
/** 任务级取消:走 Run API,不绑单个 WorkflowItem。 */
|
||||
const reasonDialogRunNo = ref<string | null>(null);
|
||||
/** 文件叶子重解析只能绑定后端已裁决的 Review Case;不得由前端按状态推导。 */
|
||||
const reasonDialogCaseNo = ref<string | null>(null);
|
||||
/** 单文件取消:仅由后端 cancel_unit 授权的 document_id 赋值。 */
|
||||
const reasonDialogDocumentId = ref<number | null>(null);
|
||||
const processingWorkItems = computed((): ShippingProcessingProjection[] => (
|
||||
@@ -477,6 +481,14 @@ async function onProcessingTaskAction(payload: {
|
||||
openReparseRunDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (action === 'reparse_batch') {
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
return;
|
||||
}
|
||||
openReparseBatchDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (action === 'retry_parse' || action === 'retry') {
|
||||
const intakeNo = String(task.user_task_no || '').replace(/^INTAKE:/i, '').trim();
|
||||
if (intakeNo.startsWith('SNI-')) {
|
||||
@@ -550,10 +562,29 @@ function openCancelRunDialog(runNo: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开重识别原因弹窗:走 Run 级 reparse API。
|
||||
* 打开批次重解析原因弹窗:服务端按 PDF 预检并创建独立子 Run。
|
||||
*/
|
||||
function openReparseBatchDialog(runNo: string) {
|
||||
reasonDialogRunNo.value = String(runNo || '').trim() || null;
|
||||
reasonDialogCaseNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
reasonDialogAction.value = 'reparse_batch';
|
||||
reasonDialogOpen.value = true;
|
||||
}
|
||||
|
||||
/** 打开 Run 级重解析原因弹窗:仅重建当前 Run 的一个后继版本,不展开批次。 */
|
||||
function openReparseRunDialog(runNo: string) {
|
||||
reasonDialogRunNo.value = String(runNo || '').trim() || null;
|
||||
reasonDialogCaseNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
reasonDialogAction.value = 'reparse';
|
||||
reasonDialogOpen.value = true;
|
||||
}
|
||||
|
||||
/** 打开 Case 级重解析原因弹窗;该 Case 必须来自文件叶子的后端 Projection。 */
|
||||
function openReparseCaseDialog(caseNo: string) {
|
||||
reasonDialogCaseNo.value = String(caseNo || '').trim() || null;
|
||||
reasonDialogRunNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
reasonDialogAction.value = 'reparse';
|
||||
reasonDialogOpen.value = true;
|
||||
@@ -614,11 +645,12 @@ function reparseErrorMessage(error: unknown): { title: string; message: string }
|
||||
*/
|
||||
async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
const runNo = String(reasonDialogRunNo.value || '').trim();
|
||||
const caseNo = String(reasonDialogCaseNo.value || '').trim();
|
||||
const documentId = reasonDialogDocumentId.value;
|
||||
if (!runNo || actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = runNo;
|
||||
if ((!runNo && !caseNo) || actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = caseNo || runNo;
|
||||
try {
|
||||
if (reasonDialogAction.value === 'reparse') {
|
||||
if (reasonDialogAction.value === 'reparse' || reasonDialogAction.value === 'reparse_batch') {
|
||||
const allowed = new Set(['rule_updated', 'field_mapping_error', 'document_quality', 'other']);
|
||||
const normalizedReason = allowed.has(payload.reason)
|
||||
? payload.reason as 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other'
|
||||
@@ -626,10 +658,19 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
const comment = normalizedReason === 'other'
|
||||
? [payload.reason, payload.comment].filter(Boolean).join(' — ') || undefined
|
||||
: payload.comment;
|
||||
await reparseWorkspaceShippingOrderExtractionRun(runNo, {
|
||||
reason: normalizedReason,
|
||||
comment,
|
||||
});
|
||||
if (caseNo) {
|
||||
await reparseWorkspaceShippingOrderReviewDocument(caseNo, normalizedReason, comment);
|
||||
} else if (reasonDialogAction.value === 'reparse_batch') {
|
||||
await reparseWorkspaceShippingOrderExtractionBatch(runNo, {
|
||||
reason: normalizedReason,
|
||||
comment,
|
||||
});
|
||||
} else {
|
||||
await reparseWorkspaceShippingOrderExtractionRun(runNo, {
|
||||
reason: normalizedReason,
|
||||
comment,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (documentId && documentId > 0) {
|
||||
await cancelWorkspaceShippingOrderExtractionDocument(runNo, documentId, { reason: payload.reason });
|
||||
@@ -640,11 +681,13 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
await ctl.value.refresh();
|
||||
reasonDialogOpen.value = false;
|
||||
reasonDialogRunNo.value = null;
|
||||
reasonDialogCaseNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
} catch (err) {
|
||||
// 失败时关闭原因确认框,避免与错误提示双遮罩。
|
||||
reasonDialogOpen.value = false;
|
||||
reasonDialogRunNo.value = null;
|
||||
reasonDialogCaseNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
msg.error(reparseErrorMessage(err));
|
||||
} finally {
|
||||
@@ -706,7 +749,13 @@ async function onTaskProjectionAction(payload: {
|
||||
void onProcessingTaskAction({ task, action: 'reparse' });
|
||||
return;
|
||||
}
|
||||
// 文件叶子没有父任务同名 workItemNo;仅使用后端下发的当前 Run,不反推任务或阶段。
|
||||
// 文件叶子的重解析目标由后端投影明确给出:有 Case 走 Case API;无 Case 的
|
||||
// 失败文件只能使用该叶子下发的 Run API。禁止从状态、文件名或阶段反推目标。
|
||||
const caseNo = String(projection.caseNo || '').trim();
|
||||
if (caseNo) {
|
||||
openReparseCaseDialog(caseNo);
|
||||
return;
|
||||
}
|
||||
const runNo = String(projection.runNo || '').trim();
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
@@ -715,6 +764,15 @@ async function onTaskProjectionAction(payload: {
|
||||
openReparseRunDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (code === 'reparse_batch') {
|
||||
const runNo = String(projection.runNo || '').trim();
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
return;
|
||||
}
|
||||
openReparseBatchDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (code === 'retry_inventory_preparation') {
|
||||
const gateSummary = projection.processGate;
|
||||
if (!gateSummary) {
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -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,
|
||||
@@ -55,10 +52,7 @@ const api = vi.hoisted(() => ({
|
||||
|
||||
reparseDocument: vi.fn(),
|
||||
|
||||
putInventoryCandidates: vi.fn(),
|
||||
rerouteInventoryRouting: vi.fn(),
|
||||
adoptInventoryRoutingSuggestion: vi.fn(),
|
||||
keepManualInventoryRouting: vi.fn(),
|
||||
|
||||
confirmCase: vi.fn(),
|
||||
|
||||
@@ -89,10 +83,7 @@ vi.mock('../api/shipping.api', () => ({
|
||||
getWorkspaceShippingOrderExtractionRun: api.getExtractionRun,
|
||||
getWorkspaceShippingProcessingWorkItem: api.getProcessingWorkItem,
|
||||
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates: api.putInventoryCandidates,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingReroute: api.rerouteInventoryRouting,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion: api.adoptInventoryRoutingSuggestion,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual: api.keepManualInventoryRouting,
|
||||
|
||||
confirmWorkspaceShippingOrderReviewCase: api.confirmCase,
|
||||
|
||||
@@ -345,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);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
@@ -429,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();
|
||||
|
||||
@@ -439,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');
|
||||
|
||||
});
|
||||
|
||||
@@ -709,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();
|
||||
@@ -866,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 = {
|
||||
@@ -881,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,
|
||||
@@ -894,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();
|
||||
@@ -919,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,
|
||||
@@ -952,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 () => ({
|
||||
@@ -965,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({
|
||||
@@ -987,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: {} },
|
||||
@@ -1016,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',
|
||||
@@ -1029,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,
|
||||
@@ -1096,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();
|
||||
});
|
||||
|
||||
@@ -1132,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!,
|
||||
@@ -1159,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',
|
||||
@@ -1170,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');
|
||||
});
|
||||
@@ -1193,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,15 +5,13 @@
|
||||
* 逻辑:按 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,
|
||||
@@ -22,7 +20,6 @@ import {
|
||||
getWorkspaceShippingOrderReviewIntakeParseContext,
|
||||
getWorkspaceShippingOrderReviewPreview,
|
||||
getWorkspaceShippingOrderReviewEmailEvidencePreview,
|
||||
getShippingNoticeIntake,
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
getWorkspaceShippingOrderReviewQueue,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
@@ -32,9 +29,6 @@ import {
|
||||
updateWorkspaceShippingNoticeLine,
|
||||
markWorkspaceShippingOrderReviewNonOrder,
|
||||
markWorkspaceShippingOrderReviewQualityIssue,
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingReroute,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
validateWorkspaceShippingOrderReviewDraft,
|
||||
@@ -55,11 +49,11 @@ import type {
|
||||
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';
|
||||
|
||||
/** ???????????? */
|
||||
@@ -77,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;
|
||||
@@ -184,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 ??????????????
|
||||
@@ -211,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());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -392,7 +357,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const previewCaseNo = ref<string | null>(null);
|
||||
const previewLoading = ref(false);
|
||||
const previewLoadFailed = ref(false);
|
||||
const emailPreview = ref<{ document_id: number; document_type: 'email_body'; filename: string; text: string } | null>(null);
|
||||
const emailPreview = ref<ShippingOrderReviewEmailEvidencePreview | null>(null);
|
||||
/** 接收解析工作面专用上下文;切换 Case 或重新加载时必须立即清空,禁止串附件/EML。 */
|
||||
const intakeParseContext = ref<ShippingOrderReviewIntakeParseContext | null>(null);
|
||||
const intakeParseLoading = ref(false);
|
||||
@@ -413,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 快照。
|
||||
@@ -464,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,
|
||||
@@ -505,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;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -627,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 () => {
|
||||
@@ -643,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;
|
||||
@@ -675,7 +530,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
if (getCurrentInstance()) {
|
||||
onBeforeUnmount(() => {
|
||||
stopWorkflowProgressPolling();
|
||||
stopReparseProgressPolling();
|
||||
stopReparseCaseRefreshPolling();
|
||||
stopShippingProcessing();
|
||||
clearPreview();
|
||||
});
|
||||
@@ -692,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 ???????
|
||||
@@ -747,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;
|
||||
@@ -781,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),
|
||||
@@ -831,6 +674,42 @@ 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?????????
|
||||
*/
|
||||
@@ -904,9 +783,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
};
|
||||
|
||||
/** 按当前证据 Document 读取邮件正文;PDF 证据仍使用受控 PDF Blob。 */
|
||||
const ensureEmailEvidenceLoaded = async (caseNo: string, documentId: number): Promise<boolean> => {
|
||||
const ensureEmailEvidenceLoaded = async (caseNo: string, documentId: number, evidenceId?: string): Promise<boolean> => {
|
||||
try {
|
||||
emailPreview.value = await getWorkspaceShippingOrderReviewEmailEvidencePreview(caseNo, documentId);
|
||||
emailPreview.value = await getWorkspaceShippingOrderReviewEmailEvidencePreview(caseNo, documentId, evidenceId);
|
||||
return true;
|
||||
} catch {
|
||||
emailPreview.value = null;
|
||||
@@ -997,12 +876,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
]);
|
||||
reviewRun.value = run;
|
||||
reviewQueue.value = queue;
|
||||
// ? 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;
|
||||
// [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 : [];
|
||||
@@ -1010,16 +885,6 @@ 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;
|
||||
@@ -1338,21 +1203,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* ????????????????? 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
|
||||
@@ -1367,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;
|
||||
@@ -1490,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;
|
||||
@@ -1499,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 ?????????
|
||||
*/
|
||||
@@ -1618,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,
|
||||
@@ -1685,7 +1438,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
draftConflictDiffLines,
|
||||
buildEligibility,
|
||||
canConfirmBuild,
|
||||
manualInventoryLines,
|
||||
routingRecoveryLines,
|
||||
isViewingHistoricalVersion,
|
||||
isWorkItemClosed,
|
||||
@@ -1714,16 +1466,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
clearPreview,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
reparseProgressActive,
|
||||
reparseProgressPolling,
|
||||
reparseProgressRefreshFailed,
|
||||
reparseProgressStage,
|
||||
reparseLastStableStage,
|
||||
reparseRunStatus,
|
||||
reparseLastActivityAt,
|
||||
reparseLastRefreshedAt,
|
||||
reparseStalePolls,
|
||||
refreshReparseProgress,
|
||||
loading,
|
||||
loadFailed,
|
||||
caseSwitchLoading,
|
||||
@@ -1747,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,
|
||||
|
||||
@@ -299,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',
|
||||
@@ -1318,7 +1317,6 @@ export function projectConversationProcessingFromWorkItems(
|
||||
primaryAction: userPrimaryAction,
|
||||
facts: userFacts,
|
||||
userGroup: item.userGroup ?? null,
|
||||
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
|
||||
userCurrentGateCode: item.userCurrentGateCode ?? null,
|
||||
legacyStatus: item.legacyStatus ?? null,
|
||||
legacyStage: item.legacyStage ?? null,
|
||||
|
||||
@@ -83,7 +83,7 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized!.sourceSummary.documentId).toBe(17);
|
||||
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
|
||||
expect(normalized!.availableActions).toEqual(['open_review']);
|
||||
expect(normalized!.uiState).toEqual({
|
||||
expect(normalized!.uiState).toMatchObject({
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'pdf_preferred_critical_conflict', i18nKey: null, details: {} },
|
||||
|
||||
@@ -291,7 +291,7 @@ function normalizeAggregateSummary(
|
||||
|
||||
/**
|
||||
* 题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;
|
||||
@@ -308,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;
|
||||
@@ -348,7 +347,6 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
|
||||
preparedSources,
|
||||
pendingSources,
|
||||
failedSources,
|
||||
exhaustedSources,
|
||||
activeAttemptCount,
|
||||
gateAttemptActive,
|
||||
latestAttempts: Object.keys(latestAttempts).length ? latestAttempts : undefined,
|
||||
@@ -424,14 +422,12 @@ 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),
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
|
||||
workspaceShippingExportUrl,
|
||||
workspaceShippingInventoryFileUrl,
|
||||
workspaceShippingLineInventoryFileUrl,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
@@ -25,6 +26,17 @@ export async function downloadWorkspaceShippingInventoryFile(taskId: string): Pr
|
||||
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) {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -23,7 +23,6 @@ import { normalizeShippingProcessingProjection } from './normalizeShippingProces
|
||||
const DEFAULT_POLL_MS = 3000;
|
||||
const TERMINAL_STATUSES = new Set([
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
]);
|
||||
|
||||
|
||||
@@ -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'
|
||||
@@ -341,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)。 */
|
||||
@@ -352,8 +352,6 @@ 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;
|
||||
/**
|
||||
@@ -387,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),顺序以冻结记录为准。 */
|
||||
@@ -396,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>;
|
||||
}
|
||||
@@ -418,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;
|
||||
@@ -606,7 +602,6 @@ export interface ConversationProcessingUserTask {
|
||||
userStage?: ShippingUserProcessingStage | null;
|
||||
userCurrentGateCode?: string | null;
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
retryable?: boolean;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
facts?: ShippingProcessingFacts;
|
||||
/** EML Intake 的用户可见全局分组;前端只消费,不从附件状态自行推导。 */
|
||||
@@ -763,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 {
|
||||
@@ -786,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>[];
|
||||
@@ -869,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;
|
||||
@@ -1042,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'
|
||||
@@ -1103,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 由后端合同推导,客户端不得提交覆盖。 */
|
||||
@@ -1541,13 +1534,33 @@ export interface ShippingTaskUiState {
|
||||
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?: string | null;
|
||||
target_surface?: ShippingActionTargetSurface | null;
|
||||
target_anchor?: ShippingActionTargetAnchor | null;
|
||||
disabled_reason?: string | null;
|
||||
expected_gate_version?: number | null;
|
||||
}
|
||||
@@ -2163,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;
|
||||
@@ -2223,6 +2238,10 @@ 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;
|
||||
@@ -2269,10 +2288,25 @@ export interface ShippingOrderReviewIntakeParseContext {
|
||||
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;
|
||||
@@ -2423,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;
|
||||
@@ -2436,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;
|
||||
@@ -2490,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[];
|
||||
@@ -2520,6 +2543,8 @@ export interface ShippingOrderReviewCase {
|
||||
customer_resolution?: ShippingOrderReviewCustomerResolution | null;
|
||||
/** 建单前字段冲突;有开放项时工作台侧栏展示裁决区 */
|
||||
field_conflicts?: ShippingOrderReviewFieldConflict[] | null;
|
||||
/** 关键字段证据缺失;与多来源取值冲突分区展示,不提供重复填值入口。 */
|
||||
evidence_issues?: ShippingOrderReviewFieldConflict[] | null;
|
||||
/** 建单前重复检测;needs_adjudication 时侧栏展示裁决区 */
|
||||
duplicate?: ShippingOrderReviewDuplicate | null;
|
||||
/** 建单前文档模板匹配只读摘要 */
|
||||
@@ -2607,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 乐观锁。 */
|
||||
@@ -3017,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;
|
||||
@@ -3033,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 {
|
||||
@@ -3079,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';
|
||||
|
||||
|
||||
@@ -17,16 +17,24 @@ import {
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails,
|
||||
auditWorkspaceShippingOrderReviewVersionHistory,
|
||||
getWorkspaceShippingTask,
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
retryWorkspaceShippingOrderStpAutoCreate,
|
||||
retryWorkspaceShippingTask,
|
||||
retryWorkspaceShippingTaskLine,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const { downloadWorkspaceShippingInventoryFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingInventoryFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
const { downloadWorkspaceShippingLineInventoryFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingLineInventoryFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
const { downloadWorkspaceShippingExcelFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingExcelFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/shipping/shippingDownload', () => ({
|
||||
downloadWorkspaceShippingInventoryFile: downloadWorkspaceShippingInventoryFileMock,
|
||||
downloadWorkspaceShippingLineInventoryFile: downloadWorkspaceShippingLineInventoryFileMock,
|
||||
}));
|
||||
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
|
||||
downloadWorkspaceShippingExcelFile: downloadWorkspaceShippingExcelFileMock,
|
||||
}));
|
||||
|
||||
const focusSuggestionField = vi.fn();
|
||||
@@ -38,6 +46,12 @@ const confirmMock = vi.fn();
|
||||
const reloadLatestDraftMock = vi.fn().mockResolvedValue(undefined);
|
||||
const refreshShippingProcessingMock = vi.fn().mockResolvedValue(undefined);
|
||||
const patchLineMock = vi.fn().mockResolvedValue(undefined);
|
||||
const { submitProcessGatePrimaryActionMock } = vi.hoisted(() => ({
|
||||
submitProcessGatePrimaryActionMock: vi.fn().mockResolvedValue({ outcome: 'submitted' }),
|
||||
}));
|
||||
const { postFormalGateActionMock } = vi.hoisted(() => ({
|
||||
postFormalGateActionMock: vi.fn().mockResolvedValue({}),
|
||||
}));
|
||||
|
||||
const messageMocks = vi.hoisted(() => ({
|
||||
info: vi.fn(),
|
||||
@@ -94,9 +108,13 @@ const workItem = ref<Record<string, any> | null>(null);
|
||||
const reviewProgressContext = ref<Record<string, any> | null>(null);
|
||||
/** 与 activeCase 同源共享,供断言 Progress 优先阶段源。 */
|
||||
const shippingProcessingProjection = ref<Record<string, any> | null>(null);
|
||||
/** 正式任务投影的请求中状态;用于覆盖 Case 先到、Projection 后到的过渡窗口。 */
|
||||
const shippingProcessingLoading = ref(false);
|
||||
const intakeParseContext = ref<Record<string, any> | null>(null);
|
||||
|
||||
const activeCase = ref({
|
||||
/** 每个用例必须从独立的 Case 图快照开始,避免嵌套 schema/draft 被浅拷贝污染。 */
|
||||
function createActiveCaseFixture() {
|
||||
return {
|
||||
case_no: 'CASE-1',
|
||||
document_id: 1,
|
||||
status: 'draft',
|
||||
@@ -140,7 +158,10 @@ const activeCase = ref({
|
||||
process_gate: null,
|
||||
profile_match: { available: false, visibility: 'admin_only', candidates: [] },
|
||||
automation: { status: 'idle', can_auto_create: false, can_build: true },
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const activeCase = ref<Record<string, any>>(createActiveCaseFixture());
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/features/chat/api/shipping.api')>();
|
||||
@@ -149,6 +170,8 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
|
||||
auditWorkspaceShippingOrderReviewVersionHistory: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
|
||||
retryWorkspaceShippingTask: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
retryWorkspaceShippingTaskLine: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
retryWorkspaceShippingOrderStpAutoCreate: vi.fn().mockResolvedValue({
|
||||
status: 'queued',
|
||||
job_id: 901,
|
||||
@@ -254,7 +277,6 @@ function createReviewComposableMock() {
|
||||
markNonOrder: vi.fn(),
|
||||
markQualityIssue: vi.fn(),
|
||||
reparseDocument: vi.fn(),
|
||||
uploadReplacement: vi.fn(),
|
||||
focusSuggestionField,
|
||||
setEvidenceDrawerFocus: vi.fn(),
|
||||
clearEvidenceDrawerFocus: vi.fn(),
|
||||
@@ -268,19 +290,9 @@ function createReviewComposableMock() {
|
||||
showWorkflowProgress: computed(() => false),
|
||||
workflowProgressPolling: computed(() => false),
|
||||
shippingProcessingProjection,
|
||||
shippingProcessingLoading: ref(false),
|
||||
shippingProcessingLoading,
|
||||
shippingProcessingError: ref(null),
|
||||
refreshShippingProcessing: refreshShippingProcessingMock,
|
||||
reparseProgressActive: computed(() => false),
|
||||
reparseProgressPolling: computed(() => false),
|
||||
reparseProgressRefreshFailed: computed(() => false),
|
||||
reparseProgressStage: computed(() => 'submitted'),
|
||||
reparseLastStableStage: computed(() => 'submitted'),
|
||||
reparseRunStatus: computed(() => 'queued'),
|
||||
reparseLastActivityAt: computed(() => null),
|
||||
reparseLastRefreshedAt: computed(() => null),
|
||||
reparseStalePolls: computed(() => 0),
|
||||
refreshReparseProgress: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -290,6 +302,17 @@ vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => messageMocks,
|
||||
}));
|
||||
|
||||
vi.mock('@/features/shipping-process-gates/composables/useShippingProcessGateRecovery', () => ({
|
||||
useShippingProcessGateRecovery: () => ({
|
||||
busy: ref(false),
|
||||
submitPrimaryAction: submitProcessGatePrimaryActionMock,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/shipping-process-gates/api/process-gates.api', () => ({
|
||||
postWorkspaceProcessGateAction: (...args: unknown[]) => postFormalGateActionMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock('../components/shipping-review/ReviewDocumentPreview.vue', () => ({
|
||||
default: {
|
||||
name: 'ReviewDocumentPreview',
|
||||
@@ -422,7 +445,6 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
markNonOrder: '非订单',
|
||||
markQualityIssue: '质量异常',
|
||||
reparse: '重新识别',
|
||||
uploadReplacement: '替换 PDF',
|
||||
saveNow: '保存并校验',
|
||||
saveOrderAndValidate: '保存订单并校验',
|
||||
confirmCreate: '确认并建单',
|
||||
@@ -491,25 +513,6 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
saveFailed: '失败',
|
||||
versionConflict: { badge: '冲突' },
|
||||
statusBanner: { unknown: '未知' },
|
||||
reparseFailedVersion: {
|
||||
notice: 'V{failedVersion} 重新识别失败,失败阶段:{stage}。当前展示并可继续复核:V{displayedVersion}。',
|
||||
unknownStage: '未知阶段',
|
||||
stages: { layout_parsing: '解析 PDF 页面与表格' },
|
||||
},
|
||||
reparseProgress: {
|
||||
title: '重识别',
|
||||
subtitle: '',
|
||||
polling: '',
|
||||
refreshFailed: '',
|
||||
failed: '',
|
||||
retry: '',
|
||||
stages: {
|
||||
submitted: '1',
|
||||
layout_parsing: '2',
|
||||
extracting: '3',
|
||||
draft_ready: '4',
|
||||
},
|
||||
},
|
||||
autoProgress: {
|
||||
status: { unknown: '', needs_retry: '待重试', needs_human: '需要人工处理' },
|
||||
result: '{status}',
|
||||
@@ -592,6 +595,9 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
frozenOrder: '冻结订单',
|
||||
inventorySource: '库存源',
|
||||
downloadInventory: '下载库存文件',
|
||||
retryInventory: '重新获取库存',
|
||||
releaseShortage: '库存缺口放行',
|
||||
shortage: '库存不足',
|
||||
pending: '库存匹配或通知文件尚未生成。',
|
||||
},
|
||||
},
|
||||
@@ -658,26 +664,10 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
|
||||
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
|
||||
function resetActiveCaseFixture() {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
case_no: 'CASE-1',
|
||||
document_id: 1,
|
||||
status: 'draft',
|
||||
confirmed_task_no: null,
|
||||
confirmed_task_id: null,
|
||||
has_formal_ot: false,
|
||||
task_missing: false,
|
||||
recovery_available: null,
|
||||
post_confirm_auto_progress: null,
|
||||
process_gate: null,
|
||||
current_stage: null,
|
||||
technical_progress: null,
|
||||
automation: { status: 'idle', can_auto_create: false, can_build: true },
|
||||
available_actions: ['validate', 'confirm', 'mark_non_order', 'reparse'],
|
||||
profile_match: { available: false, visibility: 'admin_only', candidates: [] },
|
||||
};
|
||||
shippingProcessingProjection.value = null;
|
||||
intakeParseContext.value = null;
|
||||
activeCase.value = createActiveCaseFixture();
|
||||
shippingProcessingProjection.value = null;
|
||||
shippingProcessingLoading.value = false;
|
||||
intakeParseContext.value = null;
|
||||
}
|
||||
|
||||
describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
@@ -712,6 +702,21 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
},
|
||||
automation: { status: 'manual_fallback', can_auto_create: false, can_build: true },
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-GATE-1', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'confirm_customer', kind: 'current_gate', enabled: true,
|
||||
dispatch: 'navigation', ui_handler: 'customer_resolution',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
process_gate: { execution_no: 'EXEC-GATE-1' }, summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
@@ -721,6 +726,114 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.find('[data-testid="mock-process-gate"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('submits a server-authorized Gate action from the current-task card without an action-code alias', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', has_formal_ot: true, task_missing: false,
|
||||
confirmed_task_id: 98, confirmed_task_no: 'SN-EXCEL-1',
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
workItemType: 'order_task', workItemNo: 'SN-EXCEL-1', sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'SN-EXCEL-1', shippingNoticeNo: 'SN-EXCEL-1', conversationId: 'conv-1',
|
||||
submissionNo: 'SUB-EXCEL-1', intakeNo: 'SNI-EXCEL-1', status: 'blocked', stage: 'excel_generating',
|
||||
progressVersion: 1, lastActivityAt: '2026-08-18T12:13:30Z', currentGate: {
|
||||
gateCode: 'artifact_generation', status: 'blocked_retryable', nextActionCode: 'regenerate_excel_artifact',
|
||||
},
|
||||
processGate: {
|
||||
execution_no: 'EXEC-EXCEL-1', status: 'blocked_retryable', current_gate_code: 'artifact_generation',
|
||||
next_action_code: 'regenerate_excel_artifact', allowed_actions: ['regenerate_excel_artifact'],
|
||||
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable', evaluation_version: 8 },
|
||||
},
|
||||
availableActions: ['regenerate_excel_artifact'],
|
||||
sourceSummary: { emailSubject: null, filename: 'po.xlsx', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
childOrderTasks: [],
|
||||
uiState: {
|
||||
status: 'retryable', stage: 'excel_generating', blocking_reason: null,
|
||||
primary_action: { code: 'regenerate_excel_artifact', i18nKey: 'chat.shippingProcessing.action.regenerate_excel' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-EXCEL-1', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
|
||||
dispatch: 'mutation',
|
||||
target_surface: 'fulfillment_prep', target_anchor: 'excel_artifact',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-EXCEL-1',
|
||||
current_blocking_gate: {
|
||||
gate_code: 'artifact_generation', evaluation_version: 8,
|
||||
},
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:旧 Projection 的 regenerate_excel 不可执行;正式任务的原始动作码
|
||||
// 只委托统一 Gate 执行器,由其按后端版本与授权再次校验。
|
||||
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
execution_no: 'EXEC-EXCEL-1',
|
||||
current_blocking_gate: expect.objectContaining({ gate_code: 'artifact_generation' }),
|
||||
}),
|
||||
{ actionCode: 'regenerate_excel_artifact' },
|
||||
);
|
||||
expect(postFormalGateActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not submit an action merely because its code has a Gate-like prefix', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', has_formal_ot: true, task_missing: false,
|
||||
confirmed_task_id: 99, confirmed_task_no: 'SN-UNAUTHORIZED-1',
|
||||
// 旧 Case 投影仍可能带上 Gate;不能让它以动作码前缀绕过实时 Projection。
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-STALE-CASE-1', status: 'blocked_retryable', owner_type: 'human', technical_auto_only: false,
|
||||
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable' },
|
||||
},
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
workItemType: 'order_task', workItemNo: 'SN-UNAUTHORIZED-1', sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'SN-UNAUTHORIZED-1', shippingNoticeNo: 'SN-UNAUTHORIZED-1', conversationId: 'conv-1',
|
||||
submissionNo: 'SUB-UNAUTHORIZED-1', intakeNo: 'SNI-UNAUTHORIZED-1', status: 'blocked', stage: 'excel_generating',
|
||||
progressVersion: 1, lastActivityAt: '2026-08-18T12:13:30Z', currentGate: {
|
||||
gateCode: 'artifact_generation', status: 'blocked_retryable', nextActionCode: 'confirm_customer',
|
||||
},
|
||||
processGate: {
|
||||
execution_no: 'EXEC-UNAUTHORIZED-1', status: 'blocked_retryable', current_gate_code: 'artifact_generation',
|
||||
next_action_code: 'confirm_customer', allowed_actions: ['confirm_customer'],
|
||||
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable', evaluation_version: 9 },
|
||||
},
|
||||
availableActions: ['confirm_customer'],
|
||||
sourceSummary: { emailSubject: null, filename: 'po.xlsx', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
childOrderTasks: [],
|
||||
uiState: {
|
||||
status: 'retryable', stage: 'excel_generating', blocking_reason: null,
|
||||
primary_action: { code: 'regenerate_excel_artifact', i18nKey: 'chat.shippingProcessing.action.regenerate_excel' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
|
||||
// 旧 Projection 的 action 不可替代正式任务动作;详情无同码授权时右侧不展示写按钮。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('routes the right-rail field-conflict action through the registered focus executor', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -816,7 +929,33 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows restored version as current and latest version only as failed attempt', async () => {
|
||||
it('keeps a formal task action loading until its authoritative processing projection arrives', async () => {
|
||||
// Case 快照先返回时可能携带历史/降级 Gate;正式 OT 的动作必须等待统一 Projection 裁决。
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
has_formal_ot: true,
|
||||
confirmed_task_id: 90,
|
||||
confirmed_task_no: 'SN-PROJECTION-PENDING',
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-PROJECTION-PENDING', status: 'blocked_retryable', owner_type: 'human', technical_auto_only: false,
|
||||
current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' },
|
||||
primary_action: { code: 'retry', label_key: 'chat.shippingOrderReview.currentTask.actionRetry' },
|
||||
},
|
||||
automation: { status: 'failed', retryable: true, can_auto_create: false, can_build: true },
|
||||
};
|
||||
shippingProcessingProjection.value = null;
|
||||
shippingProcessingLoading.value = true;
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:不得先显示 Case 的通用“重试”,避免 Projection 到达后按钮语义跳变。
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render legacy reparse failure stage as a separate progress source', async () => {
|
||||
reviewProgressContext.value = {
|
||||
item_no: 'WFI-1',
|
||||
current_version_no: 4,
|
||||
@@ -832,21 +971,20 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
|
||||
const notice = wrapper.find('[data-testid="review-reparse-failed-version-notice"]');
|
||||
expect(notice.text()).toContain('V4 重新识别失败');
|
||||
expect(notice.text()).toContain('解析 PDF 页面与表格');
|
||||
expect(notice.text()).toContain('V3');
|
||||
// 关键断言:顶栏当前版本跟随旧成功结果 V3,禁止把旧字段标成失败尝试 V4。
|
||||
expect(wrapper.find('[data-testid="review-reparse-failed-version-notice"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-reparse-progress"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-reparse-progress-rail"]').exists()).toBe(false);
|
||||
// 关键断言:页面只消费统一生命周期/处理投影,禁止用旧失败阶段重建另一条进度轨道。
|
||||
expect(wrapper.find('[data-testid="review-workbench-execution-summary"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain('V3');
|
||||
});
|
||||
|
||||
it('does not show reparse-failure version notice for normal review', async () => {
|
||||
it('does not render a legacy reparse progress rail for normal review', async () => {
|
||||
reviewProgressContext.value = {
|
||||
item_no: 'WFI-1', current_version_no: 3, lifecycle_status: 'pending_review',
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
expect(wrapper.find('[data-testid="review-reparse-failed-version-notice"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-reparse-progress"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders main editor + summary rail without chat context toggle', async () => {
|
||||
@@ -1210,7 +1348,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
intakeParseContext.value = {
|
||||
case_no: 'CASE-1',
|
||||
attachment: { document_id: 1, filename: 'current.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' },
|
||||
email: { document_id: 2, filename: 'source.eml', text: 'current CASE-1 EML body' },
|
||||
email: { document_id: 2, filename: 'source.eml', render_kind: 'text', text: 'current CASE-1 EML body' },
|
||||
};
|
||||
|
||||
const intakeWrapper = await mountView({ lifecycle_stage: 'intake_parse' });
|
||||
@@ -1218,6 +1356,11 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
// 关键断言:接收解析面板只显示当前 Case context 的邮件正文和附件。
|
||||
expect(intakeWrapper.get('[data-testid="intake-parse-email-body"]').text()).toContain('current CASE-1 EML body');
|
||||
expect(intakeWrapper.get('[data-testid="intake-parse-attachment-preview"] iframe').attributes('src')).toBe('blob:mock-pdf');
|
||||
const intakeFooter = intakeWrapper.get('[data-testid="review-footer-actions"]');
|
||||
// 关键断言:接收解析处置复用订单复核的固定底栏,滚动邮件/附件时仍可操作。
|
||||
expect(intakeFooter.classes()).toEqual(expect.arrayContaining(['sticky', 'bottom-0']));
|
||||
expect(intakeFooter.text()).toContain('非订单');
|
||||
expect(intakeWrapper.find('[data-testid="intake-parse-disposition-actions"]').exists()).toBe(false);
|
||||
|
||||
const orderWrapper = await mountView({ lifecycle_stage: 'order_review' });
|
||||
// 关键断言:订单复核底栏保留 validate,但不再承载四个接收解析处置入口。
|
||||
@@ -1449,11 +1592,24 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
.toBeLessThan(wrapper.html().indexOf('review-fulfillment-prep-workspace'));
|
||||
});
|
||||
|
||||
it('keeps frozen order lines visible when the inventory file and match result are not ready', async () => {
|
||||
it('renders one row-level inventory workspace with each line source and authorized retry', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_id: 903, confirmed_task_no: 'SN-FROZEN', has_formal_ot: true,
|
||||
line_fulfillment: {
|
||||
lines: [{
|
||||
line_key: 'line-frozen',
|
||||
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
|
||||
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
|
||||
line_allowed_actions: ['release_inventory_shortage'],
|
||||
release_template_fields: [
|
||||
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
|
||||
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
|
||||
],
|
||||
release_required_fields: [{ field_id: '102', display_name: '库位' }],
|
||||
}],
|
||||
},
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
uiState: {
|
||||
@@ -1469,11 +1625,15 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
status: 'blocked', has_match_result: false,
|
||||
status: 'blocked', has_match_result: true,
|
||||
frozen_order_lines: [{
|
||||
line_key: 'line-frozen', reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6',
|
||||
}],
|
||||
lines: [], inventory_sources: [{ source_code: 'CRANE', status: 'waiting', inventory_file_id: null }],
|
||||
lines: [{
|
||||
line_key: 'line-frozen', reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN',
|
||||
required_qty: '6', available_qty: null, shortage_qty: null, source_code: 'DBS',
|
||||
inventory_file_no: 'SIF-LINE-DBS', status: 'shortage',
|
||||
}],
|
||||
artifact: { file_name: null, status: 'not_generated' },
|
||||
},
|
||||
},
|
||||
@@ -1483,78 +1643,63 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:无库存文件时仍展示冻结订单;库存匹配空态不能吞掉订单明细。
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-frozen-order"]').text()).toContain('RSV-FROZEN');
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-frozen-order"]').text()).toContain('PN-FROZEN');
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-prep-pending"]').exists()).toBe(true);
|
||||
// 关键断言:订单基线列和库存事实合为唯一行级工作表,库存源不得退化为任务级 CRANE。
|
||||
const workspace = wrapper.get('[data-testid="review-fulfillment-prep-workspace"]');
|
||||
expect(workspace.text()).toContain('RSV-FROZEN');
|
||||
expect(workspace.text()).toContain('PN-FROZEN');
|
||||
expect(workspace.text()).toContain('DBS');
|
||||
expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-download-line-frozen"]').attributes('title'))
|
||||
.toBeTruthy();
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-line-frozen"]').attributes('title'))
|
||||
.toBeTruthy();
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-retry-matching-line-frozen"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').exists()).toBe(true);
|
||||
expect(workspace.text()).toContain('库存不足');
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-download-line-frozen"]').trigger('click');
|
||||
expect(downloadWorkspaceShippingLineInventoryFileMock).toHaveBeenCalledWith('SN-FROZEN', 'SIF-LINE-DBS');
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-line-frozen"]').trigger('click');
|
||||
expect(retryWorkspaceShippingTaskLine).toHaveBeenCalledWith('SN-FROZEN', 'line-frozen');
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').trigger('click');
|
||||
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM ID');
|
||||
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM-001');
|
||||
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
|
||||
await dialog.find('textarea').setValue('客户确认分批发货');
|
||||
await dialog.find('input').setValue('A-01');
|
||||
await dialog.get('button.bg-amber-600').trigger('click');
|
||||
expect(vi.mocked(decideWorkspaceShippingOrderReviewLineFulfillment)).toHaveBeenCalledWith('CASE-1', expect.objectContaining({
|
||||
line_key: 'line-frozen',
|
||||
reason: '客户确认分批发货',
|
||||
release_field_values: { '102': 'A-01' },
|
||||
}));
|
||||
});
|
||||
|
||||
it('only exposes inventory download for the current task when the backend confirms its active file', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_id: 905, confirmed_task_no: 'SN-INVENTORY-FILE', has_formal_ot: true,
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
uiState: {
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-INVENTORY-FILE', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
frozen_order_lines: [], lines: [], has_match_result: false,
|
||||
inventory_file: { available: true, file_name: 'confirmed-inventory.xlsx' },
|
||||
},
|
||||
},
|
||||
},
|
||||
} as any);
|
||||
it('keeps intake parse on the standard workbench and removes the inventory return row', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
lifecycle_stage: 'intake_parse',
|
||||
lifecycle_entries: [],
|
||||
intake_parse_authorized: true,
|
||||
}],
|
||||
};
|
||||
const intakeWrapper = await mountView({ lifecycle_stage: 'intake_parse' });
|
||||
await flushPromises();
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:只有服务端声明当前任务 active link 文件可用时才出现入口,避免跨订单猜测下载。
|
||||
const download = wrapper.get('[data-testid="review-fulfillment-inventory-download"]');
|
||||
expect(download.text()).toContain('下载库存文件');
|
||||
await download.trigger('click');
|
||||
expect(downloadWorkspaceShippingInventoryFileMock).toHaveBeenCalledWith('SN-INVENTORY-FILE');
|
||||
// 关键断言:接收解析不是库存工作面,避免用户看不到重解析入口。
|
||||
expect(intakeWrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode'))
|
||||
.toBe('standard');
|
||||
expect(intakeWrapper.find('[data-testid="review-enter-inventory-mode"]').exists()).toBe(false);
|
||||
expect(intakeWrapper.find('[data-testid="review-return-standard-mode"]').exists()).toBe(false);
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not expose inventory download when the current task has no active inventory file', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_id: 906, confirmed_task_no: 'SN-NO-INVENTORY-FILE', has_formal_ot: true,
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
uiState: {
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-NO-INVENTORY-FILE', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: { preparation: { frozen_order_lines: [], lines: [], has_match_result: false, inventory_file: { available: false } } },
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="review-fulfillment-inventory-download"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('prefers the formal Gate over a stale processing projection in the current-task card', async () => {
|
||||
it('uses the current processing projection instead of a stale formal-task Gate in the current-task card', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -1582,9 +1727,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:正式 Gate 阻断时,右栏不得继续写成“系统正在处理”。
|
||||
// 关键断言:正式任务详情是附件/明细快照;当前 Gate 必须由实时 Projection 裁决。
|
||||
expect(wrapper.get('[data-testid="review-build-gate-rail"] [data-testid="review-current-processing-card"]')
|
||||
.attributes('data-user-status')).toBe('retryable');
|
||||
.attributes('data-user-status')).toBe('running');
|
||||
});
|
||||
|
||||
it('ignores a late formal-task response after switching to another PDF', async () => {
|
||||
@@ -1657,7 +1802,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.get('[data-testid="review-footer-actions"]').text()).toContain('保存订单并校验');
|
||||
});
|
||||
|
||||
it('keeps manual upload registration out of the upload main area because the current-task card owns it', async () => {
|
||||
it('keeps backend-authorized manual upload registration out of the upload main area', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
activeCase.value = {
|
||||
@@ -1691,6 +1836,8 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
target_surface: 'upload_complete',
|
||||
target_anchor: 'manual_upload',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
@@ -1700,14 +1847,205 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
} as any);
|
||||
const withAuthorization = await mountView({ lifecycle_stage: 'upload_complete' });
|
||||
await flushPromises();
|
||||
// Gate 写操作只在右侧“当前任务”显示;主区只保留上传事实与审计摘要。
|
||||
expect(withAuthorization.find('[data-testid="review-lifecycle-upload-manual"]').exists()).toBe(false);
|
||||
// 无界面 TaskTodoPanel 仍须挂载执行器,供右栏 Gate 动作统一调度。
|
||||
expect((withAuthorization.vm as { formalTodoPanelRef?: unknown }).formalTodoPanelRef).toBeTruthy();
|
||||
// 正式动作直接提交当前 Gate,不允许无界面 TaskTodoPanel 作为隐藏执行器。
|
||||
expect((withAuthorization.vm as { formalTodoPanelRef?: unknown }).formalTodoPanelRef).toBeUndefined();
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('opens the page-level evidence dialog when the authorized current-task action is manual upload', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-DIALOG', confirmed_task_id: 19, has_formal_ot: true,
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-UPLOAD-DIALOG', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
|
||||
target_surface: 'upload_complete', target_anchor: 'manual_upload',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('renders the authorized Excel download in every upload-complete order line instead of the task rail', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-DOWNLOAD-DISPATCH', confirmed_task_id: 20, has_formal_ot: true,
|
||||
schema: {
|
||||
...activeCase.value.schema,
|
||||
fields: [
|
||||
...activeCase.value.schema.fields,
|
||||
{ field_id: 'fld-line-no', field_code: 'line_no', display_name: '项次', scope: 'line', value_type: 'string', required: true, options: [] },
|
||||
{ field_id: 'fld-part-number', field_code: 'part_number', display_name: '料号', scope: 'line', value_type: 'string', required: true, options: [] },
|
||||
{ field_id: 'fld-quantity', field_code: 'quantity', display_name: '数量', scope: 'line', value_type: 'number', required: true, options: [] },
|
||||
],
|
||||
},
|
||||
draft: {
|
||||
...activeCase.value.draft,
|
||||
lines: [
|
||||
{ line_key: 'LINE-1', values: { 'fld-line-no': { value: '10' }, 'fld-part-number': { value: 'PN-ONE' }, 'fld-quantity': { value: '4' } }, machine_fields: [] },
|
||||
{ line_key: 'LINE-2', values: { 'fld-line-no': { value: '20' }, 'fld-part-number': { value: 'PN-TWO' }, 'fld-quantity': { value: '7' } }, machine_fields: [] },
|
||||
],
|
||||
},
|
||||
line_fulfillment: {
|
||||
lines: [
|
||||
{ line_key: 'LINE-1', reservation_id: 'RSV-1', line_status: 'fulfilled' },
|
||||
{ line_key: 'LINE-2', reservation_id: 'RSV-2', line_status: 'fulfilled' },
|
||||
],
|
||||
},
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-DOWNLOAD-DISPATCH', status: 'completed', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [{
|
||||
code: 'download_excel', label: '下载 Excel', kind: 'view', enabled: true,
|
||||
dispatch: 'view', ui_handler: 'excel_download',
|
||||
target_surface: 'upload_complete', target_anchor: 'excel_artifact',
|
||||
requires_confirmation: false,
|
||||
}],
|
||||
},
|
||||
lifecycle_stage: 'upload_complete',
|
||||
lifecycle_entries: [{ code: 'upload_complete', state: 'current' }],
|
||||
process_gate: { execution_no: 'EXEC-DOWNLOAD-DISPATCH' }, summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
|
||||
await flushPromises();
|
||||
|
||||
const rows = wrapper.findAll('[data-testid="review-upload-complete-line"]');
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0].text()).toContain('PN-ONE');
|
||||
expect(rows[1].text()).toContain('PN-TWO');
|
||||
expect(wrapper.find('[data-testid="review-current-task-recovery-download_excel"]').exists()).toBe(false);
|
||||
|
||||
await wrapper.get('[data-testid="review-upload-complete-download-LINE-1"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 下载是 Artifact 只读操作;订单行不按 PO 聚合,且不得伪装成 Gate mutation。
|
||||
expect(downloadWorkspaceShippingExcelFileMock).toHaveBeenCalledWith('SN-DOWNLOAD-DISPATCH');
|
||||
expect(messageMocks.success).not.toHaveBeenCalled();
|
||||
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps backend-authorized Excel regeneration out of fulfillment preparation main area', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-EXCEL-RETRY', confirmed_task_id: 12, has_formal_ot: true,
|
||||
};
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0], lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ 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' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-EXCEL-RETRY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
|
||||
dispatch: 'mutation',
|
||||
target_surface: 'fulfillment_prep',
|
||||
target_anchor: 'excel_artifact',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
stage_context: { preparation: { status: 'blocked', has_match_result: false, lines: [] } },
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// Gate 18 的写入口只属于右侧“当前任务”;准备区仅展示库存与产物事实。
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-preparation-regenerate_excel_artifact"]').exists()).toBe(false);
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not place a backend action in a lifecycle area when its anchor differs', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-ANCHOR-1', confirmed_task_id: 13, has_formal_ot: true,
|
||||
};
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0], lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-ANCHOR-1', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
|
||||
dispatch: 'mutation',
|
||||
target_surface: 'fulfillment_prep', target_anchor: 'inventory_matching',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
stage_context: { preparation: { status: 'blocked', has_match_result: false, lines: [] } },
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 位置必须同时由后端 surface 与 anchor 授权;前端不能仅凭动作码或阶段补放。
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-preparation-regenerate_excel_artifact"]').exists()).toBe(false);
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
}, 15000);
|
||||
|
||||
it('renders a persistent result panel for a completed formal task', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -1914,7 +2252,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
expect(messageMocks.warning).toHaveBeenCalledWith('审计记录失败,敏感面板未打开,请重试');
|
||||
});
|
||||
|
||||
it('restores object-level retry from post_confirm_auto_progress after reload', async () => {
|
||||
it('waits for the authoritative Gate projection instead of restoring Case retry after reload', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
@@ -1938,15 +2276,15 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
// 关键断言:琥珀色确认条已移除;刷新后对象级重试挂在当前处理卡。
|
||||
// 关键断言:正式 OT 的旧 Case 快照不是写授权;实时 Gate 未返回时只能等待。
|
||||
expect(wrapper.find('[data-testid="review-confirm-outcome"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-RECOVER-1');
|
||||
}, 15000);
|
||||
|
||||
it('retries formal OT via unified /retry from main card after refresh without confirmSuccess (UI-01)', async () => {
|
||||
// 关键断言:刷新后无 confirmSuccess 时,主卡仍用 confirmed_task_no 调统一 /retry(禁止 auto-progress)。
|
||||
it('does not call legacy retry before the formal OT Gate projection arrives (UI-01)', async () => {
|
||||
// 关键断言:刷新后无实时 Gate 时,不能用 confirmed_task_no 调旧 /retry。
|
||||
vi.mocked(retryWorkspaceShippingTask).mockClear();
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -1972,10 +2310,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
const retryBtn = wrapper.find('[data-testid="review-current-processing-retry"]');
|
||||
expect(retryBtn.exists()).toBe(true);
|
||||
await retryBtn.trigger('click');
|
||||
await flushPromises();
|
||||
expect(retryWorkspaceShippingTask).toHaveBeenCalledWith('SN-OT-FAIL-1');
|
||||
expect(retryBtn.exists()).toBe(false);
|
||||
expect(retryWorkspaceShippingTask).not.toHaveBeenCalled();
|
||||
}, 15000);
|
||||
|
||||
it('disables the formal Gate retry while inventory preparation is waiting for RPA callback', async () => {
|
||||
@@ -2005,6 +2341,25 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
vi.mocked(getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-OT-WAITING-INVENTORY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'retry_inventory_preparation', kind: 'recovery', enabled: true,
|
||||
dispatch: 'mutation', requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-INVENTORY-WAITING',
|
||||
current_blocking_gate: {
|
||||
gate_code: 'inventory_preparation', evaluation_version: 1,
|
||||
},
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
@@ -2147,8 +2502,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
|
||||
}, 15000);
|
||||
|
||||
it('hydrates progress-failed retry state from Case projection without confirm UI', async () => {
|
||||
// 关键断言:无确认建单按钮时,仍可从 post_confirm_auto_progress 恢复对象级重试入口。
|
||||
it('does not hydrate a write retry from Case projection without formal Gate data', async () => {
|
||||
// 关键断言:无确认建单按钮时,Case 的失败状态只能作为历史摘要,不能恢复写入口。
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
@@ -2173,7 +2528,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-CONFIRM-PROGRESS-FAIL');
|
||||
}, 15000);
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user