!11 feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
Merge pull request !11 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
402 files changed
+23045
-20484
No files matched your search
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* features/chat/api/shipping.api.request-dedupe.spec.ts
|
||||
* 用途:锁定重型订单抽取 Run 读取的同 key 在途请求合并契约。
|
||||
* 依赖:Vitest、shipping.api、统一 requestJson。
|
||||
* 逻辑:两个消费者同时读取同一 Run 时必须复用一个 HTTP 请求;请求结束后才允许下一次读取。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const requestJson = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/shared/api/client', () => ({
|
||||
BusinessError: class BusinessError extends Error {},
|
||||
requestJson,
|
||||
}));
|
||||
|
||||
import {
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
getWorkspaceShippingProcessing,
|
||||
} from './shipping.api';
|
||||
|
||||
describe('getWorkspaceShippingOrderExtractionRun', () => {
|
||||
beforeEach(() => {
|
||||
requestJson.mockReset();
|
||||
// 模块级短缓存会跨用例保留;本文件的会话 ID 均唯一,避免上一用例污染下一用例。
|
||||
});
|
||||
|
||||
it('coalesces concurrent reads of the same Run into one HTTP request', async () => {
|
||||
let resolveRequest!: (value: { run_no: string }) => void;
|
||||
requestJson.mockImplementationOnce(() => new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}));
|
||||
|
||||
const first = getWorkspaceShippingOrderExtractionRun('SNER-SAME');
|
||||
const second = getWorkspaceShippingOrderExtractionRun('SNER-SAME');
|
||||
|
||||
// 关键断言:慢 Run 投影在途时,同一文件的第二个消费者不得再创建独立网络请求。
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
resolveRequest({ run_no: 'SNER-SAME' });
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
{ run_no: 'SNER-SAME' },
|
||||
{ run_no: 'SNER-SAME' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('lets one caller stop waiting without aborting a shared Run request', async () => {
|
||||
let resolveRequest!: (value: { run_no: string }) => void;
|
||||
requestJson.mockImplementationOnce(() => new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}));
|
||||
const controller = new AbortController();
|
||||
|
||||
const cancelledCaller = getWorkspaceShippingOrderExtractionRun('SNER-SHARED', controller.signal);
|
||||
const activeCaller = getWorkspaceShippingOrderExtractionRun('SNER-SHARED');
|
||||
controller.abort();
|
||||
|
||||
// 关键断言:路由离开只结束当前消费者等待,不能中止其他组件复用的重型读取。
|
||||
await expect(cancelledCaller).rejects.toMatchObject({ name: 'AbortError' });
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
resolveRequest({ run_no: 'SNER-SHARED' });
|
||||
await expect(activeCaller).resolves.toEqual({ run_no: 'SNER-SHARED' });
|
||||
});
|
||||
|
||||
it('reuses a successful conversation summary during the short refresh burst', async () => {
|
||||
requestJson.mockResolvedValue({
|
||||
conversation_id: 'conversation-summary-cache',
|
||||
work_items: [],
|
||||
conversation_processing: null,
|
||||
});
|
||||
|
||||
await getWorkspaceShippingProcessing('conversation-summary-cache');
|
||||
await getWorkspaceShippingProcessing('conversation-summary-cache');
|
||||
|
||||
// 关键断言:首屏 watcher 连续触发时必须复用刚完成的摘要,避免重复慢查询。
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('binds every summary leaf to its status-group task for batch rendering', async () => {
|
||||
requestJson.mockResolvedValue({
|
||||
conversation_id: 'conversation-leaf-binding-20260822',
|
||||
conversation_processing: {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
status_groups: {
|
||||
failed: [],
|
||||
waiting_human: [{
|
||||
user_task_no: 'INTAKE:SNI-1', group: 'needs_action', status_label: 'waiting_human',
|
||||
file_count: 1, can_append: false,
|
||||
aggregate_children: [{
|
||||
work_item_type: 'order_task', work_item_no: 'DOCUMENT:1', source_type: 'eml',
|
||||
conversation_id: 'conversation-leaf-binding-20260822', intake_no: 'SNI-1', submission_no: 'SUB-1',
|
||||
// 同一邮件内另一 Candidate 的原始 OT 不能用作父卡关联键。
|
||||
root_order_task_no: 'OT-OTHER-CANDIDATE',
|
||||
status: 'waiting_human', stage: 'candidate_creating', progress_version: 1,
|
||||
source_summary: { document_id: 1, filename: 'order.pdf' },
|
||||
}],
|
||||
}],
|
||||
processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = await getWorkspaceShippingProcessing('conversation-leaf-binding-20260822');
|
||||
|
||||
// 关键断言:批次卡按父任务查实时叶子时,必须能找到本摘要组的文件。
|
||||
expect(response.conversation_processing?.status_groups?.waiting_human[0]?.aggregateChildren?.[0]).toMatchObject({
|
||||
workItemNo: 'DOCUMENT:1',
|
||||
});
|
||||
expect(response.conversation_processing?.status_groups?.waiting_human[0]?.aggregateChildren).toHaveLength(1);
|
||||
expect(response.work_items).toHaveLength(1);
|
||||
expect(response.work_items[0]?.rootOrderTaskNo).toBe('INTAKE:SNI-1');
|
||||
expect(response.work_items[0]?.sourceSummary.documentId).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -23,11 +23,13 @@ import type {
|
||||
ShippingNoticeIntakeResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingFreightNoticeGroupsResponse,
|
||||
ShippingTaskBatchDispositionResponse,
|
||||
ShippingTaskPage,
|
||||
ShippingCustomerOption,
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunListItem,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingOrderReviewQueue,
|
||||
@@ -69,11 +71,6 @@ type ShippingApiStatusPayload = {
|
||||
code?: string;
|
||||
details?: Record<string, unknown>;
|
||||
request_id?: string;
|
||||
/** 批次重试等接口返回的已发起任务数 */
|
||||
started?: number;
|
||||
/** 批次重试等接口返回的跳过任务数 */
|
||||
skipped?: number;
|
||||
batch_no?: string;
|
||||
/** 后端返回的语义化原因码(对齐 noop / needs_human / already_running 等状态分支) */
|
||||
reason_code?: ConversationProcessingAppendBlockReason | string | null;
|
||||
};
|
||||
@@ -125,6 +122,12 @@ export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[
|
||||
export const getWorkspaceShippingTask = (taskNo: string) =>
|
||||
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
|
||||
|
||||
/** 读取当前 PO 下按 business_no 聚合的货代上传 Notice。 */
|
||||
export const getWorkspaceShippingFreightNoticeGroups = (taskNo: string) =>
|
||||
requestJson<ShippingFreightNoticeGroupsResponse>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/freight-notice-groups`,
|
||||
);
|
||||
|
||||
/**
|
||||
* 分页拉取任务工作台统一审计时间线(ShippingAuditEvent 单源)。
|
||||
*/
|
||||
@@ -145,10 +148,14 @@ export const listWorkspaceShippingTaskAuditTimeline = (
|
||||
export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
|
||||
requestJson<ShippingTaskUiState>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/ui-state`);
|
||||
|
||||
/** 生成任务导出文件的前端下载 URL。 */
|
||||
/** 旧任务号 Excel 下载 URL;仅供未迁移页面兼容,新货代操作必须使用 business_no。 */
|
||||
export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
|
||||
|
||||
/** 按发货通知单号下载唯一正式 Excel。 */
|
||||
export const workspaceShippingNoticeExportUrl = (businessNo: string) =>
|
||||
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/export`;
|
||||
|
||||
/** 当前任务已关联库存快照的受控下载 URL;后端会再次校验任务归属与活动 link。 */
|
||||
export const workspaceShippingInventoryFileUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-file`;
|
||||
@@ -158,7 +165,7 @@ export const workspaceShippingLineInventoryFileUrl = (taskNo: string, inventoryF
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-files/${encodeURIComponent(inventoryFileNo)}`;
|
||||
|
||||
/** 下载一个批次或显式任务集合的当前 ready 发货 Excel ZIP。 */
|
||||
export async function downloadWorkspaceShippingExportArchive(payload: { batch_no?: string; task_nos?: string[] }) {
|
||||
export async function downloadWorkspaceShippingExportArchive(payload: { task_nos?: string[] }) {
|
||||
const response = await fetch('/api/workspace/shipping-exports/archive', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, body: JSON.stringify(payload),
|
||||
});
|
||||
@@ -198,9 +205,9 @@ export const createWorkspaceOrderExtractionSubmission = (
|
||||
);
|
||||
|
||||
/**
|
||||
* 拉取统一 ShippingProcessingProjection(唯一进度读源;含 order_intake / order_task)。
|
||||
* 核心逻辑:内嵌 conversation_processing.status_groups 是新版批次列表唯一读源;
|
||||
* 仅旧服务端未返回该字段时才由 work_items 合成兼容分组;旧 GET 已移除。
|
||||
* 拉取会话首屏摘要(唯一进度读源)。
|
||||
* 核心逻辑:首屏只消费后端裁决的 status_groups;完整 work_items/Gate 详情不进入
|
||||
* 轮询请求,按需通过 work-item 接口读取;旧服务端才允许 work_items 兼容。
|
||||
*/
|
||||
type WorkspaceShippingProcessingResponse = {
|
||||
conversation_id: string;
|
||||
@@ -210,18 +217,38 @@ type WorkspaceShippingProcessingResponse = {
|
||||
|
||||
/** 同一会话跨组件实例共享在途请求,避免历史路由恢复重挂载造成重复慢查询。 */
|
||||
const shippingProcessingRequests = new Map<string, Promise<WorkspaceShippingProcessingResponse>>();
|
||||
const SHIPPING_PROCESSING_REQUEST_TIMEOUT_MS = 10_000;
|
||||
/** 成功摘要短暂复用,覆盖同一渲染周期内的重复触发而不延迟后续轮询更新。 */
|
||||
const shippingProcessingSnapshots = new Map<string, {
|
||||
expiresAt: number;
|
||||
value: WorkspaceShippingProcessingResponse;
|
||||
}>();
|
||||
const SHIPPING_PROCESSING_SNAPSHOT_TTL_MS = 3_000;
|
||||
// 会话投影包含 Gate/Review 的只读裁决;真实大批次在服务端已完成附件批量预取后
|
||||
// 仍可能超过 10 秒。超时必须覆盖最坏合法读取,不能将未完成投影误显示为 0 文件。
|
||||
const SHIPPING_PROCESSING_REQUEST_TIMEOUT_MS = 30_000;
|
||||
|
||||
export const getWorkspaceShippingProcessing = async (
|
||||
conversationId: string,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
const normalized = String(conversationId || '').trim();
|
||||
if (!normalized) {
|
||||
throw new BusinessError({
|
||||
message: 'conversation_id is required',
|
||||
code: 'SHIPPING.PROCESSING_CONVERSATION_REQUIRED',
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
const existing = shippingProcessingRequests.get(normalized);
|
||||
if (existing) return existing;
|
||||
|
||||
// 不把单个组件的 AbortSignal 传给共享网络请求:卸载旧实例不能取消新实例仍需的首屏数据。
|
||||
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
|
||||
const snapshot = shippingProcessingSnapshots.get(normalized);
|
||||
if (snapshot) {
|
||||
if (snapshot.expiresAt > Date.now()) return Promise.resolve(snapshot.value);
|
||||
shippingProcessingSnapshots.delete(normalized);
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
@@ -232,18 +259,43 @@ export const getWorkspaceShippingProcessing = async (
|
||||
work_items?: unknown[];
|
||||
conversation_processing?: ConversationProcessingProjection | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-processing/conversations/${encodeURIComponent(normalized)}`,
|
||||
`/api/workspace/shipping-processing/conversations/${encodeURIComponent(normalized)}?view=summary`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then((raw): WorkspaceShippingProcessingResponse => ({
|
||||
conversation_id: String(raw?.conversation_id || normalized),
|
||||
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
|
||||
// 会话级 status_groups / 四阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
|
||||
// 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。
|
||||
conversation_processing: raw?.conversation_processing
|
||||
.then((raw): WorkspaceShippingProcessingResponse => {
|
||||
const conversationProcessing = raw?.conversation_processing
|
||||
? normalizeConversationProcessingProjection(raw.conversation_processing)
|
||||
: null,
|
||||
}))
|
||||
: null;
|
||||
// summary 读模型只传状态→EML→PDF树。为既有批次中心提供最小实时叶子,
|
||||
// 禁止回退到完整 Run/Gate 详情或历史快照。
|
||||
// normalizeConversationProcessingProjection 已把 aggregate_children 转成 camelCase。
|
||||
// 为避免“后端 DTO 已规范化、再按 snake_case 读取”的二次断裂,直接透传
|
||||
// 已规范化叶子后仅覆写本次展示关联键。
|
||||
const normalizedSummaryLeaves = conversationProcessing?.status_groups
|
||||
? Object.values(conversationProcessing.status_groups).flatMap((tasks) => tasks.flatMap((task) => (
|
||||
(task.aggregateChildren || []).map((child) => ({
|
||||
...child,
|
||||
rootOrderTaskNo: task.user_task_no,
|
||||
}))
|
||||
)))
|
||||
: [];
|
||||
const value: WorkspaceShippingProcessingResponse = {
|
||||
conversation_id: String(raw?.conversation_id || normalized),
|
||||
work_items: Array.isArray(raw?.work_items) && raw.work_items.length
|
||||
? normalizeShippingProcessingWorkItems(raw.work_items)
|
||||
// 摘要接口返回空数组是合法形态;此时已完成 API 规范化的叶子直接作为
|
||||
// 批次展示索引,不能再送入 snake_case 规范器导致叶子被丢弃。
|
||||
: normalizedSummaryLeaves,
|
||||
// 会话级 status_groups / 五阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
|
||||
// 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。
|
||||
conversation_processing: conversationProcessing,
|
||||
};
|
||||
shippingProcessingSnapshots.set(normalized, {
|
||||
expiresAt: Date.now() + SHIPPING_PROCESSING_SNAPSHOT_TTL_MS,
|
||||
value,
|
||||
});
|
||||
return value;
|
||||
})
|
||||
.finally(() => {
|
||||
clearTimeout(timeout);
|
||||
if (shippingProcessingRequests.get(normalized) === request) {
|
||||
@@ -304,11 +356,66 @@ export const markWorkspaceConversationTaskViewed = (
|
||||
* @param runNo - Run 业务编号。
|
||||
* @param signal - 切会话或超时时取消当前 GET,不取消后台 Run。
|
||||
*/
|
||||
export const getWorkspaceShippingOrderExtractionRun = (runNo: string, signal?: AbortSignal) =>
|
||||
requestJson<ShippingOrderExtractionRun>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}`,
|
||||
{ signal },
|
||||
/**
|
||||
* 同一 Run 的完整工作台投影可能较重;跨组件并发读取时只保留一个在途 HTTP 请求。
|
||||
* 单个消费者取消不取消共享请求,避免路由切换或轮询重叠重复触发服务端投影。
|
||||
*/
|
||||
const shippingOrderExtractionRunRequests = new Map<string, Promise<ShippingOrderExtractionRun>>();
|
||||
const SHIPPING_ORDER_EXTRACTION_RUN_REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* 为共享的 Run HTTP Promise 绑定单个消费者的取消边界。
|
||||
* 核心逻辑:消费者离开时立即拒绝该消费者,但绝不取消仍可能被其他组件复用的底层请求。
|
||||
* @param request - 已由同一 Run 消费者共享的底层 HTTP Promise。
|
||||
* @param signal - 当前消费者的可选取消信号。
|
||||
* @returns 仅代表当前消费者生命周期的 Promise。
|
||||
*/
|
||||
const withCallerAbort = <T>(request: Promise<T>, signal?: AbortSignal): Promise<T> => {
|
||||
if (!signal) return request;
|
||||
if (signal.aborted) return Promise.reject(new DOMException('Aborted', 'AbortError'));
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const cleanup = () => signal.removeEventListener('abort', onAbort);
|
||||
const onAbort = () => {
|
||||
cleanup();
|
||||
reject(new DOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
request.then(
|
||||
(value) => {
|
||||
cleanup();
|
||||
resolve(value);
|
||||
},
|
||||
(error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const getWorkspaceShippingOrderExtractionRun = async (runNo: string, signal?: AbortSignal) => {
|
||||
const normalized = String(runNo || '').trim();
|
||||
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
|
||||
const existing = shippingOrderExtractionRunRequests.get(normalized);
|
||||
if (existing) return withCallerAbort(existing, signal);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
SHIPPING_ORDER_EXTRACTION_RUN_REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
const request = requestJson<ShippingOrderExtractionRun>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(normalized)}`,
|
||||
{ signal: controller.signal },
|
||||
).finally(() => {
|
||||
clearTimeout(timeout);
|
||||
if (shippingOrderExtractionRunRequests.get(normalized) === request) {
|
||||
shippingOrderExtractionRunRequests.delete(normalized);
|
||||
}
|
||||
});
|
||||
shippingOrderExtractionRunRequests.set(normalized, request);
|
||||
return withCallerAbort(request, signal);
|
||||
};
|
||||
|
||||
/** 复用原附件与冻结快照,重新入队一次失败的订单抽取 Run。 */
|
||||
export const retryWorkspaceShippingOrderExtractionRun = (runNo: string) =>
|
||||
@@ -380,10 +487,11 @@ export const getWorkspaceShippingOrderReviewRun = (runNo: string) =>
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/review`,
|
||||
);
|
||||
|
||||
/** 获取一份 PDF 的冻结 Schema 与只读机器/草稿投影。 */
|
||||
export const getWorkspaceShippingOrderReviewCase = (caseNo: string) =>
|
||||
/** 获取一份 PDF 的冻结 Schema 与只读机器/草稿投影;signal 只取消本次浏览器读取。 */
|
||||
export const getWorkspaceShippingOrderReviewCase = (caseNo: string, signal?: AbortSignal) =>
|
||||
requestJson<ShippingOrderReviewCaseSnapshot>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}`,
|
||||
{ signal },
|
||||
);
|
||||
|
||||
/** 保存一个复核订单头字段;后端以 expected_draft_version 拒绝过期窗口覆盖。 */
|
||||
@@ -421,7 +529,10 @@ export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey:
|
||||
);
|
||||
|
||||
export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expectedDraftVersion: number) =>
|
||||
requestJson<{ case: ShippingOrderReviewCase }>(
|
||||
requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/validate`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
@@ -638,9 +749,10 @@ export const reparseWorkspaceShippingOrderReviewDocument = (caseNo: string, reas
|
||||
* 获取复核字段的安全证据摘要(含 highlight_quality / highlight_bbox 契约字段)。
|
||||
* PDF 二进制继续由受控同源预览接口提供;坐标缺失不影响字段值。
|
||||
*/
|
||||
export const getWorkspaceShippingOrderReviewEvidence = (caseNo: string) =>
|
||||
export const getWorkspaceShippingOrderReviewEvidence = (caseNo: string, signal?: AbortSignal) =>
|
||||
requestJson<{ case_no: string; items: ShippingOrderReviewEvidence[] }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/evidence`,
|
||||
{ signal },
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -770,7 +882,7 @@ export const decideWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
);
|
||||
|
||||
/**
|
||||
* 为选中完整明细行创建履约波次 Task。
|
||||
* 为选中完整明细行创建独立发货通知和 Excel。
|
||||
*/
|
||||
export const waveWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
caseNo: string,
|
||||
@@ -786,6 +898,7 @@ export const waveWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
task_no?: string | null;
|
||||
wave_no?: number | null;
|
||||
notice_no?: string | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/wave`,
|
||||
{
|
||||
@@ -882,7 +995,7 @@ export const listWorkspaceShippingOrderExtractionRuns = (
|
||||
) => {
|
||||
const params = new URLSearchParams({ limit: String(limit) });
|
||||
if (conversationId) params.set('conversation_id', conversationId);
|
||||
return requestJson<{ items: ShippingOrderExtractionRun[] }>(
|
||||
return requestJson<{ items: ShippingOrderExtractionRunListItem[] }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs?${params.toString()}`,
|
||||
{ signal },
|
||||
);
|
||||
@@ -994,37 +1107,6 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试当前发货任务。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param comment - 可选重试备注
|
||||
* @returns 重试结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingTask(taskNo: string, comment?: string) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry`,
|
||||
jsonPost(comment ? { comment, reason: comment } : { reason: 'user_retry' }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级统一「重试」:后端决策器选择 fetch/rematch/needs_human。
|
||||
* 核心逻辑:前端不传内部动作码。
|
||||
* @param taskNo - 正式任务号
|
||||
* @param lineKey - 行键
|
||||
*/
|
||||
export async function retryWorkspaceShippingTaskLine(
|
||||
taskNo: string,
|
||||
lineKey: string,
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/lines/${encodeURIComponent(lineKey)}/retry`,
|
||||
jsonPost({ reason: 'user_retry_inventory' }),
|
||||
);
|
||||
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 }
|
||||
@@ -1212,22 +1294,38 @@ export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: s
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记货代系统已人工上传完成。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param payload - 当前 Artifact、人工回执 FileAsset 编号及可选货代参考号;回执编号必填。
|
||||
* 按发货通知单号确认货代系统已人工上传完成。
|
||||
* @param businessNo - 对外发货通知单号
|
||||
* @param payload - 当前通知唯一 Excel 的可选 Artifact 编号。
|
||||
* @returns 上传确认结果
|
||||
*/
|
||||
export async function markWorkspaceShippingManualUploaded(
|
||||
taskNo: string,
|
||||
payload: { evidence_asset_no: string; artifact_id?: number; freight_ref_no?: string },
|
||||
businessNo: string,
|
||||
payload: { artifact_id?: number } = {},
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/mark-manual-uploaded`,
|
||||
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/confirm-uploaded`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 按多个发货通知单号批量确认人工上传;后端逐单裁决并返回逐单结果。 */
|
||||
export async function batchConfirmWorkspaceShippingNoticesUploaded(businessNos: string[]) {
|
||||
return requestJson<{ results: Array<Record<string, unknown>> }>(
|
||||
'/api/workspace/shipping-notices/batch/confirm-uploaded',
|
||||
jsonPost({ business_nos: businessNos }),
|
||||
);
|
||||
}
|
||||
|
||||
/** 按多个发货通知单号批量受理货代 RPA 上传;RPA 成功仍以回调为准。 */
|
||||
export async function batchStartWorkspaceShippingNoticeRpaUpload(businessNos: string[]) {
|
||||
return requestJson<{ results: Array<Record<string, unknown>> }>(
|
||||
'/api/workspace/shipping-notices/batch/rpa-upload',
|
||||
jsonPost({ business_nos: businessNos }),
|
||||
);
|
||||
}
|
||||
|
||||
/** 发货通知 Agent 应用类型标识(运行时识别)。 */
|
||||
export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
|
||||
|
||||
@@ -1348,9 +1446,6 @@ export const resolveShippingNoticeCandidateDuplicate = (
|
||||
|
||||
export type {
|
||||
ShippingChatAction,
|
||||
ShippingConversationBatch,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingConversationWorkspaceSummary,
|
||||
ShippingCurrentStepProgress,
|
||||
ShippingDecisionResponse,
|
||||
ShippingMatchLineResult,
|
||||
|
||||
@@ -94,64 +94,23 @@ const shippingProcessing = useShippingNoticeWorkflow({
|
||||
});
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
|
||||
|
||||
/**
|
||||
* 当前货代工作台的会话身份。
|
||||
*
|
||||
* 核心逻辑:历史会话首帧时 page.conversationId 尚未由消息恢复链路回填,
|
||||
* 但 route.query.conversation_id 已是用户明确打开的会话。所有批次中心
|
||||
* 显隐、传参和会话切换边界必须使用同一个优先级,避免中心带空 ID 初始化。
|
||||
*/
|
||||
const activeShippingConversationId = computed(() => (
|
||||
String(route.query.conversation_id || page.conversationId || '').trim()
|
||||
));
|
||||
|
||||
const isOrderReviewMode = computed(() => route.query.mode === 'order-review' && typeof route.query.run_no === 'string' && route.query.run_no.length > 0);
|
||||
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
|
||||
const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.currentAgent, 'maintenance'));
|
||||
|
||||
const activeExtractionRunNo = computed(() => {
|
||||
|
||||
// [STEP 1] 优先从消息流中的抽取状态卡取 run_no(终态后仍在消息里)。
|
||||
// page 经 reactive provide 后 messages 已解包为数组,禁止再读 .value。
|
||||
const messages = Array.isArray(page.messages) ? page.messages : [];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
|
||||
const item = messages[i];
|
||||
|
||||
if (!item || item.role !== 'assistant') continue;
|
||||
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload : null;
|
||||
|
||||
const fromPayload = payload && typeof (payload as { order_extraction_run_no?: unknown }).order_extraction_run_no === 'string'
|
||||
|
||||
? String((payload as { order_extraction_run_no: string }).order_extraction_run_no).trim()
|
||||
|
||||
: '';
|
||||
|
||||
if (fromPayload) return fromPayload;
|
||||
|
||||
if (item.shipping_order_extraction_state) {
|
||||
|
||||
const fromGetter = String(page.getActiveOrderExtractionRunNo?.() || '').trim();
|
||||
|
||||
if (fromGetter) return fromGetter;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// [STEP 2] 回退活动 Run(轮询中)与路由深链。
|
||||
|
||||
try {
|
||||
|
||||
const fromActive = String(page.getActiveOrderExtractionRunNo?.() || '').trim();
|
||||
|
||||
if (fromActive) return fromActive;
|
||||
|
||||
} catch {
|
||||
|
||||
/* ignore */
|
||||
|
||||
}
|
||||
|
||||
const fromQuery = typeof route.query.run_no === 'string' ? route.query.run_no.trim() : '';
|
||||
|
||||
return fromQuery;
|
||||
|
||||
});
|
||||
|
||||
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
|
||||
const batchWorkbenchOpen = ref(false);
|
||||
|
||||
@@ -160,7 +119,7 @@ const batchWorkbenchOpen = ref(false);
|
||||
const showShippingWorkflowTimeline = computed(() => (
|
||||
page.isShippingNoticeAgent
|
||||
&& batchWorkbenchOpen.value
|
||||
&& Boolean(page.conversationId || activeExtractionRunNo.value)
|
||||
&& Boolean(activeShippingConversationId.value)
|
||||
));
|
||||
|
||||
const compactShippingProgress = computed(() => batchWorkbenchOpen.value);
|
||||
@@ -178,7 +137,7 @@ function closeBatchWorkbench() {
|
||||
* 否则旧会话的右侧投影会短暂占用新会话的对话区并造成“本次处理”串批错觉。
|
||||
*/
|
||||
watch(
|
||||
() => [String(page.conversationId || ''), Number(page.currentAgentId || 0)] as const,
|
||||
() => [activeShippingConversationId.value, Number(page.currentAgentId || 0)] as const,
|
||||
(next, previous) => {
|
||||
if (!previous || next[0] === previous[0] && next[1] === previous[1]) return;
|
||||
batchWorkbenchOpen.value = false;
|
||||
@@ -694,7 +653,7 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
<ShippingWorkflowTimeline
|
||||
v-if="showShippingWorkflowTimeline"
|
||||
:conversation-id="page.conversationId"
|
||||
:conversation-id="activeShippingConversationId"
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingProcessing"
|
||||
|
||||
|
||||
@@ -112,16 +112,6 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
|
||||
@confirm="page.handleDeleteConfirm"
|
||||
@cancel="page.closeDeleteConfirmDialog"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-model="page.showRetryFailedConfirmDialog"
|
||||
:title="page.t('chat.shippingNoticeUi.retryFailedConfirmTitle')"
|
||||
:message="page.t('chat.shippingNoticeUi.retryFailedConfirmMessage')"
|
||||
:confirm-text="page.t('chat.shippingNoticeUi.retryFailedConfirmAction')"
|
||||
:confirm-loading="page.retryingShippingPendingTasks"
|
||||
confirm-tone="primary"
|
||||
@confirm="page.handleRetryFailedConfirm"
|
||||
@cancel="page.closeRetryFailedConfirm"
|
||||
/>
|
||||
<div
|
||||
v-if="page.shippingToastMessage"
|
||||
class="pointer-events-none fixed inset-x-0 top-20 z-[145] flex justify-center px-4"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/ShippingWorkflowStepper.vue
|
||||
* 用途:货代发货四阶段 Stepper 展示组件。
|
||||
* 用途:货代发货五阶段 Stepper 展示组件。
|
||||
* 依赖:shipping/shippingStepper、vue-i18n。
|
||||
* 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。
|
||||
*/
|
||||
@@ -33,7 +33,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4' : 'md:grid-cols-4'">
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-5' : 'md:grid-cols-5'">
|
||||
<div
|
||||
v-for="(step, index) in steps"
|
||||
:key="step.id"
|
||||
|
||||
+7
-3
@@ -167,7 +167,9 @@ const hasDiagnosticDetails = computed(() => Boolean(
|
||||
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
|
||||
<section
|
||||
class="rounded-lg border px-3 py-2 text-xs"
|
||||
:class="eligibility.can_build
|
||||
:class="eligibility.can_build === null
|
||||
? 'border-slate-200 bg-slate-50 text-slate-800 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100'
|
||||
: eligibility.can_build
|
||||
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100'
|
||||
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
|
||||
data-testid="review-eligibility-details-overall"
|
||||
@@ -175,8 +177,10 @@ const hasDiagnosticDetails = computed(() => Boolean(
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
|
||||
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
|
||||
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
|
||||
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build
|
||||
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build === null ? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-100' : eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
|
||||
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build === null
|
||||
? t('chat.shippingOrderReview.buildEligibility.notValidated')
|
||||
: eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span>
|
||||
</span>
|
||||
|
||||
+7
-2
@@ -153,6 +153,7 @@ const lowConfidenceFields = computed(() => props.eligibility?.issues?.flatMap((i
|
||||
) || []);
|
||||
const unexplainedBlocked = computed(() => Boolean(
|
||||
props.eligibility
|
||||
&& props.eligibility.status !== 'not_validated'
|
||||
&& props.eligibility.can_build === false
|
||||
&& !props.eligibility.issues?.length
|
||||
&& !props.eligibility.failed_gates?.length
|
||||
@@ -212,13 +213,17 @@ const gateChecklist = computed(() => {
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="eligibility.can_build
|
||||
:class="eligibility.can_build === null
|
||||
? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'
|
||||
: eligibility.can_build
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
|
||||
data-testid="review-build-eligibility-badge"
|
||||
>
|
||||
{{
|
||||
eligibility.can_build
|
||||
eligibility.status === 'not_validated'
|
||||
? t('chat.shippingOrderReview.buildEligibility.notValidated')
|
||||
: eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo')
|
||||
}}
|
||||
|
||||
+23
-6
@@ -19,9 +19,11 @@ const i18n = createI18n({
|
||||
shippingNotice: {
|
||||
processGate: {
|
||||
actionCodes: {
|
||||
reload_inventory_result: '重新读取库存结果',
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
},
|
||||
inventoryActions: {
|
||||
reloadInventoryResult: '重新读取库存结果',
|
||||
retryInventoryMatching: '重新库存匹配',
|
||||
retryInventoryPreparation: '重新获取库存',
|
||||
},
|
||||
@@ -33,7 +35,7 @@ const i18n = createI18n({
|
||||
},
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
saveOrderAndValidate: '保存订单并校验',
|
||||
saveOrderAndValidate: '提交订单',
|
||||
currentProcessing: {
|
||||
waitingStart: '等待系统启动',
|
||||
},
|
||||
@@ -69,7 +71,10 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
|
||||
it('keeps the retry action for retryable states', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: { stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true },
|
||||
props: {
|
||||
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
|
||||
primaryAction: { code: 'retry_inventory_preparation', i18nKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
@@ -77,6 +82,18 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('renders reload inventory result as the timeout primary action', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
|
||||
primaryAction: { code: 'reload_inventory_result' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新读取库存结果');
|
||||
});
|
||||
|
||||
it('hides the order-review entry when the user is already in the lifecycle workbench', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
@@ -104,7 +121,7 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新库存匹配');
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').text()).toBe('重新库存匹配');
|
||||
});
|
||||
|
||||
it('does not render save and validate as a current-task action', () => {
|
||||
@@ -116,9 +133,9 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 保存订单并校验是底栏唯一动作;未提交校验必须给出明确交接提示,不能显示系统处理中。
|
||||
// 提交订单是底栏唯一动作;未提交前必须给出明确交接提示,不能显示系统处理中。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('保存订单并校验');
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('提交订单');
|
||||
});
|
||||
|
||||
it('labels an unqueued automatic Gate as waiting for system start', () => {
|
||||
@@ -207,7 +224,7 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-current-processing-retry"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]').trigger('click');
|
||||
|
||||
// 两个稳定 action 码分别进入 Gate API:重匹配不可误触 RPA,重新获取库存才会触发 RPA。
|
||||
|
||||
+16
-21
@@ -62,7 +62,6 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
locate: [lineKey?: string | null, fieldId?: string | null];
|
||||
action: [code: string, parameters?: Record<string, unknown>];
|
||||
}>();
|
||||
@@ -219,8 +218,7 @@ function isNonTaskCapabilityAction(code: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务动作按钮:后端确认 retryable=true → 主按钮为「重试」;
|
||||
* 否则若 primary_action.code 非 retry 且不是工作台内自跳转 → 渲染对应人工动作。
|
||||
* 业务动作按钮只消费 primary_action;retryable 是状态,不是授权。
|
||||
*/
|
||||
const showBusinessAction = computed(() => {
|
||||
if (props.loading) return false;
|
||||
@@ -228,13 +226,12 @@ const showBusinessAction = computed(() => {
|
||||
// [STEP] 自动处理期间没有人工业务动作;只保留外层的刷新进度入口。
|
||||
// 防止正式任务编辑等历史 primary_action 穿透到库存获取运行态。
|
||||
if (props.userStatus === 'running') return false;
|
||||
if (props.retryable) return true;
|
||||
const code = String(props.primaryAction?.code || '').trim();
|
||||
if (isInternalInventoryAction(code)) return false;
|
||||
if (!code) return false;
|
||||
if (isNonTaskCapabilityAction(code)) return false;
|
||||
if (isHiddenWorkbenchNavigationAction(code)) return false;
|
||||
// retry 仅当 retryable=true 时展示(避免按钮闪烁矛盾)
|
||||
// 无对象边界的泛化 retry 永不展示。
|
||||
if (code === 'retry') return false;
|
||||
return true;
|
||||
});
|
||||
@@ -243,7 +240,6 @@ const businessActionLabel = computed(() => {
|
||||
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 '';
|
||||
@@ -257,11 +253,6 @@ const businessActionLabel = computed(() => {
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
}
|
||||
// fallback 到 legacy chat.shippingProcessing.action
|
||||
const legacyKey = `chat.shippingProcessing.action.${pa.code}`;
|
||||
if (te(legacyKey)) {
|
||||
return t(legacyKey);
|
||||
}
|
||||
// 当前任务按钮没有受控文案时 fail-closed,禁止泄漏内部 action code。
|
||||
return '';
|
||||
});
|
||||
@@ -274,7 +265,7 @@ const businessActionTitle = computed(() => {
|
||||
return '';
|
||||
});
|
||||
|
||||
const actionIsRetry = computed(() => Boolean(props.retryable) || String(props.primaryAction?.code || '') === 'retry');
|
||||
const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('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();
|
||||
@@ -301,14 +292,7 @@ function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): st
|
||||
|
||||
function handleBusinessActionClick() {
|
||||
const primaryActionCode = String(props.primaryAction?.code || '').trim();
|
||||
if (props.retryable && primaryActionCode && primaryActionCode !== 'retry') {
|
||||
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
|
||||
return;
|
||||
}
|
||||
if (actionIsRetry.value) {
|
||||
emit('retry');
|
||||
return;
|
||||
}
|
||||
if (!primaryActionCode || primaryActionCode === 'retry') return;
|
||||
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
|
||||
}
|
||||
|
||||
@@ -368,7 +352,18 @@ type ReviewCurrentUserStatus =
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentProcessing.status') }}</dt>
|
||||
<dd data-testid="review-current-task-status" :class="loading ? 'animate-pulse' : ''">{{ statusLabel }}</dd>
|
||||
<dd
|
||||
class="inline-flex items-center gap-1"
|
||||
data-testid="review-current-task-status"
|
||||
:class="loading ? 'animate-pulse' : ''"
|
||||
>
|
||||
<RefreshCw
|
||||
v-if="userStatus === 'running' && !loading"
|
||||
class="h-3 w-3 animate-spin"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{{ statusLabel }}
|
||||
</dd>
|
||||
</div>
|
||||
<div
|
||||
v-if="hasFormalOt && shippingNoticeNo"
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts
|
||||
* 用途:锁定唯一标准客户候选的工作台提示,避免将可自动确认状态误报为未识别。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel。
|
||||
* 逻辑:unique_candidate 显示自动确认说明和明确按钮;其他未确认状态维持人工选择入口。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewCustomerResolutionPanel from './ReviewCustomerResolutionPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingCustomer: { loadFailed: '加载失败', confirmFailed: '确认失败' },
|
||||
shippingOrderReview: {
|
||||
customerResolution: {
|
||||
title: '客户确认', subtitle: '请选择标准客户', uniqueCandidateHint: '已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。',
|
||||
confirmUniqueCandidate: '确认唯一候选', selectCustomer: '选择标准客户', retrying: '识别中…', retryCustomer: '重新识别客户',
|
||||
retryDone: '已重新识别客户', retryFailed: '重新识别客户失败', confirmed: '客户已确认', confirmReason: '人工确认',
|
||||
standardCustomer: '标准客户', customerCode: '客户编码', matchedInputs: '匹配输入', candidates: '候选客户', pdfReparseHint: '请重新识别 PDF',
|
||||
inputLabels: { customerCode: '客户编码', customerName: '客户名称', address: '地址', email: '邮箱', domain: '域名', other: '其他' },
|
||||
status: { unique_candidate: '唯一候选', unmatched: '未匹配', confirmed: '已确认' },
|
||||
},
|
||||
resume: { autoCreated: '已自动建单', waitingManualConfirm: '等待人工确认' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function mountPanel(status: string) {
|
||||
return mount(ReviewCustomerResolutionPanel, {
|
||||
props: {
|
||||
caseNo: 'CASE-CUSTOMER-1',
|
||||
editable: true,
|
||||
resolution: { resolved: false, status, raw_name: 'ACME' },
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: { ShippingCustomerConfirmDialog: true },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewCustomerResolutionPanel', () => {
|
||||
it('唯一候选展示自动确认说明和明确确认入口', () => {
|
||||
const wrapper = mountPanel('unique_candidate');
|
||||
|
||||
expect(wrapper.text()).toContain('保存校验时系统会自动确认');
|
||||
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('确认唯一候选');
|
||||
});
|
||||
|
||||
it('非唯一未确认状态维持人工选择客户入口', () => {
|
||||
const wrapper = mountPanel('unmatched');
|
||||
|
||||
expect(wrapper.text()).not.toContain('保存校验时系统会自动确认');
|
||||
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('选择标准客户');
|
||||
});
|
||||
});
|
||||
+12
-2
@@ -41,6 +41,10 @@ const options = ref<ShippingCustomerOption[]>([]);
|
||||
const loadingOptions = ref(false);
|
||||
|
||||
const resolved = computed(() => Boolean(props.resolution?.resolved));
|
||||
const hasUniqueCandidate = computed(() => (
|
||||
!resolved.value
|
||||
&& String(props.resolution?.status || '').trim() === 'unique_candidate'
|
||||
));
|
||||
const statusLabel = computed(() => {
|
||||
const status = String(props.resolution?.status || '').trim();
|
||||
if (!status) {
|
||||
@@ -198,7 +202,11 @@ async function onRetry() {
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.customerResolution.subtitle') }}</p>
|
||||
<p class="mt-0.5 text-xs text-muted">
|
||||
{{ hasUniqueCandidate
|
||||
? t('chat.shippingOrderReview.customerResolution.uniqueCandidateHint')
|
||||
: t('chat.shippingOrderReview.customerResolution.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
@@ -244,7 +252,9 @@ async function onRetry() {
|
||||
:disabled="busy"
|
||||
@click="openSelectDialog"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
|
||||
{{ hasUniqueCandidate
|
||||
? t('chat.shippingOrderReview.customerResolution.confirmUniqueCandidate')
|
||||
: t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -30,7 +30,7 @@ export type ReviewDocumentNavItem = {
|
||||
lifecycle_stage?: ReviewLifecycleStageCode | null;
|
||||
};
|
||||
|
||||
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
|
||||
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
|
||||
|
||||
@@ -112,7 +112,7 @@ function caseStatusLabel(status: string): string {
|
||||
/** 后端阶段码只做 i18n 投影;缺失时保留空白,禁止按 Case 状态补造阶段。 */
|
||||
function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
|
||||
const code = String(item.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
|
||||
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(code)) return null;
|
||||
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(code)) return null;
|
||||
const key = `chat.shippingOrderReview.lifecycle.stages.${code}`;
|
||||
return te(key) ? t(key) : null;
|
||||
}
|
||||
|
||||
+16
-1
@@ -31,7 +31,8 @@ const i18n = createI18n({
|
||||
customValue: '手工值', customPlaceholder: '请输入', submitCustom: '确认手工值',
|
||||
resolveReason: '人工裁决', resolveFailed: '提交失败', resolveSuccess: '已处理',
|
||||
fields: { part_number: '料号' }, reasons: { field_conflict: '字段冲突' },
|
||||
evidenceRole: {}, optionLabel: '候选 {index}', adoptOption: '采用候选值',
|
||||
evidenceRole: {}, recoveryAction: { reparse_current_pdf: '建议操作:重新识别此 PDF' },
|
||||
optionLabel: '候选 {index}', adoptOption: '采用候选值',
|
||||
},
|
||||
resume: { autoCreated: '已自动建单', waitingManualConfirm: '待人工确认' },
|
||||
} },
|
||||
@@ -57,6 +58,20 @@ describe('ReviewFieldConflictPanel', () => {
|
||||
expect(wrapper.find('[data-testid="review-field-conflict-custom-toggle"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows the server-provided recovery action for a historical evidence gap', () => {
|
||||
const wrapper = mount(ReviewFieldConflictPanel, {
|
||||
props: {
|
||||
caseNo: 'SORC-1', draftVersion: 1, editable: true, conflicts: [],
|
||||
evidenceIssues: [{
|
||||
conflict_key: '-1:unit_price', field_code: 'unit_price', reason: 'supplement_conflict_evidence_insufficient',
|
||||
options: [], recovery_action: 'reparse_current_pdf',
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.get('[data-testid="review-evidence-issue-recovery-action"]').text()).toContain('重新识别此 PDF');
|
||||
});
|
||||
|
||||
it('refreshes the case when confirming a stale manual value returns conflict-not-found', async () => {
|
||||
resolveFieldConflict.mockRejectedValueOnce(new BusinessError({
|
||||
message: 'Field conflict not found',
|
||||
|
||||
@@ -73,6 +73,16 @@ function evidenceRoleLabel(role: string | undefined | null): string {
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示服务端指定的恢复动作;页面只解释并复用既有顶部操作,不自行发起重识别。
|
||||
*/
|
||||
function recoveryActionLabel(action: string | undefined | null): string {
|
||||
const code = String(action || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `chat.shippingOrderReview.fieldConflict.recoveryAction.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定位冲突字段到草稿/证据区。
|
||||
*/
|
||||
@@ -311,6 +321,13 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
<span class="text-muted">{{ scopeLabel(issue.scope) }} · </span>
|
||||
<span class="font-mono">{{ fieldLabel(issue.field_code) }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="recoveryActionLabel(issue.recovery_action)"
|
||||
class="text-[11px] text-amber-800 dark:text-amber-200"
|
||||
data-testid="review-evidence-issue-recovery-action"
|
||||
>
|
||||
{{ recoveryActionLabel(issue.recovery_action) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="text-[11px] text-primary underline-offset-2 hover:underline"
|
||||
|
||||
+18
-263
@@ -1,275 +1,30 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewFulfillmentDecisionPanel.vue
|
||||
用途:复核工作台行级履约决定(等待补货 / 完整行先行 / 关闭)。
|
||||
依赖:vue-i18n、decide/wave line-fulfillment API、showReviewResumeOutcome。
|
||||
逻辑:分列展示料号/需求数量/可用数量/预约单号/状态;禁止 part_number 回退预约单号;
|
||||
逐行决定;选中 fulfill 行可确认波次;关闭 emit open-close-dialog。
|
||||
-->
|
||||
<!-- 履约摘要侧栏;完整明细与批量出单统一由主库存表承载。 -->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
waveWorkspaceShippingOrderReviewLineFulfillment,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
import type {
|
||||
ShippingOrderReviewLineFulfillment,
|
||||
ShippingOrderReviewLineFulfillmentDecisionCode,
|
||||
ShippingOrderReviewLineFulfillmentLine,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
caseNo: string;
|
||||
draftVersion: number | null | undefined;
|
||||
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
|
||||
editable: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
'open-close-dialog': [lineKeys: string[]];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const busyKey = ref<string | null>(null);
|
||||
const selectedFulfillKeys = ref<string[]>([]);
|
||||
const waveBusy = ref(false);
|
||||
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{ caseNo: string; draftVersion: number | null | undefined; lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined; editable: boolean }>();
|
||||
const emit = defineEmits<{ refreshed: []; 'open-close-dialog': [lineKeys: string[]] }>();
|
||||
const { t } = useI18n();
|
||||
const TERMINAL_STATUSES = new Set(['task_created', 'fulfilled', 'closed_unfulfillable']);
|
||||
|
||||
const visible = computed(() => Boolean(
|
||||
props.lineFulfillment?.has_open_lines
|
||||
|| props.lineFulfillment?.has_shortage,
|
||||
));
|
||||
|
||||
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter(
|
||||
(line) => !TERMINAL_STATUSES.has(String(line.line_status || '')),
|
||||
));
|
||||
|
||||
/**
|
||||
* 行状态本地化。
|
||||
*/
|
||||
function lineStatusLabel(status: string | null | undefined): string {
|
||||
const normalized = String(status || 'pending_decision').trim();
|
||||
const key = `chat.shippingOrderReview.fulfillmentDecision.lineStatus.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换 fulfill 波次选中行。
|
||||
*/
|
||||
function toggleFulfillSelection(lineKey: string, checked: boolean) {
|
||||
const set = new Set(selectedFulfillKeys.value);
|
||||
if (checked) set.add(lineKey);
|
||||
else set.delete(lineKey);
|
||||
selectedFulfillKeys.value = [...set];
|
||||
}
|
||||
|
||||
/**
|
||||
* 行是否可选入 fulfill 波次。
|
||||
*/
|
||||
function canSelectForWave(line: ShippingOrderReviewLineFulfillmentLine): boolean {
|
||||
if (TERMINAL_STATUSES.has(String(line.line_status || ''))) return false;
|
||||
return Boolean(line.can_fulfill_complete_line);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入单行履约决定。
|
||||
*/
|
||||
async function onDecide(
|
||||
line: ShippingOrderReviewLineFulfillmentLine,
|
||||
decisionCode: ShippingOrderReviewLineFulfillmentDecisionCode,
|
||||
) {
|
||||
if (!props.caseNo || !props.editable || busyKey.value) return;
|
||||
if (decisionCode === 'close_unfulfillable') {
|
||||
emit('open-close-dialog', [line.line_key]);
|
||||
return;
|
||||
}
|
||||
busyKey.value = line.line_key;
|
||||
try {
|
||||
const result = await decideWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
|
||||
line_key: line.line_key,
|
||||
decision_code: decisionCode,
|
||||
expected_draft_version: props.draftVersion ?? undefined,
|
||||
});
|
||||
showReviewResumeOutcome(
|
||||
result.resume_outcome,
|
||||
msg,
|
||||
t,
|
||||
t('chat.shippingOrderReview.fulfillmentDecision.decideSuccess'),
|
||||
);
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.decideFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busyKey.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为选中完整行创建履约波次 Task。
|
||||
*/
|
||||
async function onConfirmWave() {
|
||||
if (!props.caseNo || props.draftVersion == null || waveBusy.value || !selectedFulfillKeys.value.length) return;
|
||||
waveBusy.value = true;
|
||||
try {
|
||||
const idempotencyKey = `review-wave-${props.caseNo}-${Date.now()}-${selectedFulfillKeys.value.sort().join(',')}`;
|
||||
const result = await waveWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
|
||||
line_keys: [...selectedFulfillKeys.value],
|
||||
expected_draft_version: props.draftVersion,
|
||||
idempotency_key: idempotencyKey,
|
||||
});
|
||||
showReviewResumeOutcome(
|
||||
result.resume_outcome,
|
||||
msg,
|
||||
t,
|
||||
t('chat.shippingOrderReview.fulfillmentDecision.waveSuccess', {
|
||||
taskNo: result.task_no || '',
|
||||
}),
|
||||
);
|
||||
selectedFulfillKeys.value = [];
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.waveFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
waveBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开关闭剩余行对话框(全部开放行)。
|
||||
*/
|
||||
function onCloseRemaining() {
|
||||
const keys = openLines.value.map((line) => line.line_key);
|
||||
emit('open-close-dialog', keys);
|
||||
}
|
||||
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter((line) => !TERMINAL_STATUSES.has(String(line.line_status || ''))));
|
||||
const visible = computed(() => Boolean(props.lineFulfillment?.has_open_lines || props.lineFulfillment?.has_shortage));
|
||||
function onCloseRemaining() { emit('open-close-dialog', openLines.value.map((line) => line.line_key)); }
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
|
||||
data-testid="review-fulfillment-decision-panel"
|
||||
>
|
||||
<section v-if="visible" class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40" data-testid="review-fulfillment-decision-panel">
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span class="rounded-full bg-sky-100 px-2.5 py-1 text-xs font-medium text-sky-900 dark:bg-sky-950 dark:text-sky-100">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: lineFulfillment?.open_count ?? openLines.length }) }}
|
||||
</span>
|
||||
<div><h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}</h2><p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">{{ t('chat.shippingOrderReview.fulfillmentDecision.railHint') }}</p></div>
|
||||
<span class="rounded-full bg-sky-100 px-2.5 py-1 text-xs font-medium text-sky-900 dark:bg-sky-950 dark:text-sky-100">{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: lineFulfillment?.open_count ?? openLines.length }) }}</span>
|
||||
</header>
|
||||
|
||||
<div class="mt-2 overflow-x-auto">
|
||||
<table class="min-w-full text-left text-xs">
|
||||
<thead class="text-muted">
|
||||
<tr>
|
||||
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.waveSelect') }}</th>
|
||||
<th class="px-1 py-1 font-medium">#</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.partNumber') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.requiredQty') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.reservationId') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.status') }}</th>
|
||||
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="line in lineFulfillment?.lines || []"
|
||||
:key="line.line_key"
|
||||
class="border-t border-sky-100 dark:border-sky-900"
|
||||
>
|
||||
<td v-if="editable" class="px-1 py-1">
|
||||
<input
|
||||
v-if="canSelectForWave(line)"
|
||||
type="checkbox"
|
||||
class="rounded border-default"
|
||||
:checked="selectedFulfillKeys.includes(line.line_key)"
|
||||
:data-testid="`review-fulfill-select-${line.line_key}`"
|
||||
@change="toggleFulfillSelection(line.line_key, ($event.target as HTMLInputElement).checked)"
|
||||
>
|
||||
</td>
|
||||
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
|
||||
<td class="px-1 py-1 font-mono" data-testid="review-fulfill-part-number">
|
||||
{{ line.part_number || t('chat.shippingOrderReview.fulfillmentDecision.partUnrecognized') }}
|
||||
</td>
|
||||
<td class="px-1 py-1">{{ line.required_qty ?? '—' }}</td>
|
||||
<td class="px-1 py-1">{{ line.available_qty ?? '—' }}</td>
|
||||
<td class="px-1 py-1 font-mono">{{ line.reservation_id || '—' }}</td>
|
||||
<td class="px-1 py-1">{{ lineStatusLabel(line.line_status) }}</td>
|
||||
<td v-if="editable && !TERMINAL_STATUSES.has(String(line.line_status || ''))" class="px-1 py-1">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-sky-300 px-2 py-1 text-xs hover:bg-sky-100 disabled:opacity-50 dark:border-sky-800 dark:hover:bg-sky-950"
|
||||
:disabled="busyKey != null"
|
||||
@click="onDecide(line, 'wait_inventory')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.waitInventory') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="line.can_fulfill_complete_line"
|
||||
type="button"
|
||||
class="rounded border border-emerald-300 px-2 py-1 text-xs hover:bg-emerald-50 disabled:opacity-50 dark:border-emerald-800 dark:hover:bg-emerald-950"
|
||||
:disabled="busyKey != null"
|
||||
@click="onDecide(line, 'fulfill_complete_line_now')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.fulfillNow') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-rose-300 px-2 py-1 text-xs text-rose-800 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-800 dark:text-rose-200 dark:hover:bg-rose-950"
|
||||
:disabled="busyKey != null"
|
||||
@click="onDecide(line, 'close_unfulfillable')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeLine') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
<td v-else-if="editable" class="px-1 py-1 text-muted">—</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-60"
|
||||
data-testid="review-fulfillment-confirm-wave"
|
||||
:disabled="waveBusy || !selectedFulfillKeys.length || draftVersion == null"
|
||||
@click="onConfirmWave"
|
||||
>
|
||||
{{ waveBusy
|
||||
? t('chat.shippingOrderReview.fulfillmentDecision.waving')
|
||||
: t('chat.shippingOrderReview.fulfillmentDecision.confirmWave', { count: selectedFulfillKeys.length }) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="openLines.length"
|
||||
type="button"
|
||||
class="rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 disabled:opacity-60 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200"
|
||||
data-testid="review-fulfillment-close-remaining"
|
||||
:disabled="waveBusy || busyKey != null"
|
||||
@click="onCloseRemaining"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}
|
||||
</button>
|
||||
<div class="mt-2 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.readyCount', { count: lineFulfillment?.ready_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortageCount', { count: lineFulfillment?.manual_pending_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.autoProgressCount', { count: lineFulfillment?.auto_progress_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.summaryHint') }}</div>
|
||||
</div>
|
||||
<div v-if="editable && openLines.length" class="mt-3"><button type="button" class="rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200" data-testid="review-fulfillment-close-remaining" @click="onCloseRemaining">{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}</button></div>
|
||||
</section>
|
||||
</template>
|
||||
+38
-2
@@ -17,10 +17,12 @@ const i18n = createI18n({
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingNoticeRetryParse: '重试解析',
|
||||
shippingOrderReview: {
|
||||
lifecycle: {
|
||||
navigation: '订单生命周期阶段',
|
||||
current: '当前可处理',
|
||||
processing: '处理中',
|
||||
completed: '已完成,可查看',
|
||||
blocked: '前置未完成',
|
||||
},
|
||||
@@ -33,18 +35,43 @@ const i18n = createI18n({
|
||||
const stages: ReviewLifecycleStageItem[] = [
|
||||
{ code: 'order_review', label: '订单复核', state: 'completed' },
|
||||
{ code: 'fulfillment_prep', label: '通知准备', state: 'current' },
|
||||
{ code: 'freight_upload', label: '货代上传', state: 'blocked', reason: '请先完成通知准备' },
|
||||
{ code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' },
|
||||
];
|
||||
|
||||
/** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */
|
||||
function mountNavigation() {
|
||||
return mount(ReviewLifecycleStageNavigation, {
|
||||
props: { stages, activeCode: 'fulfillment_prep' },
|
||||
props: { stages, activeCode: 'fulfillment_prep', processingCode: 'fulfillment_prep' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewLifecycleStageNavigation', () => {
|
||||
it('only exposes retry_parse on the current intake stage when the server authorizes it', async () => {
|
||||
const wrapper = mount(ReviewLifecycleStageNavigation, {
|
||||
props: {
|
||||
stages: [
|
||||
{ code: 'intake_parse', label: '接收解析', state: 'current' },
|
||||
...stages,
|
||||
],
|
||||
activeCode: 'intake_parse',
|
||||
availableActions: ['retry_parse'],
|
||||
retrying: false,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:重试入口必须位于已发送文件的当前阶段卡,且完全由后端动作授权。
|
||||
const retry = wrapper.get('[data-testid="review-lifecycle-stage-retry-parse"]');
|
||||
expect(retry.text()).toContain('重试解析');
|
||||
await retry.trigger('click');
|
||||
expect(wrapper.emitted('retry-parse')).toEqual([[]]);
|
||||
|
||||
await wrapper.setProps({ availableActions: [] });
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-retry-parse"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders intake_parse as the first lifecycle stage', () => {
|
||||
const wrapper = mount(ReviewLifecycleStageNavigation, {
|
||||
props: {
|
||||
@@ -63,9 +90,10 @@ describe('ReviewLifecycleStageNavigation', () => {
|
||||
'review-lifecycle-stage-intake_parse',
|
||||
'review-lifecycle-stage-order_review',
|
||||
'review-lifecycle-stage-fulfillment_prep',
|
||||
'review-lifecycle-stage-freight_upload',
|
||||
'review-lifecycle-stage-upload_complete',
|
||||
]);
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-4');
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-5');
|
||||
});
|
||||
|
||||
it('allows opening a completed stage for inspection', async () => {
|
||||
@@ -75,6 +103,14 @@ describe('ReviewLifecycleStageNavigation', () => {
|
||||
expect(wrapper.emitted('select')).toEqual([['order_review']]);
|
||||
});
|
||||
|
||||
it('shows a spinner and processing label on the active stage while automation runs', () => {
|
||||
const wrapper = mountNavigation();
|
||||
const stage = wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]');
|
||||
expect(stage.attributes('data-processing')).toBe('1');
|
||||
expect(stage.text()).toContain('处理中');
|
||||
expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('disables a future stage and does not emit a selection', async () => {
|
||||
const wrapper = mountNavigation();
|
||||
const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
|
||||
|
||||
+38
-5
@@ -1,13 +1,13 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue
|
||||
用途:订单生命周期工作台的四阶段导航,只呈现父级已裁决的阶段状态。
|
||||
用途:订单生命周期工作台的五阶段导航,只呈现父级已裁决的阶段状态。
|
||||
依赖:父级 ShippingOrderReviewView 提供阶段、状态和阻断原因;lucide-vue-next 图标。
|
||||
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { Check, LockKeyhole } from 'lucide-vue-next';
|
||||
import { Check, LockKeyhole, RefreshCw } from 'lucide-vue-next';
|
||||
|
||||
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
|
||||
|
||||
export interface ReviewLifecycleStageItem {
|
||||
@@ -21,13 +21,27 @@ const props = defineProps<{
|
||||
stages: ReviewLifecycleStageItem[];
|
||||
/** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */
|
||||
activeCode: ReviewLifecycleStageCode | null;
|
||||
/** 仅消费当前对象后端下发的恢复动作,禁止按阶段或状态由前端猜测。 */
|
||||
availableActions?: string[];
|
||||
/** 当前阶段正在执行自动推进时的技术阶段码;只影响展示,不授权动作。 */
|
||||
processingCode?: ReviewLifecycleStageCode | null;
|
||||
/** retry_parse 请求中的互斥状态,避免用户重复提交。 */
|
||||
retrying?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [code: ReviewLifecycleStageCode];
|
||||
'open-detail': [code: ReviewLifecycleStageCode];
|
||||
'retry-parse': [];
|
||||
}>();
|
||||
|
||||
/** 接收解析的恢复只在后端明确授权且该阶段为当前阶段时展示。 */
|
||||
function canRetryParse(stage: ReviewLifecycleStageItem): boolean {
|
||||
return stage.code === 'intake_parse'
|
||||
&& stage.state === 'current'
|
||||
&& (props.availableActions || []).includes('retry_parse');
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。
|
||||
*/
|
||||
@@ -43,7 +57,7 @@ function selectStage(stage: ReviewLifecycleStageItem) {
|
||||
:aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')"
|
||||
data-testid="review-lifecycle-stage-navigation"
|
||||
>
|
||||
<div class="grid gap-2 sm:grid-cols-4">
|
||||
<div class="grid gap-2 sm:grid-cols-5">
|
||||
<div
|
||||
v-for="stage in props.stages"
|
||||
:key="stage.code"
|
||||
@@ -55,8 +69,15 @@ function selectStage(stage: ReviewLifecycleStageItem) {
|
||||
stage.state === 'blocked' ? 'opacity-60' : '',
|
||||
]"
|
||||
:data-testid="`review-lifecycle-stage-${stage.code}`"
|
||||
:data-processing="stage.code === props.processingCode ? '1' : '0'"
|
||||
>
|
||||
<span class="flex items-center gap-2 text-sm font-semibold">
|
||||
<RefreshCw
|
||||
v-if="stage.code === props.processingCode"
|
||||
class="h-4 w-4 shrink-0 animate-spin text-brand-600"
|
||||
data-testid="review-lifecycle-stage-spinner"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Check v-if="stage.state === 'completed'" class="h-4 w-4 shrink-0 text-emerald-600" />
|
||||
<LockKeyhole v-else-if="stage.state === 'blocked'" class="h-4 w-4 shrink-0 text-muted" />
|
||||
<span v-else class="h-2 w-2 shrink-0 rounded-full bg-brand-600" aria-hidden="true" />
|
||||
@@ -76,11 +97,23 @@ function selectStage(stage: ReviewLifecycleStageItem) {
|
||||
@click="selectStage(stage)"
|
||||
>
|
||||
{{ stage.state === 'current'
|
||||
? $t('chat.shippingOrderReview.lifecycle.current')
|
||||
? (stage.code === props.processingCode
|
||||
? $t('chat.shippingOrderReview.lifecycle.processing')
|
||||
: $t('chat.shippingOrderReview.lifecycle.current'))
|
||||
: stage.state === 'completed'
|
||||
? $t('chat.shippingOrderReview.lifecycle.completed')
|
||||
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canRetryParse(stage)"
|
||||
type="button"
|
||||
class="mt-2 rounded border border-brand-300 px-2 py-1 text-xs font-medium text-brand-700 hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-brand-700 dark:text-brand-200 dark:hover:bg-brand-950/40"
|
||||
data-testid="review-lifecycle-stage-retry-parse"
|
||||
:disabled="props.retrying === true"
|
||||
@click="emit('retry-parse')"
|
||||
>
|
||||
{{ $t('chat.shippingNoticeRetryParse') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
@@ -18,6 +18,11 @@ const i18n = createI18n({
|
||||
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
|
||||
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
|
||||
routeType: '路由类型', executionMode: '执行模式',
|
||||
extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断', extractionBlockedReason: '阻断原因:{reasons}',
|
||||
coordinateModel: {
|
||||
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
|
||||
translateY: '纵向平移', reasonCodes: '原因码',
|
||||
},
|
||||
status: { matched: '已匹配', ambiguous: '多个候选' },
|
||||
} } },
|
||||
},
|
||||
@@ -44,6 +49,34 @@ function mountPanel(needsReview = false) {
|
||||
});
|
||||
}
|
||||
|
||||
function mountAnchorFramePanel(visibility: 'admin' | 'admin_only' = 'admin') {
|
||||
return mount(ReviewProfileMatchPanel, {
|
||||
props: {
|
||||
profileMatch: {
|
||||
available: true,
|
||||
visibility,
|
||||
status: 'unique_match',
|
||||
needs_review: false,
|
||||
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
|
||||
candidates: [{
|
||||
profile_code: 'ODP-A',
|
||||
version: 1,
|
||||
display_name: '客户订单模板',
|
||||
score: 0.99,
|
||||
coordinate_transform: {
|
||||
status: 'applied',
|
||||
translate_x: 0.001,
|
||||
translate_y: 0.03,
|
||||
reason_codes: [],
|
||||
},
|
||||
}],
|
||||
fallback_reason_codes: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewProfileMatchPanel', () => {
|
||||
it('默认收起无需关注的候选列表', () => {
|
||||
const wrapper = mountPanel(false);
|
||||
@@ -69,4 +102,44 @@ describe('ReviewProfileMatchPanel', () => {
|
||||
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');
|
||||
});
|
||||
|
||||
it('唯一命中时仍展示下游字段提取门禁的阻断原因', () => {
|
||||
const wrapper = mount(ReviewProfileMatchPanel, {
|
||||
props: {
|
||||
profileMatch: {
|
||||
available: true,
|
||||
visibility: 'admin',
|
||||
status: 'unique_match',
|
||||
needs_review: true,
|
||||
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
|
||||
candidates: [{ profile_code: 'ODP-A', display_name: '客户订单模板', score: 0.99 }],
|
||||
fallback_reason_codes: ['PARSE_STRATEGY_ROW_MODE_AMBIGUOUS'],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:唯一模板命中不等于字段已提取,必须明确暴露下游阻断原因。
|
||||
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
|
||||
.toContain('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS');
|
||||
});
|
||||
|
||||
it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => {
|
||||
const wrapper = mountAnchorFramePanel();
|
||||
|
||||
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
|
||||
|
||||
const details = wrapper.get('[data-testid="review-profile-match-details"]');
|
||||
expect(details.text()).toContain('锚点坐标框架');
|
||||
expect(details.text()).toContain('纵向平移');
|
||||
expect(details.text()).toContain('0.03');
|
||||
expect(details.text()).not.toContain('ORDER NO.');
|
||||
expect(details.text()).not.toContain('x0');
|
||||
});
|
||||
|
||||
it('非管理员不可见锚点框架技术详情', async () => {
|
||||
const wrapper = mountAnchorFramePanel('admin_only');
|
||||
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-profile-match-coordinate-transform"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,23 @@ const candidateCount = computed(() => (props.profileMatch?.candidates || []).len
|
||||
const defaultCandidatesExpanded = computed(() => false);
|
||||
const candidatesOpenOverride = ref<boolean | null>(null);
|
||||
const candidatesExpanded = computed(() => candidatesOpenOverride.value ?? defaultCandidatesExpanded.value);
|
||||
const selectedCoordinateTransform = computed(() => {
|
||||
if (!isAdminView.value) return null;
|
||||
const selectedCode = String(props.profileMatch?.selected_profile?.profile_code || '');
|
||||
const selectedVersion = props.profileMatch?.selected_profile?.version;
|
||||
const candidate = (props.profileMatch?.candidates || []).find((item) => (
|
||||
item.profile_code === selectedCode
|
||||
&& (selectedVersion == null || item.version === selectedVersion)
|
||||
));
|
||||
return candidate?.coordinate_transform || null;
|
||||
});
|
||||
const coordinateTransformReasonCodes = computed(() => (
|
||||
selectedCoordinateTransform.value?.reason_codes || []
|
||||
));
|
||||
/** 唯一命中仅证明版式身份;下游字段/明细恢复若受门禁阻断,必须在同卡明确说明。 */
|
||||
const extractionBlockReasons = computed(() => (
|
||||
(props.profileMatch?.fallback_reason_codes || []).filter((code) => String(code).trim())
|
||||
));
|
||||
|
||||
watch(
|
||||
() => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`,
|
||||
@@ -95,6 +112,17 @@ const selectedLabel = computed(() => {
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div
|
||||
v-if="extractionBlockReasons.length"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-profile-match-extraction-blocked"
|
||||
>
|
||||
<p class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.extractionBlocked') }}</p>
|
||||
<p class="mt-1 text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.profileMatch.extractionBlockedReason', { reasons: extractionBlockReasons.join(', ') }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<template v-if="isAdminView && candidateCount">
|
||||
<button
|
||||
type="button"
|
||||
@@ -118,6 +146,17 @@ const selectedLabel = computed(() => {
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
|
||||
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
|
||||
</div>
|
||||
<div v-if="selectedCoordinateTransform" data-testid="review-profile-match-coordinate-transform" class="mt-2 rounded-lg border border-sky-200 bg-sky-50 px-2.5 py-2 text-[11px] text-sky-950 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-100">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.anchorFrame') }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1">
|
||||
<span>{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.status') }}: {{ selectedCoordinateTransform.status }}</span>
|
||||
<span v-if="selectedCoordinateTransform.translate_x != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateX') }}: {{ selectedCoordinateTransform.translate_x }}</span>
|
||||
<span v-if="selectedCoordinateTransform.translate_y != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateY') }}: {{ selectedCoordinateTransform.translate_y }}</span>
|
||||
</div>
|
||||
<div v-if="coordinateTransformReasonCodes.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.reasonCodes') }}: {{ coordinateTransformReasonCodes.join(', ') }}
|
||||
</div>
|
||||
</div>
|
||||
</dl>
|
||||
<ul
|
||||
class="mt-2 max-h-48 space-y-1.5 overflow-y-auto pr-1"
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewReservationPanel.spec.ts
|
||||
* 用途:验证 Reservation 校验面板只展示问题与重新校验入口,不重复提供明细编辑入口。
|
||||
* 依赖:Vue Test Utils、vue-i18n、Reservation 重校验 API。
|
||||
* 逻辑:挂载存在异常的 Reservation 面板,确认问题文案与重新校验按钮保留,编辑按钮不再出现。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ReviewReservationPanel from './ReviewReservationPanel.vue';
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
revalidateWorkspaceShippingOrderReviewReservation: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn(), info: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/shipping-review/showReviewResumeOutcome', () => ({
|
||||
showReviewResumeOutcome: vi.fn(),
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { chat: chatZhCn } },
|
||||
});
|
||||
|
||||
describe('ReviewReservationPanel', () => {
|
||||
it('只保留校验提示和重新校验入口,不重复提供明细编辑按钮', () => {
|
||||
const wrapper = mount(ReviewReservationPanel, {
|
||||
props: {
|
||||
caseNo: 'CASE-1',
|
||||
draftVersion: 3,
|
||||
editable: true,
|
||||
reservation: {
|
||||
needs_attention: true,
|
||||
status: 'needs_attention',
|
||||
issues: [{ code: 'reservation_missing', severity: 'blocking', line_index: 0 }],
|
||||
lines: [{
|
||||
line_key: 'line-1',
|
||||
line_index: 0,
|
||||
effective_reservation_id: null,
|
||||
needs_attention: true,
|
||||
block_reason: 'reservation_missing',
|
||||
}],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('缺少预约单号');
|
||||
expect(wrapper.get('[data-testid="review-reservation-revalidate"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-reservation-focus-line"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('编辑此行');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
features/chat/components/shipping-review/ReviewReservationPanel.vue
|
||||
用途:复核工作台 Reservation 校验摘要;展示行级有效预约号与阻断 issue。
|
||||
依赖:vue-i18n、revalidateWorkspaceShippingOrderReviewReservation、showReviewResumeOutcome。
|
||||
逻辑:needs_attention 时展示;编辑聚焦明细行;重校验后 emit refreshed 并展示 resume 提示。
|
||||
逻辑:needs_attention 时展示问题;左侧订单明细是唯一编辑位置;重校验后 emit refreshed 并展示 resume 提示。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -20,10 +20,7 @@ const props = defineProps<{
|
||||
editable: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
'focus-line': [lineIndex: number];
|
||||
}>();
|
||||
const emit = defineEmits<{ refreshed: [] }>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
@@ -55,14 +52,6 @@ function issueLabel(code: string | null | undefined): string {
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚焦明细行以便编辑 reservation_id。
|
||||
*/
|
||||
function onFocusLine(lineIndex: number | null | undefined) {
|
||||
if (lineIndex == null || !Number.isFinite(Number(lineIndex))) return;
|
||||
emit('focus-line', Number(lineIndex));
|
||||
}
|
||||
|
||||
/**
|
||||
* 显式重校验 Reservation 并刷新 Case / 建单资格。
|
||||
*/
|
||||
@@ -128,13 +117,16 @@ async function onRevalidate() {
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<p v-if="editable" class="mt-2 text-xs text-violet-900 dark:text-violet-200">
|
||||
{{ t('chat.shippingOrderReview.reservation.editHint') }}
|
||||
</p>
|
||||
|
||||
<div v-if="lines.length" class="mt-2 overflow-x-auto">
|
||||
<table class="min-w-full text-left text-xs">
|
||||
<thead class="text-muted">
|
||||
<tr>
|
||||
<th class="px-1 py-1 font-medium">#</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.reservationId') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -151,17 +143,6 @@ async function onRevalidate() {
|
||||
{{ issueLabel(line.block_reason) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-1 py-1">
|
||||
<button
|
||||
v-if="editable && line.line_index != null"
|
||||
type="button"
|
||||
class="text-[11px] text-primary underline-offset-2 hover:underline"
|
||||
data-testid="review-reservation-focus-line"
|
||||
@click="onFocusLine(line.line_index)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.reservation.editLine') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
+19
-2
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/shipping-review/ReviewWorkbenchFooter.spec.ts
|
||||
* 用途:验证字段冲突的 Gate 主动作只由右栏当前任务卡承载,底栏不得重复展示。
|
||||
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewWorkbenchFooter。
|
||||
* 逻辑:订单复核底栏只保留保存校验,不展示已由当前任务卡或阶段页承载的流程动作。
|
||||
* 逻辑:订单复核底栏只保留提交订单,不展示已由当前任务卡或阶段页承载的流程动作。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
@@ -16,7 +16,11 @@ const i18n = createI18n({
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingProcessing: { action: { resolve_field_conflicts: '处理字段冲突', view_result: '查看结果', none: '无操作' } },
|
||||
shippingOrderReview: { unsavedSwitch: { unsavedCount: '未保存 {count} 项' } },
|
||||
shippingOrderReview: {
|
||||
saveOrderAndValidate: '提交订单',
|
||||
submitOrderHint: '提交后自动校验,满足条件将自动建单。',
|
||||
unsavedSwitch: { unsavedCount: '未保存 {count} 项' },
|
||||
},
|
||||
},
|
||||
workspace: { shippingNotice: { processGate: { actions: {} } } },
|
||||
},
|
||||
@@ -59,4 +63,17 @@ describe('ReviewWorkbenchFooter', () => {
|
||||
expect(wrapper.find('[data-testid="review-footer-flow-resolve_field_conflicts"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-footer-flow-view_result"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses submit-order wording and explains the automatic creation policy', () => {
|
||||
const wrapper = mount(ReviewWorkbenchFooter, {
|
||||
props: {
|
||||
availableActions: ['validate'], canConfirmBuild: false, saving: false, isReadOnly: false, hasDraft: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:唯一写入口完成提交语义;资格通过后的自动建单是系统行为,不要求第二次确认。
|
||||
expect(wrapper.text()).toContain('提交订单');
|
||||
expect(wrapper.get('[data-testid="review-submit-order-hint"]').text()).toBe('提交后自动校验,满足条件将自动建单。');
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:订单处理工作台底部唯一写操作栏(处置 / 保存 / 统一流程动作)。
|
||||
依赖:vue-i18n、lucide-vue-next、ActionPresentation。
|
||||
逻辑:ShippingOrderReviewView 传入 available_actions 与流程动作投影;sticky bottom;
|
||||
订单复核只保留保存校验;流程动作由所属阶段或当前任务卡承载;写按钮受 actionsExecutable 约束;
|
||||
订单复核只保留提交订单;流程动作由所属阶段或当前任务卡承载;写按钮受 actionsExecutable 约束;
|
||||
流程写操作经 flow-action emit(与 Resolver 同链);flowBusy||saving 时禁用。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -76,7 +76,7 @@ function hasAction(action: string): boolean {
|
||||
/**
|
||||
* 订单复核底栏不承载流程投影动作。
|
||||
*
|
||||
* 核心逻辑:保存并校验是表单级提交,固定放在这里;字段裁决、重试、查看结果等
|
||||
* 核心逻辑:提交订单是表单级提交,固定放在这里;字段裁决、重试、查看结果等
|
||||
* Case/阶段级动作必须留在其业务上下文中,避免同一动作在顶栏、右栏和底栏重复出现。
|
||||
*/
|
||||
const footerFlowItems = computed((): ActionPresentationItem[] => []);
|
||||
@@ -171,6 +171,16 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
|
||||
{{ autoGateHint || t('chat.shippingOrderReview.buildEligibility.autoGateWaitingHint') }}
|
||||
</p>
|
||||
<template v-if="!automating && canWriteCaseActions">
|
||||
<button
|
||||
v-if="showStpRetry && hasAction('retry_stp_auto_create')"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
class="inline-flex items-center gap-1 rounded border border-sky-300 px-3 py-2 text-sm text-sky-700 hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:text-sky-300 dark:hover:bg-sky-950/40"
|
||||
data-testid="review-retry-stp-auto-create"
|
||||
@click="emit('retry-stp')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.automation.retryStp') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showValidate && hasAction('validate')"
|
||||
type="button"
|
||||
@@ -180,6 +190,13 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
|
||||
>
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveOrderAndValidate') }}
|
||||
</button>
|
||||
<p
|
||||
v-if="showValidate && hasAction('validate')"
|
||||
class="basis-full text-right text-xs text-muted"
|
||||
data-testid="review-submit-order-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.submitOrderHint') }}
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
+3
-3
@@ -23,9 +23,9 @@ const messages = {
|
||||
subtitle: 'Advances through freight upload',
|
||||
polling: 'Refreshing…',
|
||||
progressUnavailable: 'Progress unavailable — refresh the page.',
|
||||
openTaskWorkbench: 'Open Task Center to register',
|
||||
openTaskWorkbench: 'Open Task Center to confirm upload',
|
||||
nextStepsManualUpload:
|
||||
'Next: download Excel → upload on freight platform → submit evidence and receipt',
|
||||
'Next: download Excel → upload on freight platform → confirm uploaded',
|
||||
nextStepsGeneric: 'Manual action required — follow the system prompt.',
|
||||
},
|
||||
},
|
||||
@@ -194,7 +194,7 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
});
|
||||
expect(wrapper.get('[data-testid="review-manual-upload-next-steps"]').text()).toContain('download Excel');
|
||||
const link = wrapper.get('[data-testid="review-open-task-workbench"]');
|
||||
expect(link.text()).toContain('Open Task Center to register');
|
||||
expect(link.text()).toContain('Open Task Center to confirm upload');
|
||||
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
|
||||
expect(link.attributes('href')).toContain('SN-1');
|
||||
});
|
||||
|
||||
+255
-143
@@ -22,65 +22,83 @@ const i18n = createI18n({
|
||||
});
|
||||
|
||||
function buildProjection(): ConversationProcessingProjection {
|
||||
const needsAction = {
|
||||
user_task_no: 'OT-NEED',
|
||||
group: 'needs_action' as const,
|
||||
status_label: 'pending_review',
|
||||
file_count: 2,
|
||||
run_no: 'RUN-NEED',
|
||||
can_append: false,
|
||||
recently_created: false,
|
||||
};
|
||||
const processing = {
|
||||
user_task_no: 'OT-PROC',
|
||||
submission_ordinal: 2,
|
||||
group: 'processing' as const,
|
||||
status_label: 'extracting',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-PROC',
|
||||
can_append: true,
|
||||
recently_created: true,
|
||||
focused: true,
|
||||
};
|
||||
const completed = {
|
||||
user_task_no: 'OT-DONE',
|
||||
group: 'completed' as const,
|
||||
status_label: 'completed',
|
||||
title: 'done.pdf',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-DONE',
|
||||
can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
};
|
||||
const archived = {
|
||||
user_task_no: 'OT-HIST',
|
||||
group: 'history' as const,
|
||||
status_label: 'completed',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-HIST',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
};
|
||||
const cancelled = {
|
||||
user_task_no: 'OT-CANCEL',
|
||||
group: 'history' as const,
|
||||
status_label: 'cancelled',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-CANCEL',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
};
|
||||
return {
|
||||
summary: { total_tasks: 3, processing: 1, needs_action: 1, completed: 1, history: 2 },
|
||||
focused_task_no: 'OT-PROC',
|
||||
recent_task_no: 'OT-PROC',
|
||||
needs_action: [{
|
||||
user_task_no: 'OT-NEED',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
file_count: 2,
|
||||
run_no: 'RUN-NEED',
|
||||
can_append: false,
|
||||
recently_created: false,
|
||||
}],
|
||||
processing: [{
|
||||
user_task_no: 'OT-PROC',
|
||||
submission_ordinal: 2,
|
||||
group: 'processing',
|
||||
status_label: 'extracting',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-PROC',
|
||||
can_append: true,
|
||||
recently_created: true,
|
||||
focused: true,
|
||||
}],
|
||||
completed: [{
|
||||
user_task_no: 'OT-DONE',
|
||||
group: 'completed',
|
||||
status_label: 'completed',
|
||||
title: 'done.pdf',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-DONE',
|
||||
can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
}],
|
||||
history: [
|
||||
{
|
||||
user_task_no: 'OT-HIST',
|
||||
group: 'history',
|
||||
status_label: 'completed',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-HIST',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
},
|
||||
{
|
||||
user_task_no: 'OT-CANCEL',
|
||||
group: 'history',
|
||||
status_label: 'cancelled',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-CANCEL',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
},
|
||||
],
|
||||
status_groups: {
|
||||
failed: [needsAction], waiting_human: [], processing: [processing], completed: [completed],
|
||||
cancelled: [cancelled], archived: [archived],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 测试仅构造权威 status_groups;禁止再把旧四组作为组件输入。 */
|
||||
function setStatusGroup(
|
||||
projection: ConversationProcessingProjection,
|
||||
key: keyof NonNullable<ConversationProcessingProjection['status_groups']>,
|
||||
tasks: NonNullable<ConversationProcessingProjection['status_groups']>[keyof NonNullable<ConversationProcessingProjection['status_groups']>],
|
||||
) {
|
||||
projection.status_groups![key] = tasks;
|
||||
}
|
||||
|
||||
function projectionWithGroups(
|
||||
summary: ConversationProcessingProjection['summary'],
|
||||
groups: NonNullable<ConversationProcessingProjection['status_groups']>,
|
||||
): ConversationProcessingProjection {
|
||||
return { summary, status_groups: groups };
|
||||
}
|
||||
|
||||
/** 构造任务卡使用的权威统一进度。 */
|
||||
function buildWorkItem(
|
||||
taskNo: string,
|
||||
@@ -119,12 +137,12 @@ function buildWorkItem(
|
||||
describe('ShippingConversationProcessingCard', () => {
|
||||
it('only exposes file cancellation when the backend explicitly authorizes cancel_unit', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'OT-CANCEL-UNIT', group: 'processing', status_label: 'extracting',
|
||||
file_count: 1, run_no: 'RUN-CANCEL-UNIT', can_append: false,
|
||||
objects: [{ kind: 'document', object_key: 'DOC-9', label: 'cancel.pdf', filename: 'cancel.pdf',
|
||||
document_id: 9, root_document_id: 9, status_label: 'extracting' }],
|
||||
}];
|
||||
}]);
|
||||
const workItem = buildWorkItem('OT-CANCEL-UNIT', {
|
||||
availableActions: ['cancel_unit'],
|
||||
sourceSummary: { ...buildWorkItem('OT-CANCEL-UNIT').sourceSummary, documentId: 9 },
|
||||
@@ -151,12 +169,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('does not fall back to legacy cancellation when ui_state revokes it', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'OT-CANCEL-REVOKED', group: 'processing', status_label: 'extracting',
|
||||
file_count: 1, run_no: 'RUN-CANCEL-REVOKED', can_append: false,
|
||||
objects: [{ kind: 'document', object_key: 'DOC-10', label: 'revoked.pdf', filename: 'revoked.pdf',
|
||||
document_id: 10, root_document_id: 10, status_label: 'extracting' }],
|
||||
}];
|
||||
}]);
|
||||
const workItem = buildWorkItem('OT-CANCEL-REVOKED', {
|
||||
availableActions: ['cancel_unit'],
|
||||
sourceSummary: { ...buildWorkItem('OT-CANCEL-REVOKED').sourceSummary, documentId: 10 },
|
||||
@@ -181,11 +199,11 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('does not render legacy document_names as a batch file row without a live leaf projection', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'OT-HISTORICAL-SNAPSHOT', group: 'processing', status_label: 'extracting',
|
||||
title: 'legacy-run.pdf', document_names: ['legacy-run.pdf'], file_count: 1,
|
||||
run_no: 'RUN-HISTORICAL-SNAPSHOT', can_append: false,
|
||||
}];
|
||||
}]);
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
@@ -199,7 +217,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('uses the live leaf summary instead of a stale task object in batch mode', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'OT-LIVE-LEAF', group: 'processing', status_label: 'extracting',
|
||||
title: 'snapshot-old-name.pdf', file_count: 1, run_no: 'RUN-LIVE-LEAF', can_append: false,
|
||||
objects: [{
|
||||
@@ -207,7 +225,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
filename: 'snapshot-old-name.pdf', document_id: 88, root_document_id: 88,
|
||||
status_label: 'pending_review',
|
||||
}],
|
||||
}];
|
||||
}]);
|
||||
const live = buildWorkItem('OT-LIVE-LEAF', {
|
||||
runNo: 'RUN-LIVE-LEAF',
|
||||
sourceSummary: {
|
||||
@@ -235,12 +253,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('expands EML files only from the live aggregate work item', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'INTAKE:EML-LIVE', group: 'processing', status_label: 'extracting',
|
||||
title: 'snapshot-mail.eml', document_names: ['snapshot-attachment.pdf'],
|
||||
file_count: 1, run_no: 'RUN-EML-LIVE', can_append: false,
|
||||
aggregateChildren: [],
|
||||
}];
|
||||
}]);
|
||||
const liveChild = buildWorkItem('DOCUMENT:77', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
|
||||
sourceSummary: {
|
||||
@@ -275,12 +293,49 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(wrapper.text()).not.toContain('snapshot-attachment.pdf');
|
||||
});
|
||||
|
||||
it('counts only stage-filtered EML leaves in the batch status heading', async () => {
|
||||
const projection = buildProjection();
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'INTAKE:MIXED-STAGES', group: 'processing', status_label: 'extracting',
|
||||
title: 'mixed-stages.eml', file_count: 2, run_no: 'RUN-MIXED-STAGES', can_append: false,
|
||||
}]);
|
||||
const orderReviewLeaf = buildWorkItem('DOCUMENT:401', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STAGES',
|
||||
sourceSummary: { ...buildWorkItem('DOCUMENT:401').sourceSummary, documentId: 401, filename: 'review.pdf' },
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'waiting_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const freightLeaf = buildWorkItem('DOCUMENT:402', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STAGES',
|
||||
sourceSummary: { ...buildWorkItem('DOCUMENT:402').sourceSummary, documentId: 402, filename: 'upload.xlsx' },
|
||||
uiState: {
|
||||
status: 'running', stage: 'freight_uploading', lifecycleStage: 'freight_upload',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const root = buildWorkItem('INTAKE:MIXED-STAGES', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STAGES',
|
||||
aggregateChildren: [orderReviewLeaf, freightLeaf],
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [root], workbenchMode: true, lifecycleFilter: 'order_review' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 阶段卡与列表标题必须消费同一批可见叶子,不能把同一 EML 的其它阶段附件混入。
|
||||
expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).toContain('1 个文件');
|
||||
expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).not.toContain('2 个文件');
|
||||
});
|
||||
|
||||
it('keeps an EML attachment when it has a linked child order task', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'INTAKE:EML-WITH-CHILD-OT', group: 'processing', status_label: 'extracting',
|
||||
title: 'mail.eml', file_count: 2, run_no: 'RUN-EML-WITH-CHILD-OT', can_append: false,
|
||||
}];
|
||||
}]);
|
||||
const firstAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
|
||||
sourceSummary: {
|
||||
@@ -416,9 +471,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('uses expand-files as the only detail entry when canExpandFileDetails', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 }, {
|
||||
failed: [{
|
||||
user_task_no: 'OT-MULTI',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
@@ -429,11 +484,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
run_no: 'RUN-MULTI',
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -455,9 +507,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('shows view_details when task cannot expand file details, and keeps cancel as overflow', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 }, {
|
||||
failed: [{
|
||||
user_task_no: 'OT-SINGLE',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
@@ -466,11 +518,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
objects: [],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -485,9 +534,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('shows multi-document title from authoritative projection without workflow fallback', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, total_files: 2, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, total_files: 2, processing: 0, needs_action: 1, completed: 0, history: 0 }, {
|
||||
failed: [{
|
||||
user_task_no: 'OT-MULTI',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
@@ -499,11 +548,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
objects: [],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -518,10 +564,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('uses unified order recognition title instead of internal OT number', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
needs_action: [],
|
||||
processing: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, processing: 1, needs_action: 0, completed: 0, history: 0 }, {
|
||||
failed: [], waiting_human: [], processing: [{
|
||||
user_task_no: 'OT-20260803-A13F95D2',
|
||||
group: 'processing',
|
||||
status_label: 'processing',
|
||||
@@ -529,10 +574,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
file_count: 1,
|
||||
run_no: 'SNER-X',
|
||||
can_append: false,
|
||||
}],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -558,16 +601,17 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 0, needs_action: 0, completed: 1, history: 0 },
|
||||
...projectionWithGroups(
|
||||
{ total_tasks: 1, processing: 0, needs_action: 0, completed: 1, history: 0 }, {
|
||||
failed: [], waiting_human: [], processing: [], completed: [{
|
||||
user_task_no: 'OT-DETAIL', group: 'completed', status_label: 'completed',
|
||||
file_count: 1, run_no: 'RUN-DETAIL', can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
}], cancelled: [], archived: [],
|
||||
},
|
||||
),
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [],
|
||||
completed: [{
|
||||
user_task_no: 'OT-DETAIL', group: 'completed', status_label: 'completed',
|
||||
file_count: 1, run_no: 'RUN-DETAIL', can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
}],
|
||||
processing: [], history: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
@@ -609,10 +653,13 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
props: {
|
||||
projection: {
|
||||
...buildProjection(),
|
||||
needs_action: [{
|
||||
...buildProjection().needs_action[0],
|
||||
available_actions: ['view_details', 'open_review', 'cancel_task'],
|
||||
}],
|
||||
status_groups: {
|
||||
...buildProjection().status_groups!,
|
||||
failed: [{
|
||||
...buildProjection().status_groups!.failed[0],
|
||||
available_actions: ['view_details', 'open_review', 'cancel_task'],
|
||||
}],
|
||||
},
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
@@ -632,12 +679,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
}));
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 20, processing: 20, needs_action: 0, history: 0 },
|
||||
needs_action: [],
|
||||
processing,
|
||||
history: [],
|
||||
},
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 20, processing: 20, needs_action: 0, history: 0 },
|
||||
{ failed: [], waiting_human: [], processing, completed: [], cancelled: [], archived: [] },
|
||||
),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -649,9 +694,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('renders an EML order_intake in the unified failed group rather than the removed intake side path', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 }, {
|
||||
failed: [{
|
||||
user_task_no: 'SNI-1',
|
||||
group: 'needs_action',
|
||||
userGroup: 'failed',
|
||||
@@ -660,11 +705,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
file_count: 1,
|
||||
run_no: null,
|
||||
can_append: false,
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
workItems: [{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
@@ -687,6 +729,15 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
attemptNo: 2,
|
||||
},
|
||||
availableActions: ['view_details', 'retry_parse'],
|
||||
uiState: {
|
||||
status: 'failed',
|
||||
stage: 'document_parsing',
|
||||
lifecycleStage: 'intake_parse',
|
||||
lifecycleEntries: [],
|
||||
blocking_reason: { code: 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' },
|
||||
primary_action: { code: 'retry_parse', i18nKey: null, parameters: {}, executionMode: 'immediate' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'po.pdf',
|
||||
@@ -708,7 +759,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-SNI-1"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain('重试解析');
|
||||
// Intake retry_parse 与 Case reparse 对用户统一展示为“重新解析”;
|
||||
// 后端 action_code 仍保留不同对象边界与执行接口。
|
||||
expect(wrapper.text()).toContain('重新解析');
|
||||
});
|
||||
|
||||
it('keeps a human Gate action visible before and after selecting its task', async () => {
|
||||
@@ -726,6 +779,15 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
blockingReasonCode: 'inventory_match_not_ready',
|
||||
},
|
||||
availableActions: ['open_inventory_match_review'],
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'waiting_review',
|
||||
lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [],
|
||||
blocking_reason: { code: 'inventory_match_not_ready' },
|
||||
primary_action: { code: 'open_inventory_match_review', i18nKey: null, parameters: {}, executionMode: 'immediate' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
}),
|
||||
buildWorkItem('OT-PROC', {
|
||||
stage: 'inventory_matching',
|
||||
@@ -737,12 +799,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(2);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待复核');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待人工处理');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('库存匹配');
|
||||
expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0);
|
||||
const task = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
|
||||
expect(task.find('[data-testid="unified-action-primary"]').exists()).toBe(true);
|
||||
expect(task.find('[data-testid="unified-action-primary"]').text()).toContain('库存');
|
||||
expect(task.find('[data-testid="unified-action-primary"]').text()).toContain('open_inventory_match_review');
|
||||
|
||||
await task.find('button').trigger('click');
|
||||
await flushPromises();
|
||||
@@ -754,10 +816,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('maps internal review_case_draft status to a user-facing review label', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.needs_action = [{
|
||||
...projection.needs_action[0],
|
||||
setStatusGroup(projection, 'failed', [{
|
||||
...projection.status_groups!.failed[0],
|
||||
status_label: 'review_case_draft',
|
||||
}];
|
||||
}]);
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection },
|
||||
global: { plugins: [i18n] },
|
||||
@@ -771,12 +833,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('renders a compact V3 file row with named lifecycle entries', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
...projection.processing[0],
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
...projection.status_groups!.processing[0],
|
||||
user_task_no: 'OT-LIFECYCLE',
|
||||
run_no: 'RUN-LIFECYCLE',
|
||||
file_count: 1,
|
||||
}];
|
||||
}]);
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection,
|
||||
@@ -798,9 +860,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
status: 'running',
|
||||
stage: 'inventory_match',
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [
|
||||
lifecycle_entries: [
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
blocking_reason: null,
|
||||
@@ -818,19 +881,71 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(row.text()).toContain('lifecycle.pdf');
|
||||
expect(row.text()).toContain('PO:PO-LIFECYCLE');
|
||||
expect(row.text()).toContain('通知准备');
|
||||
expect(row.text()).toContain('订单复核 · 可进入');
|
||||
expect(row.text()).toContain('通知准备 · 当前可处理');
|
||||
expect(row.text()).toContain('通知完成 · 前置未完成');
|
||||
expect(row.text()).toContain('当前阶段:通知准备');
|
||||
});
|
||||
|
||||
it('keeps the file action slot for a real action but not for duplicate lifecycle navigation', async () => {
|
||||
const projection = buildProjection();
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
...projection.status_groups!.processing[0],
|
||||
user_task_no: 'OT-FILE-ACTION', run_no: 'RUN-FILE-ACTION', file_count: 1,
|
||||
}]);
|
||||
const navigationOnly = buildWorkItem('OT-FILE-ACTION', {
|
||||
runNo: 'RUN-FILE-ACTION',
|
||||
sourceSummary: { ...buildWorkItem('OT-FILE-ACTION').sourceSummary, documentId: 31 },
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'order_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
blocking_reason: null,
|
||||
primary_action: {
|
||||
code: 'open_order_review', i18nKey: null, parameters: {}, executionMode: 'navigate',
|
||||
targetSurface: 'order_lifecycle_workbench', targetLifecycleStage: 'order_review',
|
||||
},
|
||||
secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [navigationOnly], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-31"]');
|
||||
expect(row.text()).not.toContain('进入订单复核');
|
||||
|
||||
await wrapper.setProps({
|
||||
workItems: [buildWorkItem('OT-FILE-ACTION', {
|
||||
runNo: 'RUN-FILE-ACTION',
|
||||
sourceSummary: { ...buildWorkItem('OT-FILE-ACTION').sourceSummary, documentId: 31 },
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'order_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
blocking_reason: null,
|
||||
primary_action: {
|
||||
code: 'create_draft', i18nKey: null, parameters: {}, executionMode: 'navigate',
|
||||
targetSurface: 'order_lifecycle_workbench', targetLifecycleStage: 'order_review',
|
||||
},
|
||||
secondary_actions: [],
|
||||
},
|
||||
})],
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(row.text()).toContain('创建草稿');
|
||||
await row.find('button').trigger('click');
|
||||
expect(wrapper.emitted('projectionAction')?.[0]?.[0]).toMatchObject({
|
||||
item: { actionCode: 'create_draft' },
|
||||
});
|
||||
});
|
||||
|
||||
it('fails closed when a lifecycle entry has an unknown backend state', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
...projection.processing[0],
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
...projection.status_groups!.processing[0],
|
||||
user_task_no: 'OT-LIFECYCLE-UNKNOWN',
|
||||
run_no: 'RUN-LIFECYCLE-UNKNOWN',
|
||||
file_count: 1,
|
||||
}];
|
||||
}]);
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection,
|
||||
@@ -851,7 +966,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
status: 'running',
|
||||
stage: 'inventory_match',
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [
|
||||
lifecycle_entries: [
|
||||
{ code: 'order_review', state: 'paused', targetSurface: 'order_lifecycle_workbench' },
|
||||
] as unknown as ShippingProcessingProjection['uiState']['lifecycleEntries'],
|
||||
blocking_reason: null,
|
||||
@@ -865,9 +980,6 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
await flushPromises();
|
||||
|
||||
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
|
||||
const orderReview = row.findAll('button').find((button) => button.text().includes('订单复核'));
|
||||
expect(orderReview?.attributes('disabled')).toBeDefined();
|
||||
await orderReview?.trigger('click');
|
||||
expect(wrapper.emitted('openLifecycleStage')).toBeUndefined();
|
||||
expect(row.findAll('button')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
+20
-17
@@ -36,7 +36,10 @@ import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { flattenBusinessFileProjections } from '@/features/chat/shipping/conversationProcessingProjection';
|
||||
import { resolveConversationTaskActionPresentation, resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import {
|
||||
resolveConversationTaskActionPresentation,
|
||||
resolveFilePrimaryActionPresentation,
|
||||
} from '@/features/shipping-progress/actionPresentation';
|
||||
import SidebarProgressInline from '@/features/shipping-progress/components/SidebarProgressInline.vue';
|
||||
import type { ActionPresentation, ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
|
||||
@@ -50,8 +53,8 @@ const props = defineProps<{
|
||||
hasMoreHistory?: boolean;
|
||||
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
|
||||
workbenchMode?: boolean;
|
||||
/** 批次四阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
|
||||
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
/** 批次五阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
|
||||
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
/** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */
|
||||
fileSearchQuery?: string;
|
||||
/** 后端已授权下载的正式 Excel 对应 OT。 */
|
||||
@@ -94,12 +97,13 @@ type WorkbenchFileRow = {
|
||||
po_number?: string | null;
|
||||
projection?: ShippingProcessingProjection;
|
||||
};
|
||||
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
|
||||
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
|
||||
type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number];
|
||||
const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = {
|
||||
intake_parse: 'intakeParse',
|
||||
order_review: 'orderReview',
|
||||
fulfillment_prep: 'fulfillmentPrep',
|
||||
freight_upload: 'freightUpload',
|
||||
upload_complete: 'uploadComplete',
|
||||
};
|
||||
|
||||
@@ -113,16 +117,15 @@ const hasContent = computed(() => Boolean(
|
||||
));
|
||||
|
||||
const statusGroups = computed(() => activeProjection.value?.status_groups || null);
|
||||
const completedTasks = computed(() => statusGroups.value?.completed || activeProjection.value?.completed || []);
|
||||
const historyTasks = computed(() => statusGroups.value
|
||||
? [...statusGroups.value.cancelled, ...statusGroups.value.archived]
|
||||
: (activeProjection.value?.history || []));
|
||||
/** EML 卡必须由后端 userGroup 分入独立用户区;旧任务保留 needs_action 兼容归属。 */
|
||||
const failedTasks = computed(() => statusGroups.value?.failed
|
||||
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'failed' || !task.userGroup));
|
||||
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human
|
||||
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'waiting_human'));
|
||||
const processingTasks = computed(() => statusGroups.value?.processing || activeProjection.value?.processing || []);
|
||||
const completedTasks = computed(() => statusGroups.value?.completed || []);
|
||||
const historyTasks = computed(() => [
|
||||
...(statusGroups.value?.cancelled || []),
|
||||
...(statusGroups.value?.archived || []),
|
||||
]);
|
||||
/** EML 卡的状态分区必须完全遵循后端 status_groups,禁止旧四组回退重判。 */
|
||||
const failedTasks = computed(() => statusGroups.value?.failed || []);
|
||||
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human || []);
|
||||
const processingTasks = computed(() => statusGroups.value?.processing || []);
|
||||
|
||||
/** 任务只要含一个命中附件即保留,避免筛选后打散同一封 EML 的上下文。 */
|
||||
function taskMatchesLifecycleFilter(task: ConversationProcessingUserTask): boolean {
|
||||
@@ -426,7 +429,7 @@ function isDownloadSelected(taskNo: string): boolean {
|
||||
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
|
||||
function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
|
||||
const seen = new Set<string>();
|
||||
return tasks.reduce((total, task) => total + workbenchFileRows(task).reduce((count, file) => {
|
||||
return tasks.reduce((total, task) => total + visibleWorkbenchFileRows(task).reduce((count, file) => {
|
||||
const filename = String(file.filename || file.label || '').trim().toLowerCase();
|
||||
if (filename.endsWith('.eml')) return count;
|
||||
const key = String(('document_id' in file ? file.document_id : undefined)
|
||||
@@ -454,7 +457,7 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
|
||||
return taskReasonLabel(task);
|
||||
}
|
||||
|
||||
/** 文件工作面显示四阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
|
||||
/** 文件工作面显示五阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
|
||||
function workbenchFileLifecycleStage(file: WorkbenchFileRow): string {
|
||||
const code = String(file.projection?.uiState?.lifecycleStage || '').trim();
|
||||
const key = LIFECYCLE_STAGE_LABEL_KEYS[code];
|
||||
@@ -494,7 +497,7 @@ function onOpenLifecycleStage(file: WorkbenchFileRow, lifecycleStage: LifecycleS
|
||||
/** 叶子文件动作由自身 ui_state 裁决;没有叶子投影时不伪造可操作按钮。 */
|
||||
function filePrimaryActionItem(file: WorkbenchFileRow): ActionPresentationItem | null {
|
||||
return file.projection
|
||||
? resolveProcessingActionPresentation(file.projection, { surface: 'right' }).primary
|
||||
? resolveFilePrimaryActionPresentation(file.projection)
|
||||
: null;
|
||||
}
|
||||
|
||||
|
||||
+52
-14
@@ -149,7 +149,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('处理中 1');
|
||||
});
|
||||
|
||||
it('uses the current three PDF rows instead of stale Run review totals', () => {
|
||||
it('keeps historical candidate-ready attachments under their EML instead of creating a candidate group', () => {
|
||||
const currentPdfRows = ['4210020274.pdf', '4210020272.pdf', '4210020273.pdf'].map((fileName, index) => ({
|
||||
unitId: index + 1,
|
||||
documentId: index + 101,
|
||||
@@ -181,10 +181,11 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
|
||||
});
|
||||
|
||||
// 当前卡片的总数、完成率和候选列表必须来自同一份有效 PDF 清单。
|
||||
// 旧快照缺少会话级用户状态;candidate_ready 只能作为附件阶段,不能升格为顶层分组。
|
||||
expect(wrapper.text()).toContain('共 3 个文件');
|
||||
expect(wrapper.text()).toContain('0/3 已处理');
|
||||
expect(wrapper.text()).toContain('已生成候选 3 个文件');
|
||||
expect(wrapper.text()).not.toContain('已生成候选 3 个文件');
|
||||
expect(wrapper.text()).toContain('4210020274.pdf');
|
||||
expect(wrapper.text()).not.toContain('23/20 已处理');
|
||||
expect(wrapper.text()).not.toContain('100% 完成');
|
||||
});
|
||||
@@ -234,6 +235,21 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).not.toContain('系统处理中');
|
||||
});
|
||||
|
||||
it('does not fall back to one Run file when the authoritative conversation projection has not returned', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({ summary: { ...buildState().summary, totalDocuments: 1 } }), runNo: 'SNER-SINGLE' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
// 真实会话工作流已建立但读取超时/失败时,不能将最近 Run 的单文件当作整个批次。
|
||||
processing: ref(null),
|
||||
processingWorkItems: ref([]),
|
||||
initialLoading: ref(false),
|
||||
} } },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-projection-loading"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).not.toContain('共 1 个文件');
|
||||
});
|
||||
|
||||
it('does not render message document rows while the authoritative projection is loading', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({
|
||||
@@ -337,6 +353,34 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).not.toContain('stale.pdf');
|
||||
});
|
||||
|
||||
it('uses the authoritative attachment total when a historical message only carries the EML task count', () => {
|
||||
const task = {
|
||||
user_task_no: 'INTAKE:SNI-MAILS', title: 'mail-batch.eml', file_count: 30,
|
||||
userGroup: 'waiting_human', group: 'needs_action', aggregateChildren: [],
|
||||
aggregateSummary: { intakeNo: 'SNI-MAILS', total: 30, completed: 0, processing: 0, needsAction: 30, failed: 0, stages: ['order_review'], reasonCodes: [] },
|
||||
} as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
// 历史聊天消息记录的是 18 封 EML;不能把它当成 18 个业务附件。
|
||||
state: buildState({ summary: { ...buildState().summary, totalDocuments: 18 } }),
|
||||
runNo: 'SNER-ATTACHMENT-TOTAL',
|
||||
},
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({
|
||||
summary: { total_files: 30, completed_files: 0, waiting_human_files: 30, failed_files: 0 },
|
||||
ui_state: { status: 'waiting_human' },
|
||||
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
|
||||
}),
|
||||
processingWorkItems: ref([]),
|
||||
} } },
|
||||
});
|
||||
|
||||
// 关键断言:有权威会话投影时,只能显示附件总数,禁止回退历史邮件任务数。
|
||||
expect(wrapper.text()).toContain('共 30 个文件');
|
||||
expect(wrapper.text()).toContain('0/30 已处理');
|
||||
expect(wrapper.text()).not.toContain('共 18 个文件');
|
||||
});
|
||||
|
||||
it('counts unique EML attachment children instead of task rows', async () => {
|
||||
const childA = { workItemType: 'order_task', workItemNo: 'OT-A', sourceType: 'eml', intakeNo: 'SNI-COUNT', sourceSummary: { filename: 'a.pdf', documentId: 101, documentCount: 1 }, status: 'processing', stage: 'document_parsing', userStatus: 'running', facts: { uploadState: 'not_created' } } as any;
|
||||
const childB = { ...childA, workItemNo: 'OT-B', sourceSummary: { filename: 'b.pdf', documentId: 102, documentCount: 1 } } as any;
|
||||
@@ -376,7 +420,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('4518838152.pdf');
|
||||
});
|
||||
|
||||
it('groups completed attachments under their EML intake instead of mixing unrelated files', async () => {
|
||||
it('keeps candidate-ready attachments under their EML instead of mixing unrelated files', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -390,7 +434,6 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('button').trigger('click');
|
||||
const text = wrapper.text();
|
||||
expect(text.indexOf('Forwarder_A.eml')).toBeLessThan(text.indexOf('Packing_List.pdf'));
|
||||
expect(text).toContain('Customs_Form.pdf');
|
||||
@@ -428,7 +471,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.findAll('.animate-spin').length).toBe(0);
|
||||
});
|
||||
|
||||
it('does not render completed files again as standalone cards', async () => {
|
||||
it('renders candidate-ready standalone files once without creating a candidate group', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -450,12 +493,11 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const accordion = wrapper.find('button');
|
||||
await accordion.trigger('click');
|
||||
expect(wrapper.text().match(/4518838152\.pdf/g)?.length).toBe(1);
|
||||
expect(wrapper.text()).not.toContain('已生成候选 2 个文件');
|
||||
});
|
||||
|
||||
it('aggregates a fully completed EML intake only inside the completed section', async () => {
|
||||
it('keeps an all-candidate EML in the system-processing fallback group', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -477,9 +519,6 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).not.toContain('forwarder.eml');
|
||||
expect(wrapper.text()).not.toContain('packing.pdf');
|
||||
await wrapper.find('button').trigger('click');
|
||||
expect(wrapper.text()).toContain('forwarder.eml');
|
||||
expect(wrapper.text()).toContain('packing.pdf');
|
||||
expect(wrapper.text().match(/forwarder\.eml/g)?.length).toBe(1);
|
||||
@@ -487,7 +526,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('已提取');
|
||||
});
|
||||
|
||||
it('keeps a partially completed EML intake outside the completed section', async () => {
|
||||
it('keeps a mixed-stage EML in the system-processing fallback group', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -501,7 +540,6 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('button').trigger('click');
|
||||
expect(wrapper.text()).toContain('forwarder.eml');
|
||||
expect(wrapper.text()).toContain('invoice.pdf');
|
||||
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
|
||||
|
||||
@@ -62,9 +62,12 @@ type ConversationProcessing = import('../../types/shipping.api.types').Conversat
|
||||
const conversationProcessing = computed<ConversationProcessing | null>(() => (
|
||||
(shippingWorkflow as { processing?: { value?: ConversationProcessing | null } | null } | null)?.processing?.value || null
|
||||
));
|
||||
const hasAuthoritativeConversationProvider = computed(() => Boolean(
|
||||
shippingWorkflow && 'processing' in shippingWorkflow,
|
||||
));
|
||||
const conversationProjectionLoading = computed(() => Boolean(
|
||||
(shippingWorkflow as { initialLoading?: { value?: boolean } | null } | null)?.initialLoading?.value,
|
||||
));
|
||||
) || (hasAuthoritativeConversationProvider.value && !conversationProcessing.value));
|
||||
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => conversationProcessing.value?.status_groups || null);
|
||||
const hasConversationStatusGroups = computed(() => Boolean(conversationStatusGroups.value));
|
||||
const statusGroupDefs = [
|
||||
@@ -288,37 +291,19 @@ const childRows = (email: ShippingOrderExtractionFileState) => fileRows.value.fi
|
||||
&& row.intakeId === email.intakeId
|
||||
&& !isEmailRow(row)
|
||||
));
|
||||
const candidateEmailGroups = computed(() => emailRows.value
|
||||
.map((parent) => ({ parent, children: childRows(parent) }))
|
||||
.filter((group) => group.children.length > 0 && group.children.every((child) => child.status === 'candidate_ready')));
|
||||
const emailHasFailedChild = (email: ShippingOrderExtractionFileState) => childRows(email).some(isFailedParseRow);
|
||||
const emailIsCompleted = (email: ShippingOrderExtractionFileState) => {
|
||||
const children = childRows(email);
|
||||
return children.length > 0 && children.every((child) => child.status === 'candidate_ready');
|
||||
};
|
||||
const candidateEmailUnitIds = computed(() => new Set(
|
||||
candidateEmailGroups.value.flatMap((group) => [group.parent.unitId, ...group.children.map((child) => child.unitId)]),
|
||||
));
|
||||
const candidateStandaloneRows = computed(() => fileRows.value.filter((row) => (
|
||||
!isEmailRow(row)
|
||||
&& row.status === 'candidate_ready'
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const candidateFileCount = computed(() => (
|
||||
candidateEmailGroups.value.reduce((count, group) => count + group.children.length, 0)
|
||||
+ candidateStandaloneRows.value.length
|
||||
));
|
||||
const activeEmailRows = computed(() => emailRows.value.filter((row) => !candidateEmailUnitIds.value.has(row.unitId)));
|
||||
const activeEmailRows = computed(() => emailRows.value);
|
||||
const standaloneRows = computed(() => fileRows.value.filter((row) => (
|
||||
!isEmailRow(row)
|
||||
&& row.status !== 'candidate_ready'
|
||||
&& !isFailedParseRow(row)
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const failedRows = computed(() => fileRows.value.filter((row) => (
|
||||
isFailedParseRow(row)
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const processedCount = computed(() => {
|
||||
@@ -339,8 +324,6 @@ const progressPercent = computed(() => {
|
||||
const total = batchFileCount.value;
|
||||
return total > 0 ? Math.min(100, Math.round((processedCount.value / total) * 100)) : 0;
|
||||
});
|
||||
const completedExpanded = ref(false);
|
||||
|
||||
/** 新版会话批次的业务文件数由后端汇总;旧 Run 卡仍保留历史兼容计数。 */
|
||||
const batchFileCount = computed(() => {
|
||||
if (hasConversationStatusGroups.value) {
|
||||
@@ -486,15 +469,13 @@ const handlingSummaryLine = computed(() => {
|
||||
});
|
||||
|
||||
/**
|
||||
* 唯一主 CTA:失败→重试解析;需处理→继续处理;否则不展示。
|
||||
* 唯一主 CTA 只读取服务端明确下发的动作;失败数量和 Run 状态不能自行授权重试。
|
||||
*/
|
||||
const primaryChatAction = computed((): { kind: 'retry' | 'continue'; label: string } | null => {
|
||||
if (props.readonly || hasConversationStatusGroups.value) return null;
|
||||
const actions = props.state.availableActions || [];
|
||||
const canRetry = actions.includes('retry_failed_attachments')
|
||||
|| actions.includes('retry_failed_documents')
|
||||
|| displaySummary.value.failedDocuments > 0
|
||||
|| props.state.status === 'failed';
|
||||
|| actions.includes('retry_failed_documents');
|
||||
if (canRetry) {
|
||||
return {
|
||||
kind: 'retry',
|
||||
@@ -701,26 +682,32 @@ async function onPrimaryChatAction() {
|
||||
<ChevronDown class="h-4 w-4 transition-transform" :class="expandedStatusGroups.has(group.key) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="expandedStatusGroups.has(group.key)" class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-700">
|
||||
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="rounded-lg border border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-950/30" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
|
||||
<div class="flex items-start gap-2">
|
||||
<Mail class="mt-0.5 h-4 w-4 text-blue-600" />
|
||||
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
|
||||
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<button type="button" class="flex w-full items-center justify-between gap-2 text-left" @click="toggleEmlTask(task.user_task_no)">
|
||||
<span class="truncate text-sm font-medium">{{ task.title || task.user_task_no }}</span>
|
||||
<button type="button" class="flex w-full items-center justify-between gap-3 text-left" @click="toggleEmlTask(task.user_task_no)">
|
||||
<span class="truncate font-medium">{{ task.title || task.user_task_no }}</span>
|
||||
<ChevronDown class="h-4 w-4 shrink-0 transition-transform" :class="expandedEmlTasks.has(task.user_task_no) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div class="mt-1 text-xs text-slate-500">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
|
||||
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
|
||||
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
|
||||
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-medium">{{ child.sourceSummary.filename || child.workItemNo }}</div>
|
||||
<div class="text-[11px] text-slate-500">{{ childStageLabel(child) }}</div>
|
||||
<div v-if="taskReason(child)" class="text-[11px] text-rose-600">{{ displayReason(taskReason(child)) }}</div>
|
||||
</div>
|
||||
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
|
||||
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
|
||||
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" class="mx-4 my-2 space-y-1 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30" data-testid="shipping-order-extraction-eml-children">
|
||||
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 py-1 text-sm">
|
||||
<div class="flex min-w-0 items-start gap-2">
|
||||
<LoaderCircle v-if="!isFailedProjection(child) && !isWaitingProjection(child) && !isCompletedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 animate-spin text-blue-500" />
|
||||
<AlertCircle v-else-if="isFailedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 text-rose-500" />
|
||||
<CheckCircle2 v-else-if="isCompletedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500" />
|
||||
<TriangleAlert v-else class="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
|
||||
<div class="min-w-0">
|
||||
<div class="truncate">{{ child.sourceSummary.filename || child.workItemNo }}</div>
|
||||
<div class="text-xs text-slate-500">{{ childStageLabel(child) }}</div>
|
||||
<div v-if="taskReason(child)" class="text-xs text-rose-600">{{ displayReason(taskReason(child)) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
@@ -756,19 +743,6 @@ async function onPrimaryChatAction() {
|
||||
</article>
|
||||
</div>
|
||||
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
|
||||
<button type="button" class="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-3 text-left dark:border-slate-700 dark:bg-slate-900" @click="completedExpanded = !completedExpanded">
|
||||
<span class="flex items-center gap-3 text-base font-medium"><span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-100 text-blue-600"><CheckCircle2 class="h-4 w-4" /></span>{{ t('chat.shippingProcessing.candidateFiles', { count: candidateFileCount }) }}</span>
|
||||
<ChevronDown class="h-5 w-5 transition-transform" :class="completedExpanded ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="completedExpanded && candidateFileCount" class="space-y-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div v-for="group in candidateEmailGroups" :key="`candidate-email-${group.parent.unitId}`" class="rounded-md border border-blue-100 bg-blue-50/50 px-3 py-2 dark:border-blue-900 dark:bg-blue-950/20">
|
||||
<div class="flex items-center gap-2 font-medium text-slate-700 dark:text-slate-200"><Mail class="h-4 w-4 text-blue-600" />{{ t('chat.shippingProcessing.emailPrefix') }}{{ group.parent.fileName }}<span class="ml-auto text-emerald-500">{{ t('chat.shippingProcessing.batchExtracted') }}</span></div>
|
||||
<div class="mt-1 space-y-1 border-l-2 border-blue-200 pl-3 dark:border-blue-800">
|
||||
<div v-for="row in group.children" :key="`candidate-child-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-for="row in candidateStandaloneRows" :key="`candidate-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
|
||||
</div>
|
||||
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20"><Mail class="mt-0.5 h-5 w-5 text-blue-600" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-slate-500">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
|
||||
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-blue-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
|
||||
* 用途:验收批次进度中心只投影后端实时状态,不再保留文件详情抽屉。
|
||||
* 依赖:Vitest、Vue Test Utils、Timeline、ShippingConversationProcessingCard、shipping API。
|
||||
* 逻辑:四阶段、生命周期入口与单文件取消均由后端 Projection/availableActions 决定。
|
||||
* 逻辑:五阶段、生命周期入口与单文件取消均由后端 Projection/availableActions 决定。
|
||||
*/
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -43,6 +43,12 @@ vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),
|
||||
}));
|
||||
const gateRecovery = vi.hoisted(() => ({
|
||||
submitPrimaryAction: vi.fn(async () => ({ outcome: 'submitted' })),
|
||||
}));
|
||||
vi.mock('@/features/shipping-process-gates/composables/useShippingProcessGateRecovery', () => ({
|
||||
useShippingProcessGateRecovery: () => gateRecovery,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -114,25 +120,31 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
api.reparseCase.mockClear();
|
||||
api.reparseRun.mockClear();
|
||||
api.reparseBatch.mockClear();
|
||||
api.retryRun.mockClear();
|
||||
gateRecovery.submitPrimaryAction.mockClear();
|
||||
});
|
||||
|
||||
it('renders backend-owned four-stage summaries and the authorized download toolbar', async () => {
|
||||
it('prefers backend five-stage lifecycle nodes and shows the authorized download toolbar in freight upload', async () => {
|
||||
const processing = processingProjection({
|
||||
four_stage_nodes: [
|
||||
lifecycle_nodes: [
|
||||
{ code: 'intake_parse', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'order_review', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'fulfillment_prep', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'upload_complete', status: 'running', summary: { total: 1, completed: 0, needs_action: 1, processing: 0, failed: 0, blocking_reason: { code: 'manual_upload_pending' } } },
|
||||
{ code: 'freight_upload', status: 'running', summary: { total: 1, completed: 0, needs_action: 1, processing: 0, failed: 0, blocking_reason: { code: 'manual_upload_pending' } } },
|
||||
{ code: 'upload_complete', status: 'pending', summary: { total: 1, completed: 0, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
],
|
||||
output_artifacts: [{ order_task_no: 'OT-1', filename: 'notice.xlsx', type: 'xlsx', status: 'ready', action: { code: 'download_excel', enabled: true } }],
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection()]);
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.get('[data-testid="shipping-workflow-four-stage-progress"]').text()).toContain('接收解析');
|
||||
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-upload_complete"]');
|
||||
// 四阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。
|
||||
expect(upload.text()).toBe('通知完成1');
|
||||
const progress = wrapper.get('[data-testid="shipping-workflow-lifecycle-progress"]');
|
||||
expect(progress.text()).toContain('接收解析');
|
||||
expect(progress.text()).toContain('货代上传');
|
||||
expect(progress.findAll('button')).toHaveLength(5);
|
||||
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-freight_upload"]');
|
||||
// 五阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。
|
||||
expect(upload.text()).toBe('货代上传1');
|
||||
await upload.trigger('click');
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-download-toolbar"]').exists()).toBe(true);
|
||||
});
|
||||
@@ -286,7 +298,7 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'retry', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
item: { intent: 'reparse', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
@@ -317,7 +329,7 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'retry', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
item: { intent: 'reparse', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
});
|
||||
await flushPromises();
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
@@ -425,7 +437,7 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
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 () => {
|
||||
it('rejects a legacy generic-retry action instead of treating it as a Run retry', async () => {
|
||||
const file = fileProjection({
|
||||
uiState: {
|
||||
status: 'failed', stage: 'document_parsing', lifecycleStage: 'intake_parse',
|
||||
@@ -438,12 +450,40 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'retry', actionCode: 'retry', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
item: { intent: 'retry_parse', actionCode: 'retry', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 后端只授予了 retry;附件层使用自己的 Run 执行,不能因 DOCUMENT 编号而吞掉操作。
|
||||
expect(api.retryRun).toHaveBeenCalledWith('RUN-1');
|
||||
// 泛化 retry 已退出契约;前端不得据 Run 编号擅自选择重试 API。
|
||||
expect(api.retryRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submits an authorized freight-upload retry through its Gate instead of re-running extraction', async () => {
|
||||
const processGate = {
|
||||
execution_no: 'SPE-1',
|
||||
allowed_actions: ['retry_freight_upload_rpa'],
|
||||
recovery_targets: [],
|
||||
current_blocking_gate: {
|
||||
gate_code: 'freight_upload', evaluation_version: 1,
|
||||
},
|
||||
};
|
||||
const file = fileProjection({ processGate } as Partial<ShippingProcessingProjection>);
|
||||
const wrapper = mountTimeline(processingProjection(), [file]);
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: {
|
||||
intent: 'retry_freight_upload_rpa', actionCode: 'retry_freight_upload_rpa',
|
||||
labelKey: 'chat.shippingProcessing.action.retry',
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(gateRecovery.submitPrimaryAction).toHaveBeenCalledWith(processGate, expect.objectContaining({
|
||||
actionCode: 'retry_freight_upload_rpa',
|
||||
}));
|
||||
expect(api.retryRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens manual upload with the backend root task number for a document file action', async () => {
|
||||
@@ -463,23 +503,6 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it('shows only title and total on four-stage cards', async () => {
|
||||
const processing = processingProjection({
|
||||
four_stage_nodes: [{
|
||||
code: 'order_review', status: 'blocked',
|
||||
summary: { total: 2, completed: 0, needs_action: 2, processing: 0, failed: 0, blocking_reason: { code: 'field_conflict' } },
|
||||
}],
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection()]);
|
||||
await flushPromises();
|
||||
|
||||
const card = wrapper.get('[data-testid="shipping-workflow-stage-filter-order_review"]');
|
||||
expect(card.text()).toContain('订单复核');
|
||||
expect(card.text()).toContain('2');
|
||||
expect(card.text()).not.toContain('待处理');
|
||||
expect(card.text()).not.toContain('field_conflict');
|
||||
});
|
||||
|
||||
it('does not navigate when a lifecycle entry has an unknown backend state', async () => {
|
||||
routerPush.mockClear();
|
||||
const wrapper = mountTimeline(processingProjection(), [fileProjection()]);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
|
||||
* 用途:聊天页右侧「批次进度中心」——后端批次投影、四阶段进度和文件行操作。
|
||||
* 用途:聊天页右侧「批次进度中心」——后端批次投影、五阶段进度和文件行操作。
|
||||
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
|
||||
* ReasonDialog、ProcessGateRecoveryCard。
|
||||
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
|
||||
@@ -115,25 +115,32 @@ const processing = computed(() => ctl.value.processing?.value ?? null);
|
||||
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
|
||||
const displayProcessing = computed(() => processing.value);
|
||||
const batchArtifacts = computed(() => displayProcessing.value?.output_artifacts || []);
|
||||
const batchFourStageNodes = computed(() => displayProcessing.value?.four_stage_nodes || []);
|
||||
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'>('all');
|
||||
const batchLifecycleNodes = computed(() => displayProcessing.value?.lifecycle_nodes || []);
|
||||
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete'>('all');
|
||||
const fileSearchQuery = ref('');
|
||||
const selectedDownloadTaskNos = ref<string[]>([]);
|
||||
/** 四阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
|
||||
const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
|
||||
type ConversationStatusGroup = 'failed' | 'waiting_human' | 'processing' | 'completed' | 'cancelled' | 'archived';
|
||||
function statusGroupTasks(...groups: ConversationStatusGroup[]): ConversationProcessingUserTask[] {
|
||||
const statusGroups = displayProcessing.value?.status_groups;
|
||||
if (!statusGroups) return [];
|
||||
return groups.flatMap((group) => statusGroups[group] || []);
|
||||
}
|
||||
/** 五阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
|
||||
const BATCH_LIFECYCLE_I18N_KEYS: Record<string, string> = {
|
||||
intake_parse: 'intakeParse',
|
||||
order_review: 'orderReview',
|
||||
fulfillment_prep: 'fulfillmentPrep',
|
||||
freight_upload: 'freightUpload',
|
||||
upload_complete: 'uploadComplete',
|
||||
};
|
||||
function batchFourStageLabelKey(code: string): string {
|
||||
return BATCH_FOUR_STAGE_I18N_KEYS[code] || code;
|
||||
function batchLifecycleLabelKey(code: string): string {
|
||||
return BATCH_LIFECYCLE_I18N_KEYS[code] || code;
|
||||
}
|
||||
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete') {
|
||||
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete') {
|
||||
lifecycleFilter.value = lifecycleFilter.value === code ? 'all' : code;
|
||||
}
|
||||
/** 阶段卡仅展示后端统计总数;状态、阻塞和推进语义由颜色与边框表达。 */
|
||||
function stageTotalText(node: NonNullable<typeof batchFourStageNodes.value>[number]): string {
|
||||
function stageTotalText(node: NonNullable<typeof batchLifecycleNodes.value>[number]): string {
|
||||
return String(Number(node.summary?.total || 0));
|
||||
}
|
||||
/** 下载资格仅来自后端 output_artifacts 的授权动作;筛选仅影响展示,不缩减授权集合。 */
|
||||
@@ -190,87 +197,17 @@ async function downloadBatchArchive(taskNos: string[]) {
|
||||
msg.error(err instanceof Error ? err.message : t('chat.shippingProcessing.batchWorkbench.artifacts.downloadFailed', { count: taskNos.length }));
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 批次总览一律按文件计数。会话 summary 中 processing/needs_action 是任务数,
|
||||
* 不能直接填入原型的“处理中/需处理”文件统计卡。
|
||||
*/
|
||||
function taskFileKeys(task: ConversationProcessingUserTask): string[] {
|
||||
const keys = new Set<string>();
|
||||
const collect = (children: ShippingProcessingProjection[]) => {
|
||||
for (const child of children) {
|
||||
const nested = child.aggregateChildren || [];
|
||||
if (nested.length) collect(nested);
|
||||
const filename = String(child.sourceSummary?.filename || '').trim();
|
||||
// 聚合父项/邮件容器只提供来源信息,叶子附件才计入业务文件。
|
||||
if (nested.length || filename.toLowerCase().endsWith('.eml')) continue;
|
||||
const id = Number(child.sourceSummary?.documentId || 0);
|
||||
const key = id > 0 ? `document:${id}` : filename ? `filename:${filename}` : '';
|
||||
if (key) keys.add(key);
|
||||
}
|
||||
};
|
||||
const children = task.aggregateChildren || [];
|
||||
if (children.length) {
|
||||
collect(children);
|
||||
return [...keys];
|
||||
}
|
||||
for (const object of task.objects || []) {
|
||||
if (object.kind !== 'document') continue;
|
||||
const id = Number(object.document_id || 0);
|
||||
const filename = String(object.filename || object.label || '').trim();
|
||||
if (filename.toLowerCase().endsWith('.eml')) continue;
|
||||
const key = id > 0
|
||||
? `document:${id}`
|
||||
: String(object.filename || object.object_key || '').trim();
|
||||
if (key) keys.add(key);
|
||||
}
|
||||
if (keys.size) return [...keys];
|
||||
// 无 EML 子附件明细时,直接文件可按自身 file_count 回退;EML 不允许伪造附件数。
|
||||
const taskName = String(task.title || '').trim().toLowerCase();
|
||||
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
|
||||
const fallback = Math.max(0, Number(task.file_count || 0));
|
||||
return Array.from({ length: fallback }, (_, index) => `${task.user_task_no}:file:${index}`);
|
||||
}
|
||||
const batchOverview = computed(() => {
|
||||
const summary = displayProcessing.value?.summary;
|
||||
// [AUTHORITY] status_groups 表示新版批次投影。其 summary 是后端对完整批次
|
||||
// 一次裁决的文件事实,即使当前值为 0 也不得从局部展开行重算。
|
||||
if (displayProcessing.value?.status_groups && summary) {
|
||||
return {
|
||||
total: Number(summary.total_files || 0),
|
||||
processing: Number(summary.processing_files || 0),
|
||||
completed: Number(summary.completed_files || 0),
|
||||
needsAction: Number(summary.failed_files || 0) + Number(summary.waiting_human_files || 0),
|
||||
};
|
||||
}
|
||||
const groups = displayProcessing.value?.status_groups;
|
||||
const failed = groups?.failed || [];
|
||||
const waiting = groups?.waiting_human || [];
|
||||
const processingTasks = groups?.processing || displayProcessing.value?.processing || [];
|
||||
const completed = groups?.completed || displayProcessing.value?.completed || [];
|
||||
const seen = new Set<string>();
|
||||
const count = (tasks: ConversationProcessingUserTask[]) => tasks.reduce((total, task) => {
|
||||
let count = 0;
|
||||
for (const key of taskFileKeys(task)) {
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
count += 1;
|
||||
}
|
||||
return total + count;
|
||||
}, 0);
|
||||
const needsAction = count([...failed, ...waiting]);
|
||||
const processingCount = count(processingTasks);
|
||||
const completedCount = count(completed);
|
||||
const computedTotal = needsAction + processingCount + completedCount;
|
||||
const summaryTotal = Number(displayProcessing.value?.summary?.total_files || 0);
|
||||
// [AUTHORITY] 摘要投影的统计与状态组同由服务端一次裁决;不能从展开行重算,
|
||||
// 否则 EML 聚合、历史版本去重与五阶段筛选会再次发生口径漂移。
|
||||
return {
|
||||
// status_groups 的去重文件集合优先;旧 summary.total_files 只在没有可枚举文件时回退。
|
||||
total: computedTotal > 0 ? computedTotal : summaryTotal,
|
||||
processing: processingCount,
|
||||
completed: completedCount,
|
||||
needsAction,
|
||||
total: Number(summary?.total_files || 0),
|
||||
processing: Number(summary?.processing_files || 0),
|
||||
completed: Number(summary?.completed_files || 0),
|
||||
needsAction: Number(summary?.failed_files || 0) + Number(summary?.waiting_human_files || 0),
|
||||
};
|
||||
});
|
||||
const loading = computed(() => ctl.value.loading.value);
|
||||
/** 初始加载:首次打开投影仍为空时显示摘要占位。 */
|
||||
const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
|
||||
/** 用户主动刷新(刷新按钮 / 重试 / 重解析等):驱动顶部刷新图标旋转。 */
|
||||
@@ -284,11 +221,7 @@ const error = computed(() => ctl.value.error.value);
|
||||
const hasPinnedProcessingTasks = computed(() => {
|
||||
const projection = displayProcessing.value;
|
||||
if (!projection) return false;
|
||||
return Boolean(
|
||||
projection.needs_action?.length
|
||||
|| projection.processing?.length
|
||||
|| projection.completed?.length,
|
||||
);
|
||||
return statusGroupTasks('failed', 'waiting_human', 'processing', 'completed').length > 0;
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -489,7 +422,7 @@ async function onProcessingTaskAction(payload: {
|
||||
openReparseBatchDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (action === 'retry_parse' || action === 'retry') {
|
||||
if (action === 'retry_parse') {
|
||||
const intakeNo = String(task.user_task_no || '').replace(/^INTAKE:/i, '').trim();
|
||||
if (intakeNo.startsWith('SNI-')) {
|
||||
if (actionBusyItemNo.value) return;
|
||||
@@ -741,10 +674,8 @@ async function onTaskProjectionAction(payload: {
|
||||
return;
|
||||
}
|
||||
if (code === 'reparse') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
const task = statusGroupTasks('failed', 'waiting_human', 'processing')
|
||||
.find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
void onProcessingTaskAction({ task, action: 'reparse' });
|
||||
return;
|
||||
@@ -773,13 +704,16 @@ async function onTaskProjectionAction(payload: {
|
||||
openReparseBatchDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (code === 'retry_inventory_preparation') {
|
||||
const gateSummary = projection.processGate;
|
||||
if (!gateSummary) {
|
||||
msg.warning(t('workspace.shippingNotice.processGate.noAction'));
|
||||
return;
|
||||
}
|
||||
// Gate 执行器统一处理 execution_no、乐观锁与幂等键;批次卡不自行组装写请求。
|
||||
const gateSummary = projection.processGate;
|
||||
const gateAuthorized = Boolean(gateSummary && code && (
|
||||
(gateSummary.allowed_actions || []).some((action) => String(action).trim() === code)
|
||||
|| (gateSummary.recovery_targets || []).some((target) => (
|
||||
String(target.action_code || '').trim() === code
|
||||
))
|
||||
));
|
||||
if (gateAuthorized && gateSummary) {
|
||||
// Gate 执行器统一处理 execution_no、乐观锁与幂等键;不能因展示 intent=retry
|
||||
// 误将货代上传等 Gate 恢复动作路由为重新解析。
|
||||
const result = await submitGatePrimaryAction(gateSummary, {
|
||||
actionCode: code,
|
||||
navigationContext: gateNavigationContext.value,
|
||||
@@ -793,34 +727,13 @@ async function onTaskProjectionAction(payload: {
|
||||
void onProcessingIntakeAction({ item: projection, action: code });
|
||||
return;
|
||||
}
|
||||
if (code === 'retry' || item.intent === 'retry') {
|
||||
const runNo = String(projection.runNo || '').trim();
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
return;
|
||||
}
|
||||
if (actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = runNo;
|
||||
try {
|
||||
await retryWorkspaceShippingOrderExtractionRun(runNo);
|
||||
await ctl.value.refresh();
|
||||
} catch (err) {
|
||||
msg.error(reparseErrorMessage(err));
|
||||
} finally {
|
||||
actionBusyItemNo.value = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'refresh') {
|
||||
void onRefresh();
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_order_review' || code === 'open_order_review') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
...(displayProcessing.value?.completed || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
const task = statusGroupTasks('failed', 'waiting_human', 'processing', 'completed')
|
||||
.find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
void onProcessingTaskAction({ task, action: code || 'open_review' });
|
||||
return;
|
||||
@@ -841,11 +754,8 @@ async function onTaskProjectionAction(payload: {
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'view_result' || code === 'focus_task') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
...(displayProcessing.value?.completed || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
const task = statusGroupTasks('failed', 'waiting_human', 'processing', 'completed')
|
||||
.find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
await onProcessingFocus(taskNo);
|
||||
return;
|
||||
@@ -879,12 +789,9 @@ watch(
|
||||
const focusedTaskExists = computed(() => {
|
||||
const taskNo = String(route.query.focus_task_no || '').trim();
|
||||
if (!taskNo || !displayProcessing.value) return false;
|
||||
const groups = [
|
||||
...(displayProcessing.value.needs_action || []),
|
||||
...(displayProcessing.value.processing || []),
|
||||
...(displayProcessing.value.completed || []),
|
||||
...(displayProcessing.value.history || []),
|
||||
];
|
||||
const groups = statusGroupTasks(
|
||||
'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived',
|
||||
);
|
||||
return groups.some((task) => String(task.user_task_no || '').trim() === taskNo);
|
||||
});
|
||||
|
||||
@@ -956,7 +863,7 @@ watch(
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-0.5 space-y-0.5 text-xs text-secondary" data-testid="shipping-workflow-panel-summary">
|
||||
<template v-if="loading && !displayProcessing">
|
||||
<template v-if="initialLoading && !displayProcessing">
|
||||
{{ t('chat.shippingProcessing.loading') }}
|
||||
</template>
|
||||
<template v-else-if="displayProcessing">
|
||||
@@ -968,11 +875,11 @@ watch(
|
||||
{{ t('chat.shippingProcessing.summaryTruncatedHint') }}
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="error">
|
||||
{{ resolveShippingProcessingMessage('networkRecoverable', te, t) }}
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ t('chat.shippingProcessing.compactSummary', {
|
||||
active: 0,
|
||||
total: 0,
|
||||
}) }}
|
||||
{{ t('chat.shippingProcessing.loading') }}
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@@ -998,6 +905,26 @@ watch(
|
||||
</div>
|
||||
|
||||
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-y-auto p-5">
|
||||
<div
|
||||
v-if="initialLoading && !displayProcessing"
|
||||
class="mb-4 space-y-3"
|
||||
data-testid="shipping-workflow-loading"
|
||||
>
|
||||
<div class="grid grid-cols-2 gap-3 xl:grid-cols-4">
|
||||
<div v-for="index in 4" :key="index" class="h-24 animate-pulse rounded-xl border border-default bg-surface-muted" />
|
||||
</div>
|
||||
<div class="h-32 animate-pulse rounded-xl border border-default bg-surface-muted" />
|
||||
</div>
|
||||
<div
|
||||
v-else-if="error && !displayProcessing"
|
||||
class="mb-4 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900"
|
||||
data-testid="shipping-workflow-load-error"
|
||||
>
|
||||
<p>{{ resolveShippingProcessingMessage('networkRecoverable', te, t) }}</p>
|
||||
<button type="button" class="mt-2 rounded-md border border-amber-300 px-2.5 py-1 text-xs font-medium" @click="onRefresh">
|
||||
{{ t('chat.shippingProcessing.actions.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-if="displayProcessing"
|
||||
class="mb-4 grid grid-cols-2 gap-3 xl:grid-cols-4"
|
||||
@@ -1024,15 +951,15 @@ watch(
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<section v-if="batchFourStageNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-four-stage-progress">
|
||||
<div class="grid grid-cols-4 gap-2">
|
||||
<button v-for="node in batchFourStageNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :class="[node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)">
|
||||
<span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(node.code)}`) }}</span>
|
||||
<section v-if="batchLifecycleNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-lifecycle-progress">
|
||||
<div class="grid grid-cols-2 gap-2 sm:grid-cols-5">
|
||||
<button v-for="node in batchLifecycleNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :class="[node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)">
|
||||
<span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchLifecycleLabelKey(node.code)}`) }}</span>
|
||||
<span class="mt-0.5 block text-[11px] opacity-80">{{ stageTotalText(node) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="lifecycleFilter !== 'all'" class="mt-2 flex items-center justify-between gap-2 text-xs text-secondary">
|
||||
<span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(lifecycleFilter)}`) }) }}</span>
|
||||
<span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchLifecycleLabelKey(lifecycleFilter)}`) }) }}</span>
|
||||
<button type="button" class="text-brand-700 hover:underline" data-testid="shipping-workflow-clear-stage-filter" @click="lifecycleFilter = 'all'">{{ t('chat.shippingProcessing.batchWorkbench.clearStageFilter') }}</button>
|
||||
</div>
|
||||
<p v-if="Number(displayProcessing?.unclassified_summary?.count || 0) > 0" class="mt-2 text-xs text-amber-700" data-testid="shipping-workflow-unclassified-summary">
|
||||
@@ -1048,7 +975,7 @@ watch(
|
||||
<span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.search.label') }}</span>
|
||||
<input v-model="fileSearchQuery" type="search" class="w-full rounded-md border border-default bg-surface px-2.5 py-1.5 text-xs" :placeholder="t('chat.shippingProcessing.batchWorkbench.search.placeholder')" data-testid="shipping-workflow-file-search">
|
||||
</label>
|
||||
<div v-if="lifecycleFilter === 'upload_complete' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar">
|
||||
<div v-if="lifecycleFilter === 'freight_upload' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar">
|
||||
<label class="inline-flex items-center gap-1 text-xs text-secondary"><input type="checkbox" :checked="allDownloadableSelected" data-testid="shipping-workflow-download-select-all" @change="toggleAllDownloadSelections"><span>{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selectAll') }}</span></label>
|
||||
<span class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selected', { count: selectedDownloadTaskNos.length }) }}</span>
|
||||
<button type="button" class="rounded-md border border-brand-300 px-2.5 py-1 text-xs font-medium text-brand-700 disabled:opacity-50" :disabled="!selectedDownloadTaskNos.length" data-testid="shipping-workflow-download-selected" @click="downloadSelectedBatchArtifacts">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadSelected') }}</button>
|
||||
|
||||
@@ -37,21 +37,15 @@ describe('useChat user attachment snapshots', () => {
|
||||
});
|
||||
});
|
||||
|
||||
const buildBatchUiStateEvent = (
|
||||
const buildTaskUiStateEvent = (
|
||||
taskNo: string,
|
||||
batchNo: string,
|
||||
actionId: string,
|
||||
checkpoint = 'ready_export',
|
||||
) => ({
|
||||
event: 'shipping_ui_state',
|
||||
batch_no: batchNo,
|
||||
batch_ui_state: {
|
||||
batch_no: batchNo,
|
||||
current_focus_task_no: taskNo,
|
||||
tasks: [],
|
||||
focus_task_ui_state: {
|
||||
task_no: taskNo,
|
||||
ui_state: {
|
||||
task_no: taskNo,
|
||||
batch_no: batchNo,
|
||||
checkpoint,
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
@@ -73,7 +67,6 @@ const buildBatchUiStateEvent = (
|
||||
},
|
||||
],
|
||||
updated_at: '2026-07-01T10:00:00+08:00',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -81,38 +74,38 @@ describe('useChat shipping_ui_state SSE', () => {
|
||||
it('hydrates ui_state for notifications and never attaches chat fulfillment actions', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '当前正在处理批次任务',
|
||||
content: '当前正在处理任务',
|
||||
type: 'shipping-match-result',
|
||||
payload: { action_buttons: [{ id: 'legacy' }] },
|
||||
};
|
||||
|
||||
const batchEvent = buildBatchUiStateEvent('SN-UNIT-001', 'SB-UNIT-001', 'generate_excel');
|
||||
const taskEvent = buildTaskUiStateEvent('SN-UNIT-001', 'generate_excel');
|
||||
|
||||
applyShippingUiStateToMessage(message, batchEvent);
|
||||
applyShippingUiStateToMessage(message, taskEvent);
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-UNIT-001');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toBeUndefined();
|
||||
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
|
||||
expect((message.payload as { shipping_ui_state?: { task_no?: string } }).shipping_ui_state?.task_no).toBe('SN-UNIT-001');
|
||||
});
|
||||
|
||||
it('updates ui_state when batch focus task changes without remounting action buttons', () => {
|
||||
it('updates ui_state when task changes without remounting action buttons', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '请继续处理当前批次',
|
||||
content: '请继续处理当前任务',
|
||||
payload: { action_buttons: [] },
|
||||
};
|
||||
|
||||
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-A', 'SB-FOCUS-001', 'generate_excel'));
|
||||
applyShippingUiStateToMessage(message, buildTaskUiStateEvent('SN-FOCUS-A', 'generate_excel'));
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-A');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
|
||||
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-B', 'SB-FOCUS-001', 'retry_upload'));
|
||||
applyShippingUiStateToMessage(message, buildTaskUiStateEvent('SN-FOCUS-B', 'retry_upload'));
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { shipping_batch_ui_state?: { current_focus_task_no?: string } }).shipping_batch_ui_state?.current_focus_task_no)
|
||||
expect((message.payload as { shipping_ui_state?: { task_no?: string } }).shipping_ui_state?.task_no)
|
||||
.toBe('SN-FOCUS-B');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ import type {
|
||||
RetrieverResource,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import { createStartChatTurn } from './useChatTurn';
|
||||
|
||||
@@ -112,29 +112,19 @@ const addAttributionParts = (msg: ChatMessage, value: unknown) => {
|
||||
/**
|
||||
* 解析发货通知 SSE 事件中的统一 UI State 载荷。
|
||||
*
|
||||
* 核心逻辑:优先读取单票 `ui_state`,批次事件则下钻 `batch_ui_state.focus_task_ui_state`;
|
||||
* 同时保留批次态原文,供会话上传摘要与后续同步逻辑继续消费。
|
||||
* 核心逻辑:只读取正式任务 `ui_state`;已删除的 shipping_batches 不再参与事件恢复。
|
||||
* @param data - SSE 事件 JSON
|
||||
* @returns 提炼后的单票 UI State 与原始批次 UI State
|
||||
* @returns 提炼后的单票 UI State
|
||||
*/
|
||||
export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
|
||||
uiState?: ShippingTaskUiState;
|
||||
batchUiState?: ShippingBatchUiState;
|
||||
} => {
|
||||
const rawUiState = data.ui_state;
|
||||
const uiState = rawUiState && typeof rawUiState === 'object'
|
||||
? rawUiState as ShippingTaskUiState
|
||||
: undefined;
|
||||
const rawBatchUiState = data.batch_ui_state;
|
||||
const batchUiState = rawBatchUiState && typeof rawBatchUiState === 'object'
|
||||
? rawBatchUiState as ShippingBatchUiState
|
||||
: undefined;
|
||||
const focusTaskUiState = batchUiState?.focus_task_ui_state && typeof batchUiState.focus_task_ui_state === 'object'
|
||||
? batchUiState.focus_task_ui_state
|
||||
: undefined;
|
||||
return {
|
||||
uiState: uiState || focusTaskUiState,
|
||||
batchUiState,
|
||||
uiState,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -145,7 +135,7 @@ export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
|
||||
* 不再把 action_buttons 挂到聊天消息(履约写操作改由任务处理工作台承接)。
|
||||
*/
|
||||
export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||||
const { uiState, batchUiState } = resolveShippingUiStatePayload(data);
|
||||
const { uiState } = resolveShippingUiStatePayload(data);
|
||||
if (!uiState) return;
|
||||
|
||||
msg.shipping_ui_state = uiState;
|
||||
@@ -156,7 +146,6 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
shipping_ui_state: uiState,
|
||||
...(batchUiState ? { shipping_batch_ui_state: batchUiState } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -602,7 +591,7 @@ export function useChat() {
|
||||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
|
||||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
|
||||
>,
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
): Promise<ChatMessageSendResult> => {
|
||||
const displayQuery = String(
|
||||
@@ -669,7 +658,6 @@ export function useChat() {
|
||||
kb_type: kbType,
|
||||
files: files && files.length > 0 ? files : undefined,
|
||||
task_id: context?.task_id || undefined,
|
||||
batch_no: context?.batch_no || undefined,
|
||||
shipping_temporary_inventory_asset_no: context?.shipping_temporary_inventory_asset_no || undefined,
|
||||
shipping_temporary_inventory_session_no: context?.shipping_temporary_inventory_session_no || undefined,
|
||||
display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||||
|
||||
@@ -35,7 +35,6 @@ import { useChatStore } from '../stores/chat.store';
|
||||
import { useTrainingWorkspace } from './useTrainingWorkspace';
|
||||
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
|
||||
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
|
||||
import { clearPendingNoticeBatchRetry } from '../shipping/useChatShippingUploadHandler';
|
||||
import {
|
||||
createChatPageConversationApi,
|
||||
createChatPageLocalMessageApi,
|
||||
@@ -195,7 +194,7 @@ export function useChatPage() {
|
||||
}, { immediate: true });
|
||||
|
||||
const dialogs = useChatPageDialogs(messages);
|
||||
const { openDeleteConfirmDialog, openRetryFailedConfirm, showShippingToast } = dialogs;
|
||||
const { openDeleteConfirmDialog } = dialogs;
|
||||
|
||||
let loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
let startNewChat: () => void;
|
||||
@@ -330,35 +329,6 @@ export function useChatPage() {
|
||||
|| procurement.allowsSendWithAttachmentsOnly.value,
|
||||
);
|
||||
|
||||
/**
|
||||
* 打开批次失败重试确认弹窗(会话摘要场景的兜底入口)。
|
||||
*/
|
||||
const openRetryFailedConfirmDialog = () => {
|
||||
openRetryFailedConfirm(() => confirmRetryFailedTasks());
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认后执行批次失败任务重试,并以非阻塞 toast 反馈结果。
|
||||
* 核心逻辑:调用 useChatShipping.retryCurrentShippingBatchPendingTasks,成功后刷新已内置;仅补 toast。
|
||||
*/
|
||||
const retryingShippingPendingTasks = ref(false);
|
||||
const confirmRetryFailedTasks = async () => {
|
||||
if (retryingShippingPendingTasks.value) return;
|
||||
retryingShippingPendingTasks.value = true;
|
||||
try {
|
||||
const result = await shipping.retryCurrentShippingBatchPendingTasks();
|
||||
if (!result) return;
|
||||
showShippingToast(
|
||||
t('chat.shippingNoticeUi.retryFailedStarted', {
|
||||
started: result.started,
|
||||
skipped: result.skipped,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
retryingShippingPendingTasks.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const conversationApi = createChatPageConversationApi({
|
||||
deps,
|
||||
route,
|
||||
@@ -370,13 +340,11 @@ export function useChatPage() {
|
||||
isThinking,
|
||||
loadConversationState,
|
||||
createNewChatView,
|
||||
clearPendingNoticeBatchRetry,
|
||||
onConversationIdChanging: shipping.onConversationIdChanging,
|
||||
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
|
||||
onConversationLoadFailed: shipping.onConversationLoadFailed,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
|
||||
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
|
||||
clearHistory,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
input,
|
||||
@@ -498,7 +466,6 @@ export function useChatPage() {
|
||||
currentAgentId,
|
||||
presetQuestion,
|
||||
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
|
||||
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
resetChatStateForAgentChange,
|
||||
cancelVoiceInput: voice.cancelVoiceInput,
|
||||
@@ -639,11 +606,6 @@ export function useChatPage() {
|
||||
deleteConfirmMessage: dialogs.deleteConfirmMessage,
|
||||
closeDeleteConfirmDialog: dialogs.closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm: dialogs.handleDeleteConfirm,
|
||||
showRetryFailedConfirmDialog: dialogs.showRetryFailedConfirmDialog,
|
||||
closeRetryFailedConfirm: dialogs.closeRetryFailedConfirm,
|
||||
handleRetryFailedConfirm: dialogs.handleRetryFailedConfirm,
|
||||
openRetryFailedConfirm: openRetryFailedConfirmDialog,
|
||||
retryingShippingPendingTasks,
|
||||
shippingToastMessage: dialogs.shippingToastMessage,
|
||||
clearShippingToast: dialogs.clearShippingToast,
|
||||
showChatRating,
|
||||
@@ -655,10 +617,6 @@ export function useChatPage() {
|
||||
clearProcurementOriginalContract: procurement.clearOriginalContract,
|
||||
showShippingProgressWorkspace: shipping.showShippingProgressWorkspace,
|
||||
clearShippingFocus: shipping.clearShippingFocus,
|
||||
shippingBatchSummary: shipping.shippingBatchSummary,
|
||||
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
|
||||
activeShippingBatchNo: shipping.activeShippingBatchNo,
|
||||
shippingBatchTasks: shipping.shippingBatchTasks,
|
||||
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
|
||||
getActiveOrderExtractionRunNo: shipping.getActiveOrderExtractionRunNo,
|
||||
workflowRefreshTrigger: shipping.workflowRefreshTrigger,
|
||||
@@ -667,8 +625,6 @@ export function useChatPage() {
|
||||
setFocusedConversationTaskNo: shipping.setFocusedConversationTaskNo,
|
||||
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
||||
switchShippingBatch: shipping.switchShippingBatch,
|
||||
retryCurrentShippingBatchPendingTasks: shipping.retryCurrentShippingBatchPendingTasks,
|
||||
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
|
||||
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
|
||||
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
|
||||
|
||||
@@ -13,7 +13,6 @@ export interface UseChatRouteSyncOptions {
|
||||
currentAgentId: ComputedRef<number>;
|
||||
presetQuestion: ComputedRef<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string | null>;
|
||||
shippingBatchNoFromQuery?: ComputedRef<string | null>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
resetChatStateForAgentChange: () => void;
|
||||
cancelVoiceInput: () => void;
|
||||
@@ -39,7 +38,6 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
currentAgentId,
|
||||
presetQuestion,
|
||||
shippingTaskIdFromQuery,
|
||||
shippingBatchNoFromQuery,
|
||||
resetChatStateForAgentChange,
|
||||
cancelVoiceInput,
|
||||
syncCurrentUserProfile,
|
||||
@@ -103,7 +101,7 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
loadConversation(convId, { force: true }),
|
||||
]);
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
} else if (shippingTaskIdFromQuery.value || shippingBatchNoFromQuery?.value) {
|
||||
} else if (shippingTaskIdFromQuery.value) {
|
||||
await historyPromise;
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
await resumeShippingTaskFromQuery();
|
||||
@@ -129,17 +127,16 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id, route.query.batch_no],
|
||||
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id],
|
||||
async (
|
||||
[nextAgentId, nextConversationId, nextPreset, nextTaskId, nextBatchNo],
|
||||
[prevAgentId, prevConversationId, prevPreset, prevTaskId, prevBatchNo],
|
||||
[nextAgentId, nextConversationId, nextPreset, nextTaskId],
|
||||
[prevAgentId, prevConversationId, prevPreset, prevTaskId],
|
||||
) => {
|
||||
if (
|
||||
nextAgentId === prevAgentId
|
||||
&& nextConversationId === prevConversationId
|
||||
&& nextPreset === prevPreset
|
||||
&& nextTaskId === prevTaskId
|
||||
&& nextBatchNo === prevBatchNo
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -148,7 +145,6 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
nextAgentId === prevAgentId
|
||||
&& nextPreset === prevPreset
|
||||
&& nextTaskId === prevTaskId
|
||||
&& nextBatchNo === prevBatchNo
|
||||
&& nextConversationId !== prevConversationId
|
||||
) {
|
||||
if (typeof nextConversationId === 'string' && nextConversationId) {
|
||||
|
||||
@@ -1,150 +1,36 @@
|
||||
/**
|
||||
* features/chat/composables/useChatShipping.spec.ts
|
||||
* 用途:验证发货批次切换后的默认焦点解析,避免右侧工作台沿用旧批次的 focused task。
|
||||
* 用途:验证聊天恢复只使用单票任务锚点。
|
||||
* 依赖:vitest、useChatShipping 纯函数导出。
|
||||
* 逻辑:覆盖 current focus、process summary 回退、首票回退与无任务时清空焦点原因四种路径。
|
||||
* 逻辑:历史回放只接受 task_no / shipping_ui_state,不恢复已下线批次快照。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
resolveLatestShippingMessageRecoveryPayload,
|
||||
resolveLatestShippingBatchSnapshot,
|
||||
resolveShippingBatchFocusState,
|
||||
selectShippingConversationBatch,
|
||||
} from './useChatShipping';
|
||||
|
||||
describe('useChatShipping batch focus sync', () => {
|
||||
it('prefers batch current focus task and keeps default reason', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: 'SN-BATCH-B2',
|
||||
process_summary: { current_task_no: 'SN-BATCH-B1' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-B0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-B2',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to process summary and first task when current focus is absent', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: 'SN-BATCH-C1' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-C0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-C1',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: '' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-D0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-D0',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
});
|
||||
|
||||
it('clears focus state when the new batch has no resolvable task', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: '' },
|
||||
},
|
||||
[],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: '',
|
||||
focusReason: '',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChatShipping conversation workspace selection', () => {
|
||||
const batches = [
|
||||
{ batch_no: 'SB-OLD', focus_task: { task_no: 'SN-OLD' } },
|
||||
{ batch_no: 'SB-NEW', focus_task: { task_no: 'SN-NEW' } },
|
||||
];
|
||||
|
||||
it('keeps the active batch during a normal refresh', () => {
|
||||
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', false)?.batch_no).toBe('SB-OLD');
|
||||
});
|
||||
|
||||
it('selects the latest batch after an order extraction turn', () => {
|
||||
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', true)?.batch_no).toBe('SB-NEW');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChatShipping persisted batch snapshot', () => {
|
||||
it('restores the latest valid batch snapshot from assistant message payloads', () => {
|
||||
const snapshot = resolveLatestShippingBatchSnapshot([
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '旧结果',
|
||||
payload: { shipping_batch_ui_state: { batch_no: 'SB-OLD', tasks: [] } },
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '无效结果',
|
||||
payload: { shipping_batch_ui_state: { batch_no: 'SB-INVALID' } },
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '已打开已有任务',
|
||||
payload: {
|
||||
shipping_batch_ui_state: {
|
||||
batch_no: 'SB-EXISTING',
|
||||
current_focus_task_no: 'SN-EXISTING',
|
||||
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', review_status: 'parse_review' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(snapshot?.batch_no).toBe('SB-EXISTING');
|
||||
expect(snapshot?.current_focus_task_no).toBe('SN-EXISTING');
|
||||
});
|
||||
|
||||
it('ignores malformed snapshots', () => {
|
||||
expect(resolveLatestShippingBatchSnapshot([
|
||||
{ role: 'assistant', content: '', payload: { shipping_batch_ui_state: { batch_no: 'SB-NO-TASKS' } } },
|
||||
{ role: 'user', content: '继续' },
|
||||
])).toBeNull();
|
||||
});
|
||||
});
|
||||
import { resolveLatestShippingMessageRecoveryPayload } from './useChatShipping';
|
||||
|
||||
describe('useChatShipping message recovery payload', () => {
|
||||
it('falls back to task anchor when batch snapshot is absent', () => {
|
||||
it('recovers a task anchor and read-only UI state', () => {
|
||||
const payload = resolveLatestShippingMessageRecoveryPayload([
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '已打开已有任务',
|
||||
payload: {
|
||||
task_no: 'SN-OPEN-EXISTING',
|
||||
batch_no: 'SB-OPEN-EXISTING',
|
||||
shipping_ui_state: {
|
||||
task_no: 'SN-OPEN-EXISTING',
|
||||
batch_no: 'SB-OPEN-EXISTING',
|
||||
inventory_lines_json: [{ reservation_id: 'R-1' }],
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(payload?.task_no).toBe('SN-OPEN-EXISTING');
|
||||
expect(payload?.batch_no).toBe('SB-OPEN-EXISTING');
|
||||
expect(payload?.shipping_ui_state?.task_no).toBe('SN-OPEN-EXISTING');
|
||||
expect(payload?.shipping_batch_ui_state).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a legacy batch-only payload', () => {
|
||||
expect(resolveLatestShippingMessageRecoveryPayload([
|
||||
{ role: 'assistant', content: '', payload: { shipping_batch_ui_state: { tasks: [] } } },
|
||||
])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,9 +3,8 @@
|
||||
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
|
||||
* 依赖:shipping.api(任务/客户等)、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
|
||||
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件维护会话任务摘要 + ui_state 同步,
|
||||
* 以及 focusedConversationTaskNo(提交追加优先级 / 侧栏焦点);
|
||||
* co8:shipping_batches 工作台轮询已下线,进度改由 shipping-processing projection 承接;
|
||||
* 保留 resolvedShippingBatchNo / shippingBatchSummary 等 ref 供调用方兼容,不再发起批次网络请求。
|
||||
* 以及 focusedConversationTaskNo(提交追加优先级 / 侧栏焦点)。会话恢复唯一使用 task_no;
|
||||
* 批次进度由 shipping-processing projection 承接,不维护已下线 shipping_batches 的本地快照。
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -31,7 +30,6 @@ import {
|
||||
createShippingSendHandlers,
|
||||
createShippingUploadHandlers,
|
||||
useShippingOrderExtractionRuns,
|
||||
onNoticeBatchConversationChanging,
|
||||
findLatestShippingTaskId,
|
||||
getShippingMatchResultPayload,
|
||||
getShippingParseReviewPayload,
|
||||
@@ -43,13 +41,9 @@ import {
|
||||
getWorkspaceShippingTask,
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
confirmWorkspaceShippingCustomer,
|
||||
type ShippingConversationWorkspace,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingBatchUiState,
|
||||
ShippingCustomerOption,
|
||||
} from '../types/shipping.api.types';
|
||||
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
|
||||
@@ -91,7 +85,7 @@ export interface UseChatShippingOptions {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
|
||||
@@ -100,78 +94,9 @@ export interface UseChatShippingOptions {
|
||||
createNewChatView: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析批次切换后的默认焦点状态。
|
||||
* 核心逻辑:优先取状态机记录的 current focus,其次回退到 process summary 当前任务,再回退到任务列表首票;只有拿到 task_no 才回填默认聚焦原因。
|
||||
* @param batchSummary - 当前批次摘要
|
||||
* @param batchTasks - 当前批次任务列表
|
||||
* @param defaultReason - 批次切换后写入输入栏提示的默认焦点原因
|
||||
* @returns 供步骤条、按钮与右侧工作台共用的 focus 状态;取不到 task 时返回空焦点
|
||||
*/
|
||||
export const resolveShippingBatchFocusState = (
|
||||
batchSummary: {
|
||||
current_focus_task_no?: string | null;
|
||||
process_summary?: { current_task_no?: string | null } | null;
|
||||
} | null | undefined,
|
||||
batchTasks: Array<{ task_no?: string | null }> | null | undefined,
|
||||
defaultReason: string,
|
||||
) => {
|
||||
const taskNo = String(
|
||||
batchSummary?.current_focus_task_no
|
||||
|| batchSummary?.process_summary?.current_task_no
|
||||
|| batchTasks?.[0]?.task_no
|
||||
|| '',
|
||||
).trim();
|
||||
return {
|
||||
taskNo,
|
||||
focusReason: taskNo ? defaultReason : '',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 从会话工作台选择本轮应展示的批次。
|
||||
* 核心逻辑:订单抽取完成后选服务端按创建时间升序返回的最后一个批次;普通续办优先保留当前批次。
|
||||
*/
|
||||
export const selectShippingConversationBatch = <T extends { batch_no: string; focus_task?: unknown }>(
|
||||
batches: T[],
|
||||
currentBatchNo: string,
|
||||
queryBatchNo: string,
|
||||
preferLatest = false,
|
||||
): T | undefined => (
|
||||
(preferLatest ? batches[batches.length - 1] : undefined)
|
||||
|| batches.find((item) => item.batch_no === currentBatchNo)
|
||||
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : undefined)
|
||||
|| batches.find((item) => Boolean(item.focus_task))
|
||||
|| batches[0]
|
||||
);
|
||||
|
||||
/**
|
||||
* 从消息列表解析最近一次权威批次快照。
|
||||
* 核心逻辑:只接受包含批次号和任务数组的 `shipping_batch_ui_state`,供实时终态与历史会话共用。
|
||||
* @param sourceMessages - 当前会话消息
|
||||
* @returns 最近的合法批次快照;不存在时返回 null
|
||||
*/
|
||||
export const resolveLatestShippingBatchSnapshot = (
|
||||
sourceMessages: ChatMessage[],
|
||||
): ShippingBatchUiState | null => {
|
||||
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
|
||||
const message = sourceMessages[index];
|
||||
const payload = message?.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: null;
|
||||
const rawSnapshot = payload?.shipping_batch_ui_state;
|
||||
if (!rawSnapshot || typeof rawSnapshot !== 'object') continue;
|
||||
const snapshot = rawSnapshot as ShippingBatchUiState;
|
||||
if (String(snapshot.batch_no || '').trim() && Array.isArray(snapshot.tasks)) {
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从单条助手消息中提取工作台恢复锚点。
|
||||
* 核心逻辑:优先识别合法 `shipping_batch_ui_state`,其次回退到 `task_no / batch_no / shipping_ui_state`;
|
||||
* 核心逻辑:只接受 `task_no / shipping_ui_state`;
|
||||
* 供实时终态、历史回放与刷新恢复共用。
|
||||
*/
|
||||
export const resolveShippingMessageRecoveryPayload = (
|
||||
@@ -181,34 +106,18 @@ export const resolveShippingMessageRecoveryPayload = (
|
||||
? message.payload as ShippingMessageRecoveryPayload
|
||||
: null;
|
||||
if (!payload) return null;
|
||||
const batchSnapshot = payload.shipping_batch_ui_state;
|
||||
const hasBatchSnapshot = Boolean(
|
||||
batchSnapshot
|
||||
&& String(batchSnapshot.batch_no || '').trim()
|
||||
&& Array.isArray(batchSnapshot.tasks),
|
||||
);
|
||||
const taskNo = String(
|
||||
payload.task_no
|
||||
|| payload.shipping_ui_state?.task_no
|
||||
|| batchSnapshot?.current_focus_task_no
|
||||
|| batchSnapshot?.focus_task?.task_no
|
||||
|| batchSnapshot?.tasks?.[0]?.task_no
|
||||
|| '',
|
||||
).trim();
|
||||
const batchNo = String(
|
||||
payload.batch_no
|
||||
|| payload.shipping_ui_state?.batch_no
|
||||
|| batchSnapshot?.batch_no
|
||||
|| '',
|
||||
).trim();
|
||||
const hasTaskUiState = Boolean(payload.shipping_ui_state && typeof payload.shipping_ui_state === 'object');
|
||||
if (!hasBatchSnapshot && !taskNo && !batchNo && !hasTaskUiState) {
|
||||
if (!taskNo && !hasTaskUiState) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
...payload,
|
||||
...(taskNo ? { task_no: taskNo } : {}),
|
||||
...(batchNo ? { batch_no: batchNo } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -288,160 +197,34 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
|
||||
};
|
||||
|
||||
// ── 任务编号状态(会话摘要同步,无抽屉/焦点条) ──────────────
|
||||
// ── 任务编号状态(单票恢复锚点) ─────────────────────────────
|
||||
const shippingTaskIdFromQuery = computed(() => {
|
||||
const value = route.query.task_id;
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
});
|
||||
const shippingBatchNoFromQuery = computed(() => {
|
||||
const value = route.query.batch_no;
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
});
|
||||
const resolvedShippingTaskId = ref('');
|
||||
const resolvedShippingBatchNo = ref('');
|
||||
const activeShippingBatchNo = ref('');
|
||||
const shippingConversationWorkspace = ref<ShippingConversationWorkspace | null>(null);
|
||||
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
|
||||
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
|
||||
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||||
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
||||
const lastConversationSyncKey = ref('');
|
||||
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const applyShippingBatchDetail = (
|
||||
detail: ShippingBatchUiState,
|
||||
fallbackBatchNo: string,
|
||||
) => {
|
||||
const normalizedBatchNo = detail.batch_no || fallbackBatchNo;
|
||||
resolvedShippingBatchNo.value = normalizedBatchNo;
|
||||
if (!activeShippingBatchNo.value || activeShippingBatchNo.value === fallbackBatchNo) {
|
||||
activeShippingBatchNo.value = normalizedBatchNo;
|
||||
}
|
||||
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
|
||||
shippingBatchSummary.value = {
|
||||
id: detail.id,
|
||||
batch_no: detail.batch_no,
|
||||
conversation_id: detail.conversation_id,
|
||||
current_focus_task_no: detail.focus_task?.task_no || detail.current_focus_task_no || null,
|
||||
file_count: detail.file_count,
|
||||
process_summary: detail.process_summary || null,
|
||||
created_at: detail.created_at,
|
||||
updated_at: detail.updated_at,
|
||||
};
|
||||
const preferredTaskNo = String(
|
||||
detail.focus_task?.task_no
|
||||
|| detail.process_summary?.current_task_no
|
||||
|| detail.current_focus_task_no
|
||||
|| '',
|
||||
).trim();
|
||||
if (preferredTaskNo) {
|
||||
resolvedShippingTaskId.value = preferredTaskNo;
|
||||
}
|
||||
if (detail.focus_task && detail.focus_task_ui_state) {
|
||||
activeShippingTaskDetail.value = {
|
||||
...(activeShippingTaskDetail.value || {}),
|
||||
...detail.focus_task,
|
||||
lines: activeShippingTaskDetail.value?.lines || [],
|
||||
events: activeShippingTaskDetail.value?.events || [],
|
||||
ui_state: detail.focus_task_ui_state,
|
||||
} as ShippingTaskDetail;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 同步批次摘要占位(co8 已下线批次详情 API)。
|
||||
* 按任务锚点恢复聊天工作台。
|
||||
*
|
||||
* 核心逻辑:batchNo 为空时清空摘要;否则仅回填本地 batch_no 与已有 task 焦点,不发起网络请求。
|
||||
* @param batchNo - 目标批次号
|
||||
*/
|
||||
const syncShippingBatchSummary = async (batchNo: string) => {
|
||||
const normalized = String(batchNo || '').trim();
|
||||
if (!normalized) {
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
return;
|
||||
}
|
||||
resolvedShippingBatchNo.value = normalized;
|
||||
if (!activeShippingBatchNo.value) {
|
||||
activeShippingBatchNo.value = normalized;
|
||||
}
|
||||
shippingBatchSummary.value = {
|
||||
id: 0,
|
||||
batch_no: normalized,
|
||||
conversation_id: conversationId.value,
|
||||
current_focus_task_no: resolvedShippingTaskId.value || null,
|
||||
process_summary: null,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 同步会话批次工作台(co8 已下线 conversation batches API)。
|
||||
*
|
||||
* 核心逻辑:保留调用签名供抽取 Run / 终态刷新链路兼容;始终清空 workspace 并返回 false,不发起网络。
|
||||
* @param _options - 历史参数,保留兼容
|
||||
* @returns 恒为 false
|
||||
*/
|
||||
const syncShippingConversationWorkspace = async (
|
||||
_options?: { preferLatest?: boolean },
|
||||
): Promise<boolean> => {
|
||||
void _options;
|
||||
shippingConversationWorkspace.value = null;
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从本轮 SSE 助手消息恢复权威批次快照。
|
||||
*
|
||||
* 核心逻辑:订单识别可能打开属于旧会话的已有任务,此时按当前会话补拉工作台会返回空批次;
|
||||
* 优先应用 `shipping_ui_state` 事件随消息持久化的 `shipping_batch_ui_state`,再由接口刷新后续状态。
|
||||
* @param message - 当前流式回答完成后的助手消息
|
||||
* @returns 是否找到并应用了合法批次快照
|
||||
*/
|
||||
const applyResolvedShippingBatchSnapshot = (snapshot: ShippingBatchUiState | null): boolean => {
|
||||
if (!snapshot) return false;
|
||||
const batchNo = String(snapshot.batch_no || '').trim();
|
||||
applyShippingBatchDetail(snapshot, batchNo);
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyShippingBatchSnapshot = (message: ChatMessage): boolean => (
|
||||
applyResolvedShippingBatchSnapshot(resolveLatestShippingBatchSnapshot([message]))
|
||||
);
|
||||
|
||||
/**
|
||||
* 按“批次快照 -> 任务/批次锚点 -> 会话工作台”顺序恢复聊天工作台。
|
||||
*
|
||||
* 核心逻辑:`open_existing` 可能只携带 `task_no / shipping_ui_state`;此时先恢复任务锚点并补拉任务详情,
|
||||
* 再尝试按任务所属批次加载批次详情,最后才回退到当前会话工作台。
|
||||
* 核心逻辑:`open_existing` 携带 `task_no / shipping_ui_state`;恢复任务锚点后补拉任务详情。
|
||||
* @param payload - 从消息中解析出的恢复载荷
|
||||
* @returns 是否至少恢复出一层任务或批次上下文
|
||||
* @returns 是否恢复出任务上下文
|
||||
*/
|
||||
const applyResolvedShippingMessageRecovery = async (
|
||||
payload: ShippingMessageRecoveryPayload | null,
|
||||
): Promise<boolean> => {
|
||||
if (!payload) return false;
|
||||
let recovered = false;
|
||||
const snapshot = payload.shipping_batch_ui_state ?? null;
|
||||
if (applyResolvedShippingBatchSnapshot(snapshot)) {
|
||||
recovered = true;
|
||||
}
|
||||
|
||||
const taskNo = String(
|
||||
payload.task_no
|
||||
|| payload.shipping_ui_state?.task_no
|
||||
|| '',
|
||||
).trim().toUpperCase();
|
||||
let batchNo = String(
|
||||
payload.batch_no
|
||||
|| payload.shipping_ui_state?.batch_no
|
||||
|| snapshot?.batch_no
|
||||
|| '',
|
||||
).trim();
|
||||
|
||||
if (batchNo) {
|
||||
resolvedShippingBatchNo.value = batchNo;
|
||||
activeShippingBatchNo.value = batchNo;
|
||||
}
|
||||
if (taskNo) {
|
||||
resolvedShippingTaskId.value = taskNo;
|
||||
}
|
||||
@@ -449,52 +232,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
activeShippingTaskDetail.value = {
|
||||
...(activeShippingTaskDetail.value || {}),
|
||||
task_no: taskNo,
|
||||
batch_no: batchNo || payload.shipping_ui_state.batch_no || null,
|
||||
lines: activeShippingTaskDetail.value?.lines || [],
|
||||
events: activeShippingTaskDetail.value?.events || [],
|
||||
ui_state: payload.shipping_ui_state,
|
||||
} as ShippingTaskDetail;
|
||||
recovered = true;
|
||||
}
|
||||
if (!snapshot && batchNo) {
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
recovered = true;
|
||||
}
|
||||
if (taskNo) {
|
||||
await syncActiveShippingTaskDetail(taskNo);
|
||||
const detailBatchNo = String(activeShippingTaskDetail.value?.batch_no || '').trim();
|
||||
if (detailBatchNo) {
|
||||
batchNo = detailBatchNo;
|
||||
resolvedShippingBatchNo.value = detailBatchNo;
|
||||
activeShippingBatchNo.value = detailBatchNo;
|
||||
}
|
||||
if (!snapshot && batchNo && String(shippingBatchSummary.value?.batch_no || '').trim() !== batchNo) {
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
recovered = true;
|
||||
}
|
||||
recovered = recovered || Boolean(activeShippingTaskDetail.value);
|
||||
}
|
||||
return recovered || Boolean(batchNo);
|
||||
return recovered;
|
||||
};
|
||||
|
||||
const applyShippingMessageRecovery = async (message: ChatMessage): Promise<boolean> => (
|
||||
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
|
||||
);
|
||||
|
||||
/**
|
||||
* 切换会话上传摘要中的活动批次(co8 已下线,保留签名兼容)。
|
||||
*
|
||||
* 核心逻辑:批次工作台 API 已移除,调用时仅提示用户改由右侧 processing 工作台操作。
|
||||
* @param batchNo - 目标批次号
|
||||
* @returns 恒为 false
|
||||
*/
|
||||
const switchShippingBatch = async (batchNo: string) => {
|
||||
const normalizedBatchNo = String(batchNo || '').trim();
|
||||
if (!normalizedBatchNo) return false;
|
||||
msg.warning(t('chat.shippingNoticeUi.batchSwitchRemoved'));
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 清空当前聊天页绑定的发货任务上下文。
|
||||
*
|
||||
@@ -512,11 +266,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingInventorySelectionActive.value = false;
|
||||
shippingInventorySelectionTaskId.value = '';
|
||||
resolvedShippingTaskId.value = '';
|
||||
resolvedShippingBatchNo.value = '';
|
||||
activeShippingBatchNo.value = '';
|
||||
shippingConversationWorkspace.value = null;
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
activeShippingTaskDetail.value = null;
|
||||
lastConversationSyncKey.value = '';
|
||||
};
|
||||
@@ -527,16 +276,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|| shippingTaskIdFromQuery.value
|
||||
|| '';
|
||||
|
||||
const getActiveShippingBatchNo = () =>
|
||||
activeShippingBatchNo.value
|
||||
|| resolvedShippingBatchNo.value
|
||||
|| shippingBatchNoFromQuery.value
|
||||
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|
||||
|| '';
|
||||
|
||||
const getCurrentShippingChatContext = () => ({
|
||||
task_id: getActiveBatchTaskId() || getActiveShippingTaskId(),
|
||||
batch_no: getActiveShippingBatchNo(),
|
||||
task_id: getActiveShippingTaskId(),
|
||||
});
|
||||
|
||||
const getCurrentShippingChatContextWithDisplay = (displayQuery: string) => ({
|
||||
@@ -544,23 +285,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
display_query: displayQuery,
|
||||
});
|
||||
|
||||
const getActiveBatchTaskId = () => String(
|
||||
shippingBatchSummary.value?.current_focus_task_no
|
||||
|| shippingBatchSummary.value?.process_summary?.current_task_no
|
||||
|| shippingBatchTasks.value[0]?.task_no
|
||||
|| resolvedShippingTaskId.value
|
||||
|| '',
|
||||
).trim();
|
||||
|
||||
const hasRunningShippingBatchTasks = () =>
|
||||
shippingBatchTasks.value.some(
|
||||
(task) => String(task.ui_state?.stage?.code || '').trim() !== 'upload_complete',
|
||||
);
|
||||
|
||||
/**
|
||||
* 同步当前焦点任务详情,并在仅恢复 `task_no` 的场景下补齐 `batch_no` 上下文。
|
||||
* 同步当前焦点任务详情。
|
||||
*
|
||||
* 核心逻辑:先拉取任务详情,再把详情里的批次号回填到聊天状态,确保会话恢复后仍能继续按批次模式加载 2 票/多票摘要。
|
||||
* 核心逻辑:仅拉取任务详情;批次进度由独立 processing projection 提供。
|
||||
* @param taskId - 可选任务编号;未传时回退到当前激活任务
|
||||
*/
|
||||
const syncActiveShippingTaskDetail = async (taskId?: string) => {
|
||||
@@ -571,16 +299,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
try {
|
||||
const detail = await getWorkspaceShippingTask(normalized);
|
||||
const detailBatchNo = String(detail.batch_no || '').trim();
|
||||
const activeBatchNo = String(activeShippingBatchNo.value || '').trim();
|
||||
if (activeBatchNo && detailBatchNo && detailBatchNo !== activeBatchNo) {
|
||||
return;
|
||||
}
|
||||
activeShippingTaskDetail.value = detail;
|
||||
if (detailBatchNo && resolvedShippingBatchNo.value !== detailBatchNo) {
|
||||
resolvedShippingBatchNo.value = detailBatchNo;
|
||||
activeShippingBatchNo.value = activeShippingBatchNo.value || detailBatchNo;
|
||||
}
|
||||
} catch {
|
||||
activeShippingTaskDetail.value = null;
|
||||
}
|
||||
@@ -637,7 +356,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
isThinking,
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery,
|
||||
getActiveBatchTaskId,
|
||||
getActiveShippingTaskId,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -649,10 +368,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const finalizeShippingAssistantMessage = async () => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
await shippingIntakes.refreshStatuses();
|
||||
if (!(await syncShippingConversationWorkspace())) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
await syncShippingConversationWorkspace();
|
||||
}
|
||||
shippingIntakes.clearConsumedAttachments();
|
||||
await refreshShippingActions();
|
||||
};
|
||||
@@ -666,15 +381,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const resolveShippingTaskForShortageQuery = async (taskNo?: string) => {
|
||||
const normalizedTaskNo = String(
|
||||
taskNo
|
||||
|| getActiveBatchTaskId()
|
||||
|| getActiveShippingTaskId()
|
||||
|| '',
|
||||
).trim().toUpperCase();
|
||||
if (!normalizedTaskNo) return null;
|
||||
const summaryTask = shippingBatchTasks.value.find(
|
||||
(item) => String(item.task_no || '').trim().toUpperCase() === normalizedTaskNo,
|
||||
);
|
||||
if (summaryTask && hasShortageLines(summaryTask)) return summaryTask;
|
||||
const detail = activeShippingTaskDetail.value;
|
||||
if (String(detail?.task_no || '').trim().toUpperCase() === normalizedTaskNo && hasShortageLines(detail)) {
|
||||
return detail;
|
||||
@@ -682,7 +392,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
try {
|
||||
return await getWorkspaceShippingTask(normalizedTaskNo);
|
||||
} catch {
|
||||
return summaryTask || null;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -772,7 +482,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
|
||||
getOrderExtractionReview: shippingIntakes.getOrderExtractionReview,
|
||||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||||
syncShippingConversationWorkspace,
|
||||
refreshShippingActions,
|
||||
loadHistory,
|
||||
onConversationResolved: async (resolvedConversationId) => {
|
||||
@@ -962,6 +671,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const {
|
||||
handleShippingAutoUploadFile,
|
||||
handleShippingAutoUploadNoticeBatch,
|
||||
openShippingInventoryPicker,
|
||||
openShippingNoticePicker,
|
||||
selectShippingInventoryUploadTask,
|
||||
cancelShippingInventoryTaskSelection,
|
||||
@@ -981,9 +691,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
pendingShippingNoticeTaskId,
|
||||
pendingShippingInventoryFile,
|
||||
resolvedShippingTaskId,
|
||||
resolvedShippingBatchNo,
|
||||
shippingBatchSummary,
|
||||
shippingBatchTasks,
|
||||
shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId,
|
||||
getActiveShippingTaskId,
|
||||
@@ -1013,6 +720,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
getActiveShippingTaskId,
|
||||
messages,
|
||||
sendShippingMenuMessage,
|
||||
openShippingInventoryPicker,
|
||||
openShippingNoticePicker,
|
||||
openShippingCustomerDialog,
|
||||
executeShippingDecision,
|
||||
@@ -1033,7 +741,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
attachments,
|
||||
shippingAutoFlowRequested,
|
||||
resolvedShippingTaskId,
|
||||
getActiveShippingBatchNo,
|
||||
currentAgentId,
|
||||
selectedKb,
|
||||
attachmentPolicy,
|
||||
@@ -1060,8 +767,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||||
startOrderExtractionRun: shippingOrderExtractionRuns.startRun,
|
||||
applyShippingMessageRecovery,
|
||||
applyShippingBatchSnapshot,
|
||||
syncShippingConversationWorkspace,
|
||||
refreshShippingActions,
|
||||
shippingSuggestedPrompt,
|
||||
isShippingShortageQueryIntent,
|
||||
@@ -1072,19 +777,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|
||||
// ── 路由 / 会话生命周期 ───────────────────────────────────
|
||||
/**
|
||||
* 根据路由中的 `task_id/batch_no` 恢复发货任务上下文。
|
||||
* 核心逻辑:优先同步显式传入的批次摘要;若仍缺少会话,则直接基于 `task_id` 发起一次继续任务请求,
|
||||
* 禁止再按历史标题模糊猜测旧会话,避免多批次/多票场景跳进错误会话。
|
||||
* 根据路由中的 `task_id` 恢复发货任务上下文。
|
||||
* 核心逻辑:直接基于明确 task_id 发起一次继续任务请求,禁止按历史标题模糊猜测会话。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const resumeShippingTaskFromQuery = async () => {
|
||||
const batchNo = shippingBatchNoFromQuery.value;
|
||||
if (batchNo && isShippingNoticeAgent.value) {
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
if (!shippingTaskIdFromQuery.value && resolvedShippingTaskId.value) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const taskId = shippingTaskIdFromQuery.value;
|
||||
if (!taskId || !isShippingNoticeAgent.value) return;
|
||||
if (route.query.conversation_id) return;
|
||||
@@ -1103,7 +800,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
};
|
||||
|
||||
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
||||
onNoticeBatchConversationChanging(nextId, prevId);
|
||||
shippingIntakes.stopPolling();
|
||||
if (nextId && nextId !== prevId) {
|
||||
focusedConversationTaskNo.value = null;
|
||||
@@ -1114,28 +810,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
if (prevId !== nextId) {
|
||||
resolvedShippingTaskId.value = '';
|
||||
if (!shippingBatchNoFromQuery.value) {
|
||||
resolvedShippingBatchNo.value = '';
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 重试当前聚焦批次中可恢复的失败/排队任务(co8 已下线,保留签名兼容)。
|
||||
*
|
||||
* 核心逻辑:批次重试 API 已移除,调用时提示用户改由 processing 工作台或任务动作重试。
|
||||
* @returns 恒为 null
|
||||
*/
|
||||
const retryCurrentShippingBatchPendingTasks = async (): Promise<{
|
||||
started: number;
|
||||
skipped: number;
|
||||
} | null> => {
|
||||
msg.warning(t('chat.shippingNoticeUi.batchRetryRemoved'));
|
||||
return null;
|
||||
};
|
||||
|
||||
const handleShippingLocalFilesSelected = (event: Event): boolean => {
|
||||
if (!isShippingNoticeAgent.value) return false;
|
||||
const inputEl = event.target as HTMLInputElement | null;
|
||||
@@ -1167,7 +844,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const onConversationLoadedEmpty = async () => {
|
||||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
|
||||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||||
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
|
||||
await router.replace({ path: route.path, query: nextQuery });
|
||||
};
|
||||
|
||||
@@ -1175,7 +851,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
|
||||
createNewChatView();
|
||||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||||
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
|
||||
void router.replace({ path: route.path, query: nextQuery });
|
||||
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: shippingTaskIdFromQuery.value });
|
||||
await sendMessage(
|
||||
@@ -1200,18 +875,18 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingStatusPollTimer = null;
|
||||
}
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
const taskId = getActiveShippingTaskId();
|
||||
if (!taskId) return;
|
||||
|
||||
shippingStatusPollTimer = setInterval(() => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
const nextTaskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
const nextTaskId = getActiveShippingTaskId();
|
||||
if (!nextTaskId) return;
|
||||
void (async () => {
|
||||
await syncActiveShippingTaskDetail(nextTaskId);
|
||||
await syncConversationMessagesIfNeeded(nextTaskId);
|
||||
await refreshShippingActions();
|
||||
if (!hasRunningShippingBatchTasks() && !isShippingActionBusy.value && shippingStatusPollTimer) {
|
||||
if (!isShippingActionBusy.value && shippingStatusPollTimer) {
|
||||
clearInterval(shippingStatusPollTimer);
|
||||
shippingStatusPollTimer = null;
|
||||
}
|
||||
@@ -1232,15 +907,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
});
|
||||
const shippingRecoveryWatchKey = computed(() => {
|
||||
const recovery = resolveLatestShippingMessageRecoveryPayload(messages.value);
|
||||
const snapshot = recovery?.shipping_batch_ui_state;
|
||||
const uiState = recovery?.shipping_ui_state;
|
||||
return [
|
||||
String(conversationId.value || ''),
|
||||
String(recovery?.batch_no || snapshot?.batch_no || uiState?.batch_no || ''),
|
||||
String(recovery?.task_no || snapshot?.current_focus_task_no || uiState?.task_no || ''),
|
||||
String(snapshot?.updated_at || ''),
|
||||
String(recovery?.task_no || uiState?.task_no || ''),
|
||||
String(uiState?.updated_at || ''),
|
||||
String(snapshot?.tasks.length || 0),
|
||||
].join('|');
|
||||
});
|
||||
watch([shippingRecoveryWatchKey, isShippingNoticeAgent], () => {
|
||||
@@ -1249,7 +920,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}, { immediate: true });
|
||||
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
|
||||
void refreshShippingActions().then(async () => {
|
||||
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
const taskId = getActiveShippingTaskId();
|
||||
await Promise.all([
|
||||
syncShippingParseReviewCard(taskId),
|
||||
syncActiveShippingTaskDetail(taskId),
|
||||
@@ -1257,19 +928,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
await syncConversationMessagesIfNeeded(taskId);
|
||||
});
|
||||
});
|
||||
watch([activeShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingBatchNo], ([activeBatchNo, queryBatchNo, batchNo]) => {
|
||||
const nextBatchNo = String(activeBatchNo || queryBatchNo || batchNo || '').trim();
|
||||
if (!nextBatchNo) {
|
||||
shippingBatchSummary.value = null;
|
||||
return;
|
||||
}
|
||||
void syncShippingBatchSummary(nextBatchNo);
|
||||
}, { immediate: true });
|
||||
watch([conversationId, isShippingNoticeAgent], () => {
|
||||
void syncShippingConversationWorkspace();
|
||||
}, { immediate: true });
|
||||
watch(
|
||||
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
|
||||
[isShippingNoticeAgent, conversationId, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
|
||||
() => {
|
||||
restartShippingStatusPolling();
|
||||
},
|
||||
@@ -1294,18 +954,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingInventorySelectionTaskId,
|
||||
allowsSendWithAttachmentsOnly,
|
||||
shippingTaskIdFromQuery,
|
||||
shippingBatchNoFromQuery,
|
||||
resolvedShippingBatchNo,
|
||||
activeShippingBatchNo,
|
||||
shippingConversationWorkspace,
|
||||
shippingBatchSummary,
|
||||
shippingBatchTasks,
|
||||
isShippingActionBusy,
|
||||
activeShippingTaskDetail,
|
||||
getCurrentShippingChatContext,
|
||||
getActiveShippingBatchNo,
|
||||
switchShippingBatch,
|
||||
retryCurrentShippingBatchPendingTasks,
|
||||
queryShippingShortageDetails,
|
||||
resetShippingConversationState,
|
||||
resumeShippingTaskFromQuery,
|
||||
|
||||
@@ -65,15 +65,16 @@ describe('shipping order review workbench viewport layout contract', () => {
|
||||
expect(share1440).toBeGreaterThanOrEqual(0.62);
|
||||
});
|
||||
|
||||
it('keeps four lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
|
||||
it('keeps five lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
|
||||
const lifecycleNavigation = readFileSync(lifecycleNavigationPath, 'utf8');
|
||||
const reviewWorkbench = readFileSync(reviewWorkbenchPath, 'utf8');
|
||||
|
||||
// 关键断言:接收解析为第四阶段;必须断言真实导航组件,不能只验证 spec 内常量。
|
||||
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-4"');
|
||||
// 关键断言:导航真实渲染五个业务阶段,不能只验证 spec 内常量。
|
||||
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-5"');
|
||||
// sidebar/sidebar_search 是唯一允许预留 16rem 的模式;tabs/hidden/narrow 均落入 contents。
|
||||
expect(reviewWorkbench).toMatch(/reviewDocumentNavigationMode\.value === 'sidebar'\s*\|\|\s*reviewDocumentNavigationMode\.value === 'sidebar_search'/);
|
||||
expect(reviewWorkbench).toMatch(/:class="reviewDocumentNavigationUsesSidebar\s*\? 'grid gap-2 lg:grid-cols-\[16rem_minmax\(0,1fr\)\] lg:items-start lg:gap-3'\s*:\s*'contents'"/);
|
||||
expect(reviewWorkbench).toContain('reviewDocumentNavigationCollapsed');
|
||||
expect(reviewWorkbench).toContain('lg:grid-cols-[16rem_minmax(0,1fr)]');
|
||||
expect(reviewWorkbench).not.toMatch(/reviewDocumentNavigationMode\.value === '(?:tabs|hidden|narrow)'\s*\?\s*'[^']*16rem/);
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,6 @@ import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createChatPageConversationApi } from './useChatPageConversation';
|
||||
import {
|
||||
clearPendingNoticeBatchRetry,
|
||||
createShippingUploadHandlers,
|
||||
resetShippingNoticeBatchSubmitStateForTests,
|
||||
type ShippingUploadHandlerContext,
|
||||
@@ -49,13 +48,11 @@ const createConversationContext = () => {
|
||||
messages.value = loaded;
|
||||
},
|
||||
createNewChatView,
|
||||
clearPendingNoticeBatchRetry,
|
||||
onConversationIdChanging: vi.fn(),
|
||||
onConversationLoadedEmpty: vi.fn(async () => undefined),
|
||||
onConversationLoadFailed: vi.fn(async () => undefined),
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
shippingBatchNoFromQuery: computed(() => ''),
|
||||
clearHistory: vi.fn(),
|
||||
clearAttachments: vi.fn(),
|
||||
input: ref(''),
|
||||
@@ -86,9 +83,6 @@ const createUploadContext = (
|
||||
pendingShippingNoticeTaskId: ref(''),
|
||||
pendingShippingInventoryFile: ref(null),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
resolvedShippingBatchNo: ref(''),
|
||||
shippingBatchSummary: ref(null),
|
||||
shippingBatchTasks: ref([]),
|
||||
shippingInventorySelectionActive: ref(false),
|
||||
shippingInventorySelectionTaskId: ref(''),
|
||||
getActiveShippingTaskId: () => '',
|
||||
|
||||
@@ -17,13 +17,11 @@ export interface ChatPageConversationContext {
|
||||
isThinking: Ref<boolean>;
|
||||
loadConversationState: (id: string, loaded: ChatMessage[]) => void;
|
||||
createNewChatView: () => void;
|
||||
clearPendingNoticeBatchRetry: () => void;
|
||||
onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void;
|
||||
onConversationLoadedEmpty: () => Promise<void>;
|
||||
onConversationLoadFailed: () => Promise<void>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
shippingBatchNoFromQuery?: ComputedRef<string>;
|
||||
clearHistory: () => void;
|
||||
clearAttachments: () => void;
|
||||
input: Ref<string>;
|
||||
@@ -98,7 +96,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
await ctx.onConversationLoadFailed();
|
||||
if (
|
||||
ctx.isShippingNoticeAgent.value
|
||||
&& (ctx.shippingTaskIdFromQuery.value || ctx.shippingBatchNoFromQuery?.value)
|
||||
&& ctx.shippingTaskIdFromQuery.value
|
||||
&& !ctx.isThinking.value
|
||||
) {
|
||||
return;
|
||||
@@ -108,7 +106,6 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
};
|
||||
|
||||
const startNewChat = () => {
|
||||
ctx.clearPendingNoticeBatchRetry();
|
||||
ctx.createNewChatView();
|
||||
ctx.clearAttachments();
|
||||
ctx.input.value = '';
|
||||
@@ -122,7 +119,6 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
};
|
||||
|
||||
const resetChatStateForAgentChange = () => {
|
||||
ctx.clearPendingNoticeBatchRetry();
|
||||
ctx.createNewChatView();
|
||||
ctx.clearHistory();
|
||||
ctx.clearAttachments();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/page/useChatPageDialogs.ts
|
||||
* 用途:对话页删除确认、发货「重试所有失败」确认、反馈弹窗与轻量 toast 状态。
|
||||
* 用途:对话页删除确认、反馈弹窗与轻量 toast 状态。
|
||||
* 依赖:vue computed/ref、chat.types。
|
||||
* 逻辑:由 useChatPage 组装;ChatViewOverlays 绑定 DeleteConfirmDialog 与 toast 条。
|
||||
*/
|
||||
@@ -43,37 +43,6 @@ export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
closeDeleteConfirmDialog();
|
||||
};
|
||||
|
||||
const showRetryFailedConfirmDialog = ref(false);
|
||||
let pendingRetryFailedAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
/**
|
||||
* 打开「重试所有失败」确认弹窗。
|
||||
* 核心逻辑:仅登记确认后要执行的动作,实际请求由调用方注入。
|
||||
* @param onConfirm - 用户点「确认重试」后执行的回调
|
||||
*/
|
||||
const openRetryFailedConfirm = (onConfirm: () => Promise<void> | void) => {
|
||||
pendingRetryFailedAction = onConfirm;
|
||||
showRetryFailedConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
/** 关闭重试确认弹窗并清空待执行动作。 */
|
||||
const closeRetryFailedConfirm = () => {
|
||||
showRetryFailedConfirmDialog.value = false;
|
||||
pendingRetryFailedAction = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 用户确认后执行重试动作;弹窗由 DeleteConfirmDialog 自行关闭。
|
||||
* 核心逻辑:取出并清空 pending,再 await 执行,避免重复确认。
|
||||
*/
|
||||
const handleRetryFailedConfirm = async () => {
|
||||
const action = pendingRetryFailedAction;
|
||||
pendingRetryFailedAction = null;
|
||||
showRetryFailedConfirmDialog.value = false;
|
||||
if (!action) return;
|
||||
await action();
|
||||
};
|
||||
|
||||
const shippingToastMessage = ref('');
|
||||
let shippingToastTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
@@ -85,7 +54,7 @@ export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
};
|
||||
|
||||
/**
|
||||
* 展示非阻塞顶部 toast(用于发货批量重试等轻量成功反馈)。
|
||||
* 展示非阻塞顶部 toast。
|
||||
* @param message - toast 正文;空字符串视为关闭
|
||||
*/
|
||||
const showShippingToast = (message: string) => {
|
||||
@@ -143,10 +112,6 @@ export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
openDeleteConfirmDialog,
|
||||
closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm,
|
||||
showRetryFailedConfirmDialog,
|
||||
openRetryFailedConfirm,
|
||||
closeRetryFailedConfirm,
|
||||
handleRetryFailedConfirm,
|
||||
shippingToastMessage,
|
||||
showShippingToast,
|
||||
clearShippingToast,
|
||||
|
||||
@@ -38,6 +38,7 @@ function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSe
|
||||
refreshHistoryAfterSend: vi.fn(async () => undefined),
|
||||
refreshConversationAfterSend: vi.fn(async () => undefined),
|
||||
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
|
||||
tryHandleProcurementContractSend: vi.fn(async () => false),
|
||||
tryHandleLeaveSend: vi.fn(() => false),
|
||||
tryHandleShippingSend: vi.fn(async () => false),
|
||||
refreshToolRunProgressAfterSend: vi.fn(async () => undefined),
|
||||
|
||||
@@ -55,7 +55,7 @@ export interface ChatPageSendContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
refreshHistoryAfterSend: () => Promise<void>;
|
||||
@@ -81,7 +81,7 @@ export interface ChatPageSendContext {
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string, values?: Record<string, unknown>) => string;
|
||||
copiedIndex: Ref<number | null>;
|
||||
getChatContext?: () => { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string };
|
||||
getChatContext?: () => { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string };
|
||||
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* features/chat/shipping-review/showReviewResumeOutcome.spec.ts
|
||||
* 用途:验证复核保存后的后端入队结果会被明确展示,避免用户误以为校验后没有推进。
|
||||
* 依赖:Vitest、showReviewResumeOutcome。
|
||||
* 逻辑:队列状态统一提示已入队;其他结果保持既有自动建单和兜底提示。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { showReviewResumeOutcome } from './showReviewResumeOutcome';
|
||||
|
||||
const translate = (key: string, values?: Record<string, unknown>) => (
|
||||
values?.taskNo ? `${key}:${values.taskNo}` : key
|
||||
);
|
||||
|
||||
describe('showReviewResumeOutcome', () => {
|
||||
it.each(['auto_create_enqueued', 'already_queued', 'already_running'])(
|
||||
'shows the queued progression message for %s',
|
||||
(outcome) => {
|
||||
const success = vi.fn();
|
||||
showReviewResumeOutcome({ outcome }, { success }, translate);
|
||||
|
||||
// 关键断言:用户必须看到后端已接收自动建单,而非泛化的保存成功。
|
||||
expect(success).toHaveBeenCalledWith('chat.shippingOrderReview.resume.autoCreateEnqueued');
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps the explicit auto-created message for synchronous creation', () => {
|
||||
const success = vi.fn();
|
||||
showReviewResumeOutcome({ outcome: 'auto_created', task_no: 'OT-1' }, { success }, translate);
|
||||
expect(success).toHaveBeenCalledWith('chat.shippingOrderReview.resume.autoCreated:OT-1');
|
||||
});
|
||||
|
||||
it.each(['waiting_manual_confirm', 'blocked'])('uses warning for non-success outcome %s', (outcome) => {
|
||||
const success = vi.fn();
|
||||
const warning = vi.fn();
|
||||
showReviewResumeOutcome({ outcome }, { success, warning }, translate, '保存成功');
|
||||
|
||||
// 关键断言:保存完成不等于自动建单完成,阻断状态不得显示绿色成功。
|
||||
expect(success).not.toHaveBeenCalled();
|
||||
expect(warning).toHaveBeenCalledWith(`chat.shippingOrderReview.resume.${outcome === 'blocked' ? 'blocked' : 'waitingManualConfirm'}`);
|
||||
});
|
||||
|
||||
it('uses fallback success only when backend has no resume outcome', () => {
|
||||
const success = vi.fn();
|
||||
const warning = vi.fn();
|
||||
showReviewResumeOutcome(null, { success, warning }, translate, '保存成功');
|
||||
expect(success).toHaveBeenCalledWith('保存成功');
|
||||
expect(warning).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -9,11 +9,14 @@ import type { ShippingOrderReviewResumeOutcome } from '../types/shipping.api.typ
|
||||
|
||||
type ToastApi = {
|
||||
success: (message: string) => void;
|
||||
warning: (message: string) => void;
|
||||
error?: (message: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* 按 resume_outcome 展示成功提示;无 outcome 时使用 fallbackSuccess。
|
||||
* 核心逻辑:auto_created/idempotent_replay → 自动建单;waiting_manual_confirm → 待人工确认。
|
||||
* 核心逻辑:auto_create_enqueued → 已入队等待 Worker;auto_created/idempotent_replay → 自动建单;
|
||||
* waiting_manual_confirm → 已提交但未满足自动建单门禁(兼容历史 outcome 名称)。
|
||||
* @param resume - 后端统一恢复协调结果
|
||||
* @param msg - useMessage 实例
|
||||
* @param t - vue-i18n translate
|
||||
@@ -27,6 +30,10 @@ export function showReviewResumeOutcome(
|
||||
fallbackSuccess?: string,
|
||||
): void {
|
||||
const outcome = String(resume?.outcome || '').trim();
|
||||
if (outcome === 'auto_create_enqueued' || outcome === 'already_queued' || outcome === 'already_running') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.autoCreateEnqueued'));
|
||||
return;
|
||||
}
|
||||
if (outcome === 'auto_created' || outcome === 'idempotent_replay') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.autoCreated', {
|
||||
taskNo: resume?.task_no || '',
|
||||
@@ -34,7 +41,15 @@ export function showReviewResumeOutcome(
|
||||
return;
|
||||
}
|
||||
if (outcome === 'waiting_manual_confirm') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
|
||||
msg.warning(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
|
||||
return;
|
||||
}
|
||||
if (outcome === 'blocked') {
|
||||
msg.warning(t('chat.shippingOrderReview.resume.blocked'));
|
||||
return;
|
||||
}
|
||||
if (outcome === 'auto_create_failed') {
|
||||
(msg.error || msg.warning)(t('chat.shippingOrderReview.resume.autoCreateFailed'));
|
||||
return;
|
||||
}
|
||||
if (fallbackSuccess) {
|
||||
|
||||
@@ -432,10 +432,11 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
resume_outcome: { outcome: 'auto_create_enqueued' },
|
||||
});
|
||||
|
||||
await review.validate();
|
||||
const resume = await review.validate();
|
||||
|
||||
expect(api.validateDraft).toHaveBeenCalledWith('CASE-1', 2);
|
||||
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
|
||||
expect(resume).toEqual({ outcome: 'auto_create_enqueued' });
|
||||
});
|
||||
|
||||
it('refreshes the current Case silently without entering the PDF-switch loading state', async () => {
|
||||
@@ -669,6 +670,181 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-B');
|
||||
});
|
||||
|
||||
it('aborts the previous Case snapshot request when the user immediately selects another PDF', async () => {
|
||||
let firstSignal: AbortSignal | undefined;
|
||||
let firstEvidenceSignal: AbortSignal | undefined;
|
||||
api.getCase.mockImplementation((caseNo: string, signal?: AbortSignal) => {
|
||||
if (caseNo !== 'CASE-A') return Promise.resolve(buildCase({ case_no: caseNo }));
|
||||
firstSignal = signal;
|
||||
return new Promise((_, reject) => {
|
||||
signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
|
||||
});
|
||||
});
|
||||
api.getEvidence.mockImplementation((_caseNo: string, signal?: AbortSignal) => {
|
||||
if (!firstEvidenceSignal) firstEvidenceSignal = signal;
|
||||
return Promise.resolve({ items: [] });
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
const pendingA = review.selectCase('CASE-A');
|
||||
await review.selectCase('CASE-B');
|
||||
|
||||
// 关键断言:快速跳过 A 时必须释放其仍在途的快照读取,不能只在 UI 丢弃迟到结果。
|
||||
expect(firstSignal?.aborted).toBe(true);
|
||||
expect(firstEvidenceSignal?.aborted).toBe(true);
|
||||
await expect(pendingA).resolves.toBeUndefined();
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-B');
|
||||
});
|
||||
|
||||
it('keeps the latest Run and Case when an older load response arrives last', async () => {
|
||||
// 关键断言:重识别跳转新版本后,旧 Run 的迟到响应不得覆盖新版工作面。
|
||||
let resolveOldRun: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getRun.mockImplementation((runNo: string) => (runNo === 'RUN-OLD'
|
||||
? new Promise<Record<string, unknown>>((resolve) => { resolveOldRun = resolve; })
|
||||
: Promise.resolve({
|
||||
run_no: runNo,
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-NEW', document_id: 2, status: 'draft', issue_count: 0 }],
|
||||
})));
|
||||
api.getQueue.mockImplementation((runNo: string) => Promise.resolve({
|
||||
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
|
||||
items: [{
|
||||
case_no: runNo === 'RUN-OLD' ? 'CASE-OLD' : 'CASE-NEW',
|
||||
document_id: runNo === 'RUN-OLD' ? 1 : 2,
|
||||
source_run_no: runNo,
|
||||
status: 'draft', issue_count: 0, available_actions: [],
|
||||
}],
|
||||
}));
|
||||
api.getCase.mockImplementation((caseNo: string) => Promise.resolve(buildCase({
|
||||
case_no: caseNo,
|
||||
run_no: caseNo === 'CASE-OLD' ? 'RUN-OLD' : 'RUN-NEW',
|
||||
document: {
|
||||
id: caseNo === 'CASE-OLD' ? 1 : 2,
|
||||
file_name: caseNo === 'CASE-OLD' ? 'old.pdf' : 'new.pdf',
|
||||
},
|
||||
})));
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
const olderLoad = review.load('RUN-OLD', 'CASE-OLD');
|
||||
await Promise.resolve();
|
||||
await review.load('RUN-NEW', 'CASE-NEW');
|
||||
|
||||
resolveOldRun?.({
|
||||
run_no: 'RUN-OLD',
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-OLD', document_id: 1, status: 'superseded', issue_count: 0 }],
|
||||
});
|
||||
await olderLoad;
|
||||
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-NEW');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-NEW');
|
||||
});
|
||||
|
||||
it('marks only the first successful Run read as initial loading', async () => {
|
||||
// 关键断言:后续 Run 切换仍可有 Run 读取态,但不能再被页面当作首次整页加载。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
expect(review.initialLoading.value).toBe(false);
|
||||
|
||||
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => {
|
||||
resolveRun = resolve;
|
||||
}));
|
||||
const pending = review.load('RUN-2', 'CASE-2');
|
||||
expect(review.runLoading.value).toBe(true);
|
||||
expect(review.initialLoading.value).toBe(false);
|
||||
|
||||
resolveRun?.({
|
||||
run_no: 'RUN-2', summary: {},
|
||||
items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }],
|
||||
});
|
||||
await pending;
|
||||
});
|
||||
|
||||
it('shows the cross-Run target Case when its snapshot arrives before slow navigation summaries', async () => {
|
||||
// 关键断言:目标 Case/Evidence 是当前 PDF 的事实源;慢 Run/Queue 仅延后导航校准,
|
||||
// 绝不能继续阻塞用户看到已完成读取的目标文件。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
const previousQueue = review.reviewQueue.value;
|
||||
|
||||
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
|
||||
let resolveQueue: ((value: Record<string, unknown>) => void) | null = null;
|
||||
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
|
||||
let resolveEvidence: ((value: { items: unknown[] }) => void) | null = null;
|
||||
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveRun = resolve; }));
|
||||
api.getQueue.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveQueue = resolve; }));
|
||||
api.getCase.mockImplementationOnce(() => new Promise<ShippingOrderReviewCase>((resolve) => { resolveCase = resolve; }));
|
||||
api.getEvidence.mockImplementationOnce(() => new Promise<{ items: unknown[] }>((resolve) => { resolveEvidence = resolve; }));
|
||||
|
||||
const pending = review.load('RUN-2', 'CASE-2');
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
expect(review.reviewQueue.value).toBe(previousQueue);
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1');
|
||||
|
||||
await vi.waitFor(() => expect(resolveRun).toBeTypeOf('function'));
|
||||
await vi.waitFor(() => expect(resolveQueue).toBeTypeOf('function'));
|
||||
await vi.waitFor(() => expect(resolveCase).toBeTypeOf('function'));
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1');
|
||||
|
||||
resolveCase?.(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2', document: { id: 2, file_name: 'second.pdf' } }));
|
||||
await vi.waitFor(() => expect(resolveEvidence).toBeTypeOf('function'));
|
||||
resolveEvidence?.({ items: [] });
|
||||
await vi.waitFor(() => expect(review.activeCase.value?.case_no).toBe('CASE-2'));
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
expect(review.reviewQueue.value).toBe(previousQueue);
|
||||
|
||||
resolveRun?.({ run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }] });
|
||||
resolveQueue?.({ summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, items: [{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }] });
|
||||
await pending;
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
|
||||
expect(review.reviewQueue.value?.items[0]?.case_no).toBe('CASE-2');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-2');
|
||||
});
|
||||
|
||||
it('starts the preferred Case and Evidence reads without waiting for a slow cross-Run summary', async () => {
|
||||
// 关键断言:导航已提供目标 Case 时,Run/Queue 摘要不能把详情读取串行化。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
|
||||
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
|
||||
let resolveQueue: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getCase.mockClear();
|
||||
api.getEvidence.mockClear();
|
||||
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveRun = resolve; }));
|
||||
api.getQueue.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveQueue = resolve; }));
|
||||
|
||||
const pending = review.load('RUN-2', 'CASE-2');
|
||||
await vi.waitFor(() => expect(api.getCase).toHaveBeenCalledWith('CASE-2'));
|
||||
await vi.waitFor(() => expect(api.getEvidence).toHaveBeenCalledWith('CASE-2'));
|
||||
|
||||
await vi.waitFor(() => expect(review.runLoading.value).toBe(true));
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1');
|
||||
resolveRun?.({ run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }] });
|
||||
resolveQueue?.({ summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, items: [{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }] });
|
||||
await pending;
|
||||
});
|
||||
|
||||
it('keeps the stable workbench on a cross-Run load failure', async () => {
|
||||
// 关键断言:目标 Run 读取失败时,用户可继续查看上一份稳定工作面,不能退回整页空白。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
api.getCase.mockResolvedValueOnce(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2' }));
|
||||
api.getEvidence.mockResolvedValueOnce({ items: [] });
|
||||
api.getRun.mockImplementationOnce(() => Promise.reject(new Error('target unavailable')));
|
||||
api.getQueue.mockImplementationOnce(() => Promise.reject(new Error('target unavailable')));
|
||||
|
||||
await review.load('RUN-2', 'CASE-2');
|
||||
|
||||
expect(review.loadFailed.value).toBe(false);
|
||||
expect(review.runSwitchFailed.value).toBe(true);
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
expect(review.reviewQueue.value?.items[0]?.case_no).toBe('CASE-1');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1');
|
||||
});
|
||||
|
||||
it('blocks confirm when build eligibility cannot build', async () => {
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
@@ -756,6 +932,57 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('refreshes the active Case and queue while post-confirm automation is still active', async () => {
|
||||
vi.useFakeTimers();
|
||||
const readyCase = buildCase({
|
||||
status: 'ready',
|
||||
draft: {
|
||||
...buildCase().draft!,
|
||||
build_eligibility: { can_build: true, status: 'ready', line_projections: [] },
|
||||
},
|
||||
});
|
||||
const runningCase = {
|
||||
...readyCase,
|
||||
status: 'confirmed',
|
||||
confirmed_task_no: 'OT-1',
|
||||
automation: { status: 'running', phase: 'post_ot_progress' },
|
||||
};
|
||||
api.getCase
|
||||
.mockResolvedValueOnce(readyCase)
|
||||
.mockResolvedValue(runningCase);
|
||||
api.getRun.mockResolvedValue({
|
||||
run_no: 'RUN-1', summary: {},
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, status: 'confirmed', lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [] }],
|
||||
});
|
||||
api.getQueue.mockResolvedValue({
|
||||
summary: { total: 1, needs_action: 0, processing: 1, completed: 0 },
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, source_run_no: 'RUN-1', status: 'confirmed', lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [] }],
|
||||
});
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
api.getProcessingWorkItem.mockResolvedValue({
|
||||
work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation',
|
||||
currentGate: { gateCode: 'inventory_preparation', status: 'running' },
|
||||
});
|
||||
api.confirmCase.mockResolvedValue({
|
||||
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
|
||||
case: runningCase, auto_progress_started: true,
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
|
||||
await review.confirm();
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
|
||||
// 关键断言:活动窗口内同步刷新 Case 与队列,让顶部五阶段读取到后端已推进的通知准备。
|
||||
expect(api.getCase.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
expect(api.getQueue.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
expect(review.activeCase.value?.confirmed_task_no).toBe('OT-1');
|
||||
expect(review.reviewQueue.value?.items[0]?.lifecycle_stage).toBe('fulfillment_prep');
|
||||
|
||||
review.stopWorkflowProgressPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('keeps polling after a recoverable RPA failure so a later callback can refresh the workflow', async () => {
|
||||
vi.useFakeTimers();
|
||||
const onWorkflowRefresh = vi.fn();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* 用途:订单复核工作台 composable,编排 Run/Case/PDF、草稿写入与建单确认。
|
||||
* 依赖:shipping API review/extraction-run、useShippingProcessingWorkItem、Vue ref/computed、BusinessError。
|
||||
* 逻辑:按 runNo 加载 Review Run/Case;合成 ShippingReviewProgressContext;
|
||||
* OT 绑定 Case.order_task_no / Candidate;切换 Case 时清空 activeCase(纯 skeleton,禁止旧值 DOM);
|
||||
* OT 绑定 Case.order_task_no / Candidate;切换时保留稳定显示壳,目标快照到齐后原子替换;
|
||||
* 409 REVIEW_DRAFT_VERSION_MISMATCH 冲突处理;build_eligibility 驱动 confirm/reroute;
|
||||
* 重识别后刷新正式 Run/Case/Gate 投影;PDF Blob 由 ensurePreviewLoaded 按需加载。
|
||||
*/
|
||||
@@ -47,6 +47,7 @@ import type {
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionLifecycleProgress,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingOrderReviewQueue,
|
||||
ShippingOrderReviewEmailEvidencePreview,
|
||||
@@ -60,7 +61,6 @@ import { useShippingProcessingWorkItem } from '../shipping/useShippingProcessing
|
||||
export type ReviewStatusMessage =
|
||||
| 'superseded'
|
||||
| 'work_item_closed'
|
||||
| 'reparse_in_progress'
|
||||
| 'restored'
|
||||
| 'draft_version_conflict'
|
||||
| null;
|
||||
@@ -304,6 +304,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const caseProjectionVersion = ref<number | null>(null);
|
||||
const caseLoadingContext = ref<ShippingOrderReviewCaseLoadingContext | null>(null);
|
||||
const reviewProgressContext = ref<ShippingReviewProgressContext | null>(null);
|
||||
/** 当前 Run 的用户态五阶段进度;页面 loading 或尚无 Case 时仍可展示。 */
|
||||
const extractionLifecycleProgress = ref<ShippingOrderExtractionLifecycleProgress | null>(null);
|
||||
/** ?? OT ???????????????? */
|
||||
const authoritativeOrderTaskNo = computed(() => {
|
||||
const item = reviewProgressContext.value;
|
||||
@@ -324,11 +326,19 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
enabled: computed(() => Boolean(authoritativeOrderTaskNo.value)),
|
||||
// 订单处理工作台:旧 progress_version 不得覆盖较新本地投影。
|
||||
monotonicProgressVersion: true,
|
||||
// 复核页仅由下方 2.5 秒协调轮询驱动,避免此处额外开启 3 秒定时读取。
|
||||
continuousPolling: false,
|
||||
},
|
||||
);
|
||||
const versions = ref<ShippingReviewProgressVersion[]>([]);
|
||||
const statusMessage = ref<ReviewStatusMessage>(null);
|
||||
const loading = ref(false);
|
||||
/** 首次进入工作台的页面级加载态;后续 Run 切换不得重新触发整页 loading。 */
|
||||
const initialLoading = ref(false);
|
||||
/** Run 数据读取态;供跨 Run 切换保持既有工作台壳时使用。 */
|
||||
const runLoading = ref(false);
|
||||
/** 跨 Run 读取失败;有稳定工作台时只显示局部错误,不触发页面失败态。 */
|
||||
const runSwitchFailed = ref(false);
|
||||
let initialLoadCompleted = false;
|
||||
const loadFailed = ref(false);
|
||||
const saving = ref(false);
|
||||
const saveFailed = ref(false);
|
||||
@@ -369,6 +379,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
let previewInflight: { caseNo: string; promise: Promise<boolean> } | null = null;
|
||||
/** Case 切换请求代次:快速切换时丢弃过期响应,禁止旧 Case 覆盖新 Case。 */
|
||||
let caseLoadGeneration = 0;
|
||||
/** 当前 Case 快照与证据的联合读取;新选择立即取消旧读取,减少无效后端投影。 */
|
||||
let caseSwitchAbortController: AbortController | null = null;
|
||||
/** 当前正在请求或已选定的 Case 编号(与 generation 双校验)。 */
|
||||
const requestedCaseNo = ref<string | null>(null);
|
||||
/** 同 Run 内切换 PDF/Case 的轻量加载态(不触发整页 loading)。 */
|
||||
@@ -425,6 +437,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const tick = async () => {
|
||||
try {
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
const normalizedStatus = String(run.status || '').trim();
|
||||
const synthesized = synthesizeWorkItemFromReviewContext({
|
||||
reviewRun: reviewRun.value,
|
||||
@@ -467,6 +480,26 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 自动推进期间同步当前 Case 与生命周期队列。
|
||||
*
|
||||
* 核心逻辑:仅复用既有只读 API,且只在当前 Case 未切换时写回;不读证据/PDF,
|
||||
* 不触发任何 RPA 或 Gate 写操作。正式 OT 的细粒度状态仍由 processing projection 负责。
|
||||
*/
|
||||
const refreshActiveAutomationLifecycle = async () => {
|
||||
const caseNo = String(activeCase.value?.case_no || '').trim();
|
||||
const runNo = String(reviewRun.value?.run_no || activeCase.value?.run_no || '').trim();
|
||||
if (!caseNo || !runNo) return;
|
||||
const [caseSnapshot, queue] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(caseNo),
|
||||
getWorkspaceShippingOrderReviewQueue(runNo),
|
||||
]);
|
||||
// Case 切换或重新加载后,旧轮询响应不得覆盖当前工作台。
|
||||
if (String(activeCase.value?.case_no || '').trim() !== caseNo) return;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
reviewQueue.value = queue;
|
||||
};
|
||||
|
||||
/**
|
||||
* ?????????????????
|
||||
* ???????? OT ?????? ShippingProcessing????? Extraction Run
|
||||
@@ -484,6 +517,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
// RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。
|
||||
const UNIFIED_TERMINAL = new Set(['completed', 'cancelled']);
|
||||
let lastUnifiedStatus = '';
|
||||
let lastLifecycleFingerprint = '';
|
||||
const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']);
|
||||
const tick = async () => {
|
||||
try {
|
||||
@@ -500,11 +534,25 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
|
||||
stopWorkflowProgressPolling();
|
||||
return;
|
||||
}
|
||||
// 顶部五阶段取 Case/Queue 的 lifecycle_entries。仅当 OT 投影的阶段/门禁发生变化
|
||||
// 时刷新一次,避免每 2.5 秒重复读取队列;不等待该读取,保证终态轮询及时停止。
|
||||
const lifecycleFingerprint = [
|
||||
unifiedStatus,
|
||||
String(shippingProcessingProjection.value?.stage || ''),
|
||||
String(shippingProcessingProjection.value?.currentGate?.gateCode || ''),
|
||||
String(shippingProcessingProjection.value?.currentGate?.status || ''),
|
||||
].join('|');
|
||||
if (lifecycleFingerprint !== lastLifecycleFingerprint) {
|
||||
lastLifecycleFingerprint = lifecycleFingerprint;
|
||||
void refreshActiveAutomationLifecycle();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (targetRunNo) {
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
const synthesized = synthesizeWorkItemFromReviewContext({
|
||||
reviewRun: reviewRun.value,
|
||||
activeCase: activeCase.value,
|
||||
@@ -529,6 +577,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
// ???? setup ?????????? composable ?????? Vue warn?
|
||||
if (getCurrentInstance()) {
|
||||
onBeforeUnmount(() => {
|
||||
caseSwitchAbortController?.abort();
|
||||
stopWorkflowProgressPolling();
|
||||
stopReparseCaseRefreshPolling();
|
||||
stopShippingProcessing();
|
||||
@@ -591,14 +640,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
// ?????? Case ?????? superseded????????????
|
||||
// ?????????????????????????????
|
||||
if (
|
||||
activeCase.value?.status === 'reparse_pending'
|
||||
|| reviewProgressContext.value?.lifecycle_status === 'extracting'
|
||||
|| reviewProgressContext.value?.lifecycle_status === 'layout_parsing'
|
||||
) {
|
||||
statusMessage.value = 'reparse_in_progress';
|
||||
return;
|
||||
}
|
||||
if (isViewingHistoricalVersion.value || activeCase.value?.status === 'superseded') {
|
||||
statusMessage.value = 'superseded';
|
||||
return;
|
||||
@@ -654,21 +695,34 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
/**
|
||||
* ???? WorkItem ???????????????????
|
||||
*/
|
||||
const refreshWorkItemContext = async (conversationId?: string, itemNo?: string) => {
|
||||
const refreshWorkItemContext = async (
|
||||
conversationId?: string,
|
||||
itemNo?: string,
|
||||
options?: { expectedLoadGeneration?: number },
|
||||
) => {
|
||||
const isExpectedLoad = () => (
|
||||
options?.expectedLoadGeneration == null
|
||||
|| options.expectedLoadGeneration === caseLoadGeneration
|
||||
);
|
||||
const conversation = String(conversationId || contextConversationId || '').trim();
|
||||
if (conversation) contextConversationId = conversation;
|
||||
if (itemNo) contextItemNo = itemNo;
|
||||
if (!isExpectedLoad()) return;
|
||||
versionsLoading.value = true;
|
||||
try {
|
||||
reviewProgressContext.value = await resolveWorkItem(conversation, {
|
||||
const context = await resolveWorkItem(conversation, {
|
||||
itemNo: contextItemNo || undefined,
|
||||
caseNo: activeCase.value?.case_no,
|
||||
});
|
||||
if (!isExpectedLoad()) return;
|
||||
reviewProgressContext.value = context;
|
||||
versions.value = [];
|
||||
} catch {
|
||||
if (!isExpectedLoad()) return;
|
||||
reviewProgressContext.value = null;
|
||||
versions.value = [];
|
||||
} finally {
|
||||
if (!isExpectedLoad()) return;
|
||||
versionsLoading.value = false;
|
||||
refreshStatusMessage();
|
||||
}
|
||||
@@ -848,53 +902,139 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
preferredCaseNo?: string,
|
||||
options?: { conversationId?: string; itemNo?: string; restoreProgress?: boolean },
|
||||
) => {
|
||||
++caseLoadGeneration;
|
||||
caseSwitchAbortController?.abort();
|
||||
caseSwitchAbortController = null;
|
||||
const generation = ++caseLoadGeneration;
|
||||
++intakeParseRequestGeneration;
|
||||
loading.value = true;
|
||||
requestedCaseNo.value = String(preferredCaseNo || '').trim() || null;
|
||||
const isInitialLoad = !initialLoadCompleted && !reviewRun.value;
|
||||
if (isInitialLoad) initialLoading.value = true;
|
||||
runLoading.value = true;
|
||||
runSwitchFailed.value = false;
|
||||
loadFailed.value = false;
|
||||
draftConflict.value = null;
|
||||
saveFailed.value = false;
|
||||
// [STEP 1] ?????????????????????? WorkflowItem ????? Run ???
|
||||
contextConversationId = String(options?.conversationId || '').trim();
|
||||
contextItemNo = String(options?.itemNo || '').trim();
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
caseProjectionVersion.value = null;
|
||||
caseLoadingContext.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
versions.value = [];
|
||||
evidence.value = [];
|
||||
llmSuggestions.value = [];
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
clearPreview();
|
||||
try {
|
||||
const [run, queue] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewRun(runNo),
|
||||
getWorkspaceShippingOrderReviewQueue(runNo),
|
||||
]);
|
||||
reviewRun.value = run;
|
||||
reviewQueue.value = queue;
|
||||
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
|
||||
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
|
||||
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
|
||||
// [STEP] ??????? PDF??????????????????????
|
||||
clearPreview();
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo);
|
||||
// refreshWorkItemContext ????? ref???????? ref????? load ???????????
|
||||
} catch {
|
||||
loadFailed.value = true;
|
||||
const hasStableWorkbench = Boolean(reviewRun.value && activeCase.value);
|
||||
const stableSnapshot = hasStableWorkbench
|
||||
? {
|
||||
reviewRun: reviewRun.value,
|
||||
reviewQueue: reviewQueue.value,
|
||||
activeCase: activeCase.value,
|
||||
caseProjectionVersion: caseProjectionVersion.value,
|
||||
caseLoadingContext: caseLoadingContext.value,
|
||||
evidence: evidence.value,
|
||||
llmSuggestions: llmSuggestions.value,
|
||||
extractionLifecycleProgress: extractionLifecycleProgress.value,
|
||||
}
|
||||
: null;
|
||||
if (!hasStableWorkbench) {
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
caseProjectionVersion.value = null;
|
||||
caseLoadingContext.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
reviewQueue.value = null;
|
||||
extractionLifecycleProgress.value = null;
|
||||
versions.value = [];
|
||||
statusMessage.value = null;
|
||||
evidence.value = [];
|
||||
llmSuggestions.value = [];
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
clearPreview();
|
||||
}
|
||||
try {
|
||||
const runRequest = getWorkspaceShippingOrderReviewRun(runNo);
|
||||
const queueRequest = getWorkspaceShippingOrderReviewQueue(runNo);
|
||||
// 路由已明确目标 Case 时,详情读取不应等待较慢的 Run/Queue 摘要;
|
||||
// 四份数据仍在全部成功后原子提交,避免混合工作面。
|
||||
const preferredCaseRequest = preferredCaseNo
|
||||
? Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(preferredCaseNo),
|
||||
getWorkspaceShippingOrderReviewEvidence(preferredCaseNo),
|
||||
])
|
||||
: null;
|
||||
// 已有稳定工作台且路由明确目标 PDF 时,目标详情是用户切换的关键路径;
|
||||
// Run/Queue 只负责后续更新导航和阶段摘要,不能用其慢投影阻塞当前文件显示。
|
||||
if (hasStableWorkbench && preferredCaseRequest) {
|
||||
const [caseSnapshot, caseEvidence] = await preferredCaseRequest;
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
evidence.value = caseEvidence?.items || [];
|
||||
clearPreview();
|
||||
|
||||
const [run, queue] = await Promise.all([runRequest, queueRequest]);
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
reviewRun.value = run;
|
||||
reviewQueue.value = queue;
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo, {
|
||||
expectedLoadGeneration: generation,
|
||||
});
|
||||
initialLoadCompleted = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const [run, queue, preferredSnapshot] = await Promise.all([
|
||||
runRequest,
|
||||
queueRequest,
|
||||
preferredCaseRequest,
|
||||
]);
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
|
||||
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
|
||||
const [caseSnapshot, caseEvidence] = preferredSnapshot
|
||||
? preferredSnapshot
|
||||
: caseNo
|
||||
? await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(caseNo),
|
||||
getWorkspaceShippingOrderReviewEvidence(caseNo),
|
||||
])
|
||||
: [null, null];
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
reviewRun.value = run;
|
||||
reviewQueue.value = queue;
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
evidence.value = caseEvidence?.items || [];
|
||||
// [STEP] ??????? PDF??????????????????????
|
||||
clearPreview();
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo, {
|
||||
expectedLoadGeneration: generation,
|
||||
});
|
||||
initialLoadCompleted = true;
|
||||
// refreshWorkItemContext ????? ref???????? ref????? load ???????????
|
||||
} catch {
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
loadFailed.value = !hasStableWorkbench;
|
||||
runSwitchFailed.value = hasStableWorkbench;
|
||||
// 目标 Case 已先行显示时,若其所属 Run/Queue 校准失败,必须整体回退到同一份
|
||||
// 稳定快照,不能留下“新文件 + 旧导航”的混合业务工作面。
|
||||
if (stableSnapshot) {
|
||||
reviewRun.value = stableSnapshot.reviewRun;
|
||||
reviewQueue.value = stableSnapshot.reviewQueue;
|
||||
activeCase.value = stableSnapshot.activeCase;
|
||||
caseProjectionVersion.value = stableSnapshot.caseProjectionVersion;
|
||||
caseLoadingContext.value = stableSnapshot.caseLoadingContext;
|
||||
evidence.value = stableSnapshot.evidence;
|
||||
llmSuggestions.value = stableSnapshot.llmSuggestions;
|
||||
extractionLifecycleProgress.value = stableSnapshot.extractionLifecycleProgress;
|
||||
}
|
||||
if (!hasStableWorkbench) {
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
extractionLifecycleProgress.value = null;
|
||||
reviewQueue.value = null;
|
||||
versions.value = [];
|
||||
statusMessage.value = null;
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
if (isInitialLoad) initialLoading.value = false;
|
||||
runLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -932,6 +1072,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const selectCase = async (caseNo: string) => {
|
||||
const target = String(caseNo || '').trim();
|
||||
if (!target) return;
|
||||
caseSwitchAbortController?.abort();
|
||||
const controller = new AbortController();
|
||||
caseSwitchAbortController = controller;
|
||||
const generation = ++caseLoadGeneration;
|
||||
++intakeParseRequestGeneration;
|
||||
requestedCaseNo.value = target;
|
||||
@@ -944,8 +1087,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
intakeParseLoadFailed.value = false;
|
||||
try {
|
||||
const [detail, result] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(target),
|
||||
getWorkspaceShippingOrderReviewEvidence(target),
|
||||
getWorkspaceShippingOrderReviewCase(target, controller.signal),
|
||||
getWorkspaceShippingOrderReviewEvidence(target, controller.signal),
|
||||
]);
|
||||
// [STEP 2] 代次与目标 Case 双校验;过期响应一律丢弃。
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
@@ -970,6 +1113,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
// [STEP 3] 失败保留上一份稳定快照,用户仍可继续查看/编辑,不回退成空白工作台。
|
||||
caseSwitchFailed.value = true;
|
||||
} finally {
|
||||
if (caseSwitchAbortController === controller) caseSwitchAbortController = null;
|
||||
if (generation === caseLoadGeneration) {
|
||||
caseSwitchLoading.value = false;
|
||||
}
|
||||
@@ -1195,9 +1339,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
if (!activeCase.value) return;
|
||||
validationInProgress.value = true;
|
||||
try {
|
||||
await save(async () => (
|
||||
await validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version())
|
||||
).case);
|
||||
const response = await validateWorkspaceShippingOrderReviewDraft(activeCase.value.case_no, version());
|
||||
await save(async () => response.case);
|
||||
return response.resume_outcome;
|
||||
} finally {
|
||||
validationInProgress.value = false;
|
||||
}
|
||||
@@ -1238,7 +1382,10 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
caseProjectionVersion.value = Date.now();
|
||||
caseLoadingContext.value = null;
|
||||
draftConflict.value = null;
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
if (reviewRun.value) {
|
||||
reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
extractionLifecycleProgress.value = reviewRun.value.lifecycle_progress || null;
|
||||
}
|
||||
await refreshWorkItemContext();
|
||||
// [UI-02] ?????? OT???? Notice task_no / ??? workflow_item_id ??????
|
||||
const orderTaskNo = String(
|
||||
@@ -1300,7 +1447,10 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
try {
|
||||
const response = await reparseWorkspaceShippingOrderReviewDocument(activeCase.value.case_no, reason, comment);
|
||||
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
if (reviewRun.value) {
|
||||
reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
extractionLifecycleProgress.value = reviewRun.value.lifecycle_progress || null;
|
||||
}
|
||||
await refreshWorkItemContext();
|
||||
startReparseCaseRefreshPolling(response.run.run_no);
|
||||
return response;
|
||||
@@ -1427,6 +1577,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
caseProjectionVersion,
|
||||
caseLoadingContext,
|
||||
reviewProgressContext,
|
||||
extractionLifecycleProgress,
|
||||
shippingProcessingProjection,
|
||||
authoritativeOrderTaskNo,
|
||||
shippingProcessingLoading,
|
||||
@@ -1466,7 +1617,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
clearPreview,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
loading,
|
||||
initialLoading,
|
||||
runLoading,
|
||||
runSwitchFailed,
|
||||
loadFailed,
|
||||
caseSwitchLoading,
|
||||
caseSwitchFailed,
|
||||
|
||||
@@ -49,7 +49,7 @@ export function getPrimaryDocumentName(
|
||||
|
||||
/**
|
||||
* 汇总正式 OT 任务文件数(不含 order_intake)。
|
||||
* 核心逻辑:优先 summary.total_files;缺失时对 needs_action+processing+completed 的 file_count 求和。
|
||||
* 核心逻辑:优先 summary.total_files;缺失时仅对 status_groups 的活动状态求和。
|
||||
* @param projection - 会话 processing 投影
|
||||
*/
|
||||
export function resolveFormalTaskFileCount(
|
||||
@@ -60,10 +60,12 @@ export function resolveFormalTaskFileCount(
|
||||
if (Number.isFinite(fromSummary) && fromSummary >= 0 && projection.summary?.total_files != null) {
|
||||
return fromSummary;
|
||||
}
|
||||
const groups = projection.status_groups;
|
||||
const tasks = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(groups?.failed || []),
|
||||
...(groups?.waiting_human || []),
|
||||
...(groups?.processing || []),
|
||||
...(groups?.completed || []),
|
||||
];
|
||||
return tasks.reduce((sum, task) => {
|
||||
const count = Number(task.file_count);
|
||||
@@ -83,10 +85,13 @@ export function resolveFormalTaskCount(
|
||||
if (Number.isFinite(fromSummary) && fromSummary >= 0 && projection.summary?.total_tasks != null) {
|
||||
return fromSummary;
|
||||
}
|
||||
const groups = projection.status_groups;
|
||||
return (
|
||||
(projection.needs_action?.length || 0)
|
||||
+ (projection.processing?.length || 0)
|
||||
+ (projection.completed?.length || 0)
|
||||
+ (projection.history?.length || 0)
|
||||
(groups?.failed.length || 0)
|
||||
+ (groups?.waiting_human.length || 0)
|
||||
+ (groups?.processing.length || 0)
|
||||
+ (groups?.completed.length || 0)
|
||||
+ (groups?.cancelled.length || 0)
|
||||
+ (groups?.archived.length || 0)
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@
|
||||
* ShippingProcessingProjection、合成 ShippingWorkflowItem)。
|
||||
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
|
||||
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
|
||||
* 可由统一 work_items(order_task)合成兼容分组。
|
||||
* 会话卡直接消费后端 status_groups,不从 work_items 二次聚合。
|
||||
* 语义签名与任务稳定化:轮询返回相同业务状态时复用旧对象,避免按钮闪烁。
|
||||
*/
|
||||
|
||||
@@ -16,7 +16,6 @@ import type {
|
||||
ConversationProcessingTaskGroup,
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingFacts,
|
||||
ShippingProcessingLifecycleEntry,
|
||||
ShippingProcessingPrimaryAction,
|
||||
ShippingProcessingProjection,
|
||||
@@ -96,14 +95,21 @@ export function buildTaskSemanticKey(
|
||||
intakeNo: child.intakeNo,
|
||||
status: child.userStatus ?? child.status,
|
||||
stage: child.userStage ?? child.stage,
|
||||
runNo: child.runNo ?? null,
|
||||
caseNo: child.caseNo ?? null,
|
||||
uploadState: child.facts?.uploadState ?? null,
|
||||
filename: child.sourceSummary?.filename ?? null,
|
||||
reason: child.blockingReason?.code ?? child.sourceSummary?.failureReasonCode ?? null,
|
||||
// EML 父卡会缓存其叶子对象。子文件的入口与按钮同样是后端裁决,
|
||||
// 必须进入父卡语义签名;否则父卡引用被复用时会残留已撤销的入口。
|
||||
primaryAction: child.uiState
|
||||
? (child.uiState.primary_action?.code ?? null)
|
||||
: (child.primaryAction?.code ?? null),
|
||||
primaryAction: child.uiState?.primary_action
|
||||
? {
|
||||
code: child.uiState.primary_action.code,
|
||||
executionMode: child.uiState.primary_action.executionMode ?? null,
|
||||
targetSurface: child.uiState.primary_action.targetSurface ?? null,
|
||||
targetLifecycleStage: child.uiState.primary_action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null,
|
||||
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -121,11 +127,7 @@ export function buildTaskSemanticKey(
|
||||
title: task.title,
|
||||
// [AUTHORITY] 新会话批次的可操作动作由 ui_state 单独版本化;把它纳入语义键,
|
||||
// 避免状态未变但后端撤销/切换按钮时前端错误复用旧任务对象。
|
||||
primaryAction: task.uiState
|
||||
? (task.uiState.primary_action?.code ?? null)
|
||||
: ((task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? null),
|
||||
primaryAction: task.uiState?.primary_action?.code ?? null,
|
||||
// 生命周期入口由后端独立裁决;入口被撤销/禁用时必须替换缓存对象,不能保留旧按钮。
|
||||
lifecycleEntries: task.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
@@ -147,16 +149,11 @@ export function buildTaskSemanticKey(
|
||||
?? null,
|
||||
nextActionCode: (task as ConversationProcessingUserTask & {
|
||||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||||
})
|
||||
.current_gate?.nextActionCode
|
||||
?? (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? null,
|
||||
}).current_gate?.nextActionCode ?? null,
|
||||
}
|
||||
: null,
|
||||
availableActions: normalizeActionCodes(
|
||||
task.uiState
|
||||
? task.uiState.secondary_actions.filter((action) => action.enabled).map((action) => action.code)
|
||||
: (task.available_actions || []),
|
||||
task.uiState?.secondary_actions.filter((action) => action.enabled).map((action) => action.code) || [],
|
||||
),
|
||||
canAppend: task.can_append ?? null,
|
||||
aggregateChildren,
|
||||
@@ -173,6 +170,7 @@ export function buildProcessingSemanticKey(
|
||||
projection: ConversationProcessingProjection | null | undefined,
|
||||
): string {
|
||||
if (!projection) return '';
|
||||
const groups = projection.status_groups;
|
||||
return JSON.stringify({
|
||||
summary: {
|
||||
total_tasks: projection.summary?.total_tasks || 0,
|
||||
@@ -184,10 +182,14 @@ export function buildProcessingSemanticKey(
|
||||
},
|
||||
focused_task_no: projection.focused_task_no || null,
|
||||
recent_task_no: projection.recent_task_no || null,
|
||||
needs_action: (projection.needs_action || []).map(buildTaskSemanticKey),
|
||||
processing: (projection.processing || []).map(buildTaskSemanticKey),
|
||||
completed: (projection.completed || []).map(buildTaskSemanticKey),
|
||||
history: (projection.history || []).map(buildTaskSemanticKey),
|
||||
status_groups: {
|
||||
failed: (groups?.failed || []).map(buildTaskSemanticKey),
|
||||
waiting_human: (groups?.waiting_human || []).map(buildTaskSemanticKey),
|
||||
processing: (groups?.processing || []).map(buildTaskSemanticKey),
|
||||
completed: (groups?.completed || []).map(buildTaskSemanticKey),
|
||||
cancelled: (groups?.cancelled || []).map(buildTaskSemanticKey),
|
||||
archived: (groups?.archived || []).map(buildTaskSemanticKey),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -859,74 +861,6 @@ export function groupConversationProcessingTasks(
|
||||
* 核心逻辑:同 user_task_no / run_no 时,若兜底 file_count 更大,采用兜底的
|
||||
* display_kind / title / document_names / objects(文档子对象)。
|
||||
*/
|
||||
/**
|
||||
* 将统一 ShippingProcessing status/gate 映射为会话任务分组。
|
||||
* 核心逻辑:waiting_review/blocked/failed → needs_action;completed → completed;
|
||||
* cancelled → history;其余 → processing。
|
||||
*/
|
||||
export function mapShippingProcessingStatusToTaskGroup(
|
||||
item: ShippingProcessingProjection,
|
||||
): ConversationProcessingTaskGroup {
|
||||
const userGroup = String(item.userGroup || '').trim().toLowerCase();
|
||||
const status = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim());
|
||||
const childStatuses = (item.aggregateChildren || []).map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
|
||||
const childHasFailure = childStatuses.some((value) => value === 'failed');
|
||||
const childNeedsHuman = childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready');
|
||||
const childAllUploaded = childStatuses.length > 0
|
||||
&& childStatuses.every((value, index) => value === 'completed' && item.aggregateChildren?.[index]?.facts?.uploadState === 'succeeded');
|
||||
if (childHasFailure) return 'needs_action';
|
||||
if (childNeedsHuman) return 'needs_action';
|
||||
if (childAllUploaded) return 'completed';
|
||||
// 子项真实状态优先于父级 userGroup,避免 review_required/failed 被旧 processing 覆盖。
|
||||
if (status === 'failed' || status === 'waiting_review' || status === 'manual_upload_pending') return 'needs_action';
|
||||
if (userGroup === 'failed' || userGroup === 'waiting_human') return 'needs_action';
|
||||
if (userGroup === 'completed') return 'completed';
|
||||
if (userGroup === 'cancelled' || userGroup === 'archived') return 'history';
|
||||
if (userGroup === 'processing') return 'processing';
|
||||
const gateAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase();
|
||||
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
|
||||
.map((value) => String(value || '').trim().toLowerCase())
|
||||
.some((value) => HUMAN_ACTION_CODES.has(value) || value.startsWith('retry_failed_'));
|
||||
if (
|
||||
status === 'waiting_review'
|
||||
|| status === 'blocked'
|
||||
|| status === 'failed'
|
||||
|| status === 'waiting_human'
|
||||
|| status === 'retryable'
|
||||
|| hasHumanAction
|
||||
) {
|
||||
return 'needs_action';
|
||||
}
|
||||
if (status === 'completed') return 'completed';
|
||||
if (status === 'cancelled') return 'history';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 embedded conversation_processing 的焦点元数据合并到 work_items 派生投影。
|
||||
* 核心逻辑:任务列表必须来自 work_items;仅 focused_task_no / recent_task_no 可取自 embedded。
|
||||
*
|
||||
* @param derived - 由 projectConversationProcessingFromWorkItems 生成的投影
|
||||
* @param embedded - API 内嵌 conversation_processing(可选)
|
||||
* @returns 合并后的投影;derived 为空时回退 embedded
|
||||
*/
|
||||
export function mergeConversationProcessingFocusMetadata(
|
||||
derived: ConversationProcessingProjection | null,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
): ConversationProcessingProjection | null {
|
||||
if (!derived) {
|
||||
return embedded && typeof embedded === 'object'
|
||||
? normalizeConversationProcessingProjection(embedded)
|
||||
: null;
|
||||
}
|
||||
if (!embedded || typeof embedded !== 'object') return derived;
|
||||
return {
|
||||
...derived,
|
||||
focused_task_no: embedded.focused_task_no ?? derived.focused_task_no ?? null,
|
||||
recent_task_no: embedded.recent_task_no ?? derived.recent_task_no ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
|
||||
* 核心逻辑:新版 embedded.status_groups 是后端已完成“当前文件代表项 → EML 容器”
|
||||
@@ -940,46 +874,15 @@ export function mergeConversationProcessingFocusMetadata(
|
||||
* @returns 会话处理投影;无可用数据时 null
|
||||
*/
|
||||
export function resolveConversationProcessingFromUnified(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
_workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
|
||||
_previousProjection?: ConversationProcessingProjection | null,
|
||||
_stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
// [AUTHORITY] conversation_processing.status_groups 与 four_stage_nodes / ui_state
|
||||
// 同属后端一次裁决。即使顶层 work_items 非空,也不得前端二次聚合或用旧快照覆盖。
|
||||
if (embedded && typeof embedded === 'object' && embedded.status_groups) {
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
// [AUTHORITY] 新版接口已经由后端完成「状态 → EML → 业务文件」聚合。
|
||||
// 会话卡与批次中心必须直接使用该结果;前端从 work_items 重建只保留给旧响应兼容。
|
||||
// [TRANSITION] 只有统一投影里明确存在 order_task,才认为 OT 维度已经成形。
|
||||
// 仅 order_intake 存在时视为过渡阶段:
|
||||
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
|
||||
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
|
||||
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
|
||||
const hasOrderTask = items.some((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
|| (item.workItemType === 'order_intake' && item.sourceType === 'eml')
|
||||
));
|
||||
const convId = stabilizer?.conversationId;
|
||||
if (hasOrderTask) {
|
||||
stabilizer?.markSeen?.(convId);
|
||||
return mergeConversationProcessingFocusMetadata(
|
||||
projectConversationProcessingFromWorkItems(items, previousProjection),
|
||||
embedded,
|
||||
);
|
||||
}
|
||||
const sawOrderTaskRecently = stabilizer?.hasSeenOrderTaskBefore?.(convId) === true;
|
||||
if (sawOrderTaskRecently && previousProjection) {
|
||||
// 刚刚看到过 OT 但这轮响应暂缺 OT:不立即切回 embedded,保持上一轮投影。
|
||||
// 这样 2s 内轮询不会把右侧任务卡从 order_task 派生结果抖回旧 projection。
|
||||
return previousProjection;
|
||||
}
|
||||
if (embedded && typeof embedded === 'object') {
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
return null;
|
||||
// [AUTHORITY] 会话进度只能消费后端一次裁决的状态→EML→PDF树;从 work_items
|
||||
// 二次聚合会让前端重新承担业务状态裁决并重新引入旧四组的重复响应。
|
||||
if (!embedded || typeof embedded !== 'object' || !embedded.status_groups) return null;
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -993,15 +896,11 @@ export function resolveConversationProcessingFromUnified(
|
||||
export function normalizeConversationProcessingProjection(
|
||||
projection: ConversationProcessingProjection,
|
||||
): ConversationProcessingProjection {
|
||||
const backendAuthoritative = Boolean(projection.status_groups);
|
||||
const normalizeUiState = (
|
||||
rawState: ConversationProcessingUserTask['uiState'] | undefined,
|
||||
): ConversationProcessingUserTask['uiState'] | undefined => {
|
||||
if (!rawState || typeof rawState !== 'object') return undefined;
|
||||
const state = rawState as ConversationProcessingUserTask['uiState'] & {
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
secondaryActions?: Array<{ code: string; enabled: boolean }>;
|
||||
lifecycle_stage?: ConversationProcessingUserTask['uiState'] extends { lifecycleStage?: infer S } ? S : never;
|
||||
lifecycle_entries?: Array<Record<string, unknown>>;
|
||||
};
|
||||
@@ -1035,11 +934,11 @@ export function normalizeConversationProcessingProjection(
|
||||
: null)
|
||||
),
|
||||
targetLifecycleStage: (
|
||||
['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(
|
||||
['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
|
||||
String(rawAction.targetLifecycleStage),
|
||||
)
|
||||
? rawAction.targetLifecycleStage
|
||||
: (['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(
|
||||
: (['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
|
||||
String(rawAction.target_lifecycle_stage),
|
||||
)
|
||||
? rawAction.target_lifecycle_stage
|
||||
@@ -1057,11 +956,11 @@ export function normalizeConversationProcessingProjection(
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
blocking_reason: normalizeReason(state.blocking_reason ?? state.blockingReason),
|
||||
primary_action: normalizeAction(state.primary_action ?? state.primaryAction),
|
||||
blocking_reason: normalizeReason(state.blocking_reason),
|
||||
primary_action: normalizeAction(state.primary_action),
|
||||
// 次动作与主动作同属后端 ui_state 授权契约。若仅透传原始 snake_case,
|
||||
// 文件行点击会看不到导航目标并错误落入旧兼容分支。
|
||||
secondary_actions: (state.secondary_actions ?? state.secondaryActions ?? [])
|
||||
secondary_actions: (state.secondary_actions || [])
|
||||
.map((action) => {
|
||||
const normalized = normalizeAction(action);
|
||||
return normalized && 'code' in action && 'enabled' in action
|
||||
@@ -1069,23 +968,22 @@ export function normalizeConversationProcessingProjection(
|
||||
: null;
|
||||
})
|
||||
.filter((action): action is ShippingProcessingPrimaryAction & { code: string; enabled: boolean } => Boolean(action)),
|
||||
lifecycleStage: state.lifecycleStage ?? state.lifecycle_stage,
|
||||
lifecycleEntries: Array.isArray(state.lifecycleEntries)
|
||||
? state.lifecycleEntries.filter((entry) => Boolean(entry?.code && entry?.state && entry?.targetSurface))
|
||||
: (Array.isArray(state.lifecycle_entries)
|
||||
? state.lifecycle_entries.map((entry) => {
|
||||
const rawEntry = entry as { code?: unknown; state?: unknown; target_surface?: unknown; targetSurface?: unknown };
|
||||
return {
|
||||
code: String(rawEntry.code || '') as ShippingProcessingLifecycleEntry['code'],
|
||||
state: String(rawEntry.state || '') as ShippingProcessingLifecycleEntry['state'],
|
||||
targetSurface: String(rawEntry.targetSurface ?? rawEntry.target_surface ?? '') as ShippingProcessingLifecycleEntry['targetSurface'],
|
||||
};
|
||||
}).filter((entry) => Boolean(entry.code && entry.state && entry.targetSurface))
|
||||
: []),
|
||||
lifecycleStage: state.lifecycle_stage,
|
||||
lifecycleEntries: Array.isArray(state.lifecycle_entries)
|
||||
? state.lifecycle_entries.map((entry) => {
|
||||
const rawEntry = entry as { code?: unknown; state?: unknown; target_surface?: unknown };
|
||||
return {
|
||||
code: String(rawEntry.code || '') as ShippingProcessingLifecycleEntry['code'],
|
||||
state: String(rawEntry.state || '') as ShippingProcessingLifecycleEntry['state'],
|
||||
targetSurface: String(rawEntry.target_surface || '') as ShippingProcessingLifecycleEntry['targetSurface'],
|
||||
};
|
||||
}).filter((entry) => Boolean(entry.code && entry.state && entry.targetSurface))
|
||||
: [],
|
||||
};
|
||||
};
|
||||
const normalizeTask = (task: ConversationProcessingUserTask): ConversationProcessingUserTask => {
|
||||
const raw = task as ConversationProcessingUserTask & {
|
||||
user_task_no?: string | null;
|
||||
user_status?: ConversationProcessingUserTask['userStatus'];
|
||||
user_stage?: ConversationProcessingUserTask['userStage'];
|
||||
user_group?: ConversationProcessingUserTask['userGroup'];
|
||||
@@ -1094,406 +992,52 @@ export function normalizeConversationProcessingProjection(
|
||||
aggregate_summary?: ConversationProcessingUserTask['aggregateSummary'];
|
||||
aggregate_children?: unknown[];
|
||||
};
|
||||
const rawPrimaryAction = raw.primaryAction ?? raw.primary_action ?? null;
|
||||
const aggregateChildren = Array.isArray(raw.aggregateChildren)
|
||||
? raw.aggregateChildren
|
||||
: (Array.isArray(raw.aggregate_children)
|
||||
? raw.aggregate_children
|
||||
.map(normalizeShippingProcessingProjection)
|
||||
.filter((item): item is ShippingProcessingProjection => Boolean(item))
|
||||
: []);
|
||||
// 新批次投影的 group/user_group 已由后端裁决;旧 embedded 响应没有 status_groups,
|
||||
// 仅在该兼容分支维持历史规范化,避免旧服务端响应把待人工留在处理中。
|
||||
const rawStatus = task.userStatus ?? task.status_label;
|
||||
const normalizedStatus = normalizeLifecycleStatus(rawStatus);
|
||||
const legacyActions = Array.isArray(task.available_actions) ? task.available_actions : [];
|
||||
const legacyHasHumanAction = legacyActions.some((value) => {
|
||||
const code = String(value || '').trim().toLowerCase();
|
||||
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
|
||||
});
|
||||
const finalGroup: ConversationProcessingTaskGroup = backendAuthoritative
|
||||
? task.group
|
||||
: classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
|
||||
needsCustomerConfirm: legacyHasHumanAction,
|
||||
});
|
||||
const aggregateChildren = Array.isArray(raw.aggregate_children)
|
||||
? raw.aggregate_children
|
||||
.map(normalizeShippingProcessingProjection)
|
||||
.filter((item): item is ShippingProcessingProjection => Boolean(item))
|
||||
: [];
|
||||
return {
|
||||
...task,
|
||||
status_label: backendAuthoritative
|
||||
? task.status_label
|
||||
: (normalizedStatus || task.status_label),
|
||||
userStatus: raw.userStatus ?? raw.user_status ?? null,
|
||||
userStage: raw.userStage ?? raw.user_stage ?? null,
|
||||
userGroup: raw.userGroup ?? raw.user_group ?? null,
|
||||
blockingReason: raw.blockingReason ?? raw.blocking_reason ?? null,
|
||||
primaryAction: typeof rawPrimaryAction === 'object' ? rawPrimaryAction : null,
|
||||
primary_action: typeof rawPrimaryAction === 'string' ? rawPrimaryAction : task.primary_action,
|
||||
aggregateSummary: raw.aggregateSummary ?? raw.aggregate_summary ?? null,
|
||||
status_label: task.status_label,
|
||||
userStatus: raw.user_status ?? null,
|
||||
userStage: raw.user_stage ?? null,
|
||||
userGroup: raw.user_group ?? null,
|
||||
blockingReason: raw.blocking_reason ?? null,
|
||||
primaryAction: null,
|
||||
primary_action: task.primary_action,
|
||||
aggregateSummary: raw.aggregate_summary ?? null,
|
||||
aggregateChildren,
|
||||
uiState: normalizeUiState(
|
||||
(raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).uiState
|
||||
?? (raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).ui_state,
|
||||
(raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).ui_state,
|
||||
),
|
||||
group: finalGroup,
|
||||
group: task.group,
|
||||
};
|
||||
};
|
||||
const normalizedLegacyTasks = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(projection.history || []),
|
||||
].map(normalizeTask);
|
||||
const normalizedGroups = projection.status_groups
|
||||
? {
|
||||
failed: (projection.status_groups.failed || []).map(normalizeTask),
|
||||
waiting_human: (projection.status_groups.waiting_human || []).map(normalizeTask),
|
||||
processing: (projection.status_groups.processing || []).map(normalizeTask),
|
||||
completed: (projection.status_groups.completed || []).map(normalizeTask),
|
||||
cancelled: (projection.status_groups.cancelled || []).map(normalizeTask),
|
||||
archived: (projection.status_groups.archived || []).map(normalizeTask),
|
||||
}
|
||||
: null;
|
||||
// status_groups 存在时,传统四组只是兼容镜像,可能为空;统计必须保留后端 summary,
|
||||
// 绝不能据空镜像重新裁决成 0。
|
||||
const normalizedAll = normalizedGroups
|
||||
? [
|
||||
...normalizedGroups.failed,
|
||||
...normalizedGroups.waiting_human,
|
||||
...normalizedGroups.processing,
|
||||
...normalizedGroups.completed,
|
||||
...normalizedGroups.cancelled,
|
||||
...normalizedGroups.archived,
|
||||
]
|
||||
: normalizedLegacyTasks;
|
||||
const needs_action = normalizedGroups
|
||||
? [...normalizedGroups.failed, ...normalizedGroups.waiting_human]
|
||||
: normalizedAll.filter((task) => task.group === 'needs_action');
|
||||
const processing = normalizedGroups?.processing || normalizedAll.filter((task) => task.group === 'processing');
|
||||
const completed = normalizedGroups?.completed || normalizedAll.filter((task) => task.group === 'completed');
|
||||
const history = normalizedGroups
|
||||
? [...normalizedGroups.cancelled, ...normalizedGroups.archived]
|
||||
: normalizedAll.filter((task) => task.group === 'history');
|
||||
const normalizedGroups = {
|
||||
failed: (projection.status_groups?.failed || []).map(normalizeTask),
|
||||
waiting_human: (projection.status_groups?.waiting_human || []).map(normalizeTask),
|
||||
processing: (projection.status_groups?.processing || []).map(normalizeTask),
|
||||
completed: (projection.status_groups?.completed || []).map(normalizeTask),
|
||||
cancelled: (projection.status_groups?.cancelled || []).map(normalizeTask),
|
||||
archived: (projection.status_groups?.archived || []).map(normalizeTask),
|
||||
};
|
||||
const {
|
||||
needs_action: _legacyNeedsAction,
|
||||
processing: _legacyProcessing,
|
||||
completed: _legacyCompleted,
|
||||
history: _legacyHistory,
|
||||
...authoritativeProjection
|
||||
} = projection;
|
||||
return {
|
||||
...projection,
|
||||
// [AUTHORITY] 新批次 status_groups + summary 同属一次后端裁决。summary 可能覆盖完整批次,
|
||||
// 而当前组只返回可见 EML;前端不得用局部行数覆盖后端文件/任务统计。
|
||||
summary: backendAuthoritative
|
||||
? projection.summary
|
||||
: {
|
||||
...(projection.summary || {}),
|
||||
total_tasks: normalizedAll.length,
|
||||
total_files: normalizedAll.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
|
||||
needs_action: needs_action.length,
|
||||
processing: processing.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
},
|
||||
needs_action,
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
status_groups: normalizedGroups || projection.status_groups,
|
||||
four_stage_nodes: projection.four_stage_nodes || [],
|
||||
...authoritativeProjection,
|
||||
// [AUTHORITY] summary 与 status_groups 同属后端一次裁决。前端不得从局部 EML
|
||||
// 行重算任务/文件统计,也不得重新生成旧四组镜像。
|
||||
summary: projection.summary,
|
||||
status_groups: normalizedGroups,
|
||||
lifecycle_nodes: projection.lifecycle_nodes || [],
|
||||
unclassified_summary: projection.unclassified_summary || { count: 0 },
|
||||
ui_state: projection.ui_state || undefined,
|
||||
output_artifacts: projection.output_artifacts || [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(order_task 与 EML order_intake)。
|
||||
*
|
||||
* 核心逻辑:order_task 与 EML order_intake 均进入状态区;非 EML intake 不入组;
|
||||
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
|
||||
*
|
||||
* @param workItems - 统一投影 work_items
|
||||
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
|
||||
* @returns 兼容投影;无可展示任务时返回 null
|
||||
*/
|
||||
export function projectConversationProcessingFromWorkItems(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
const orderTasks = items.filter((row) => (
|
||||
row.workItemType === 'order_task'
|
||||
|| (row.workItemType === 'order_intake' && row.sourceType === 'eml')
|
||||
));
|
||||
if (!orderTasks.length) return null;
|
||||
|
||||
const rawTaskEntries: Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }> = [];
|
||||
|
||||
for (const item of orderTasks) {
|
||||
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
|
||||
if (!taskNo) continue;
|
||||
const group = mapShippingProcessingStatusToTaskGroup(item);
|
||||
// EML 父项的 sourceSummary.filename 是邮件名,只能用于分组标题;
|
||||
// 文件行与数量必须来自其真实附件叶子。
|
||||
const leafFiles = flattenBusinessFileProjections([item]);
|
||||
const leafKeys = businessFileKeys([item]);
|
||||
const leafNames = [...new Set(leafFiles
|
||||
.map((child) => String(child.sourceSummary?.filename || '').trim())
|
||||
.filter(Boolean))];
|
||||
const leafObjects = leafFiles.map((child, index) => {
|
||||
const summary = child.sourceSummary || {};
|
||||
const documentId = Number(summary.documentId || 0) || undefined;
|
||||
const leafFilename = String(summary.filename || '').trim();
|
||||
return {
|
||||
kind: 'document' as const,
|
||||
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-leaf-${index}`,
|
||||
label: leafFilename || String(child.workItemNo || taskNo),
|
||||
filename: leafFilename || undefined,
|
||||
document_id: documentId,
|
||||
status_label: String(child.userStatus ?? child.status ?? ''),
|
||||
run_no: child.runNo || undefined,
|
||||
current_run_no: child.runNo || undefined,
|
||||
case_no: child.caseNo || undefined,
|
||||
task_no: child.rootOrderTaskNo || undefined,
|
||||
workflow_item_no: child.workItemNo || undefined,
|
||||
};
|
||||
});
|
||||
const isEmlContainer = item.sourceType === 'eml' && Array.isArray(item.aggregateChildren)
|
||||
&& item.aggregateChildren.length > 0;
|
||||
const sourceDocCount = Number(item.sourceSummary?.documentCount || 0);
|
||||
// 只有已展开的 EML 聚合以叶子集合覆盖后端摘要;普通/旧单项投影仍保留
|
||||
// sourceSummary.documentCount,避免稀疏投影把一个多文件任务错误压成 1 个文件。
|
||||
const docCount = isEmlContainer
|
||||
? leafKeys.length
|
||||
: (sourceDocCount || leafKeys.length);
|
||||
const filename = isEmlContainer
|
||||
? String(item.sourceSummary?.filename || '').trim()
|
||||
: (leafNames[0] || String(item.sourceSummary?.filename || '').trim());
|
||||
const normalizedActions = normalizeActionCodes(item.availableActions || []);
|
||||
const gateNextAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase() || null;
|
||||
const effectiveStatus = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim()) || null;
|
||||
const userBlocking: ConversationProcessingUserTask['blockingReason'] = (item.blockingReason && typeof item.blockingReason === 'object')
|
||||
? {
|
||||
code: item.blockingReason.code,
|
||||
i18nKey: (item.blockingReason as { i18nKey?: string | null }).i18nKey
|
||||
?? (item.blockingReason as { i18n_key?: string | null }).i18n_key
|
||||
?? undefined,
|
||||
details: (item.blockingReason as { details?: Record<string, unknown> }).details,
|
||||
} satisfies ShippingProcessingBlockingReason
|
||||
: null;
|
||||
const userPrimaryAction: ConversationProcessingUserTask['primaryAction'] = item.primaryAction
|
||||
? {
|
||||
code: item.primaryAction.code,
|
||||
i18nKey: (item.primaryAction as { i18nKey?: string | null }).i18nKey
|
||||
?? (item.primaryAction as { i18n_key?: string | null }).i18n_key
|
||||
?? undefined,
|
||||
parameters: (item.primaryAction as { parameters?: Record<string, unknown> }).parameters,
|
||||
} satisfies ShippingProcessingPrimaryAction
|
||||
: null;
|
||||
const userFacts: ConversationProcessingUserTask['facts'] = item.facts
|
||||
? {
|
||||
inventorySourceStatus: (item.facts as { inventorySourceStatus?: string | null }).inventorySourceStatus ?? undefined,
|
||||
candidateSourceCodes: (item.facts as { candidateSourceCodes?: string[] }).candidateSourceCodes ?? [],
|
||||
preparedSourceCodes: (item.facts as { preparedSourceCodes?: string[] }).preparedSourceCodes ?? [],
|
||||
pendingSourceCodes: (item.facts as { pendingSourceCodes?: string[] }).pendingSourceCodes ?? [],
|
||||
lineResolutions: (item.facts as { lineResolutions?: Record<string, unknown>[] }).lineResolutions ?? undefined,
|
||||
exportState: (item.facts as { exportState?: string }).exportState ?? undefined,
|
||||
uploadState: (item.facts as { uploadState?: string }).uploadState ?? undefined,
|
||||
switchState: (item.facts as { switchState?: string }).switchState ?? undefined,
|
||||
forcedMatchSourceCode: (item.facts as { forcedMatchSourceCode?: string | null }).forcedMatchSourceCode ?? undefined,
|
||||
} satisfies ShippingProcessingFacts
|
||||
: undefined;
|
||||
const task: ConversationProcessingUserTask = {
|
||||
user_task_no: taskNo,
|
||||
user_task_authoritative: true,
|
||||
title: filename || null,
|
||||
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
|
||||
document_names: leafNames.length ? leafNames : (isEmlContainer ? [] : (filename ? [filename] : [])),
|
||||
group,
|
||||
status_label: effectiveStatus,
|
||||
file_count: docCount > 0 ? docCount : (isEmlContainer ? 0 : (filename ? 1 : 0)),
|
||||
run_no: String(item.runNo || '').trim() || null,
|
||||
objects: leafObjects,
|
||||
can_append: false,
|
||||
last_activity_at: item.lastActivityAt || null,
|
||||
available_actions: normalizedActions,
|
||||
primary_action: gateNextAction || normalizedActions[0] || null,
|
||||
userStatus: item.userStatus ?? null,
|
||||
userStage: item.userStage ?? null,
|
||||
blockingReason: userBlocking,
|
||||
primaryAction: userPrimaryAction,
|
||||
facts: userFacts,
|
||||
userGroup: item.userGroup ?? null,
|
||||
userCurrentGateCode: item.userCurrentGateCode ?? null,
|
||||
legacyStatus: item.legacyStatus ?? null,
|
||||
legacyStage: item.legacyStage ?? null,
|
||||
aggregateSummary: item.aggregateSummary ?? null,
|
||||
aggregateChildren: item.aggregateChildren ?? [],
|
||||
};
|
||||
rawTaskEntries.push({ task, item });
|
||||
}
|
||||
|
||||
const rawTasks: ConversationProcessingUserTask[] = [];
|
||||
const emlGroups = new Map<string, Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }>>();
|
||||
for (const entry of rawTaskEntries) {
|
||||
if (entry.item.sourceType !== 'eml' || !entry.item.intakeNo) {
|
||||
rawTasks.push(entry.task);
|
||||
continue;
|
||||
}
|
||||
const key = String(entry.item.intakeNo).trim();
|
||||
const group = emlGroups.get(key) || [];
|
||||
group.push(entry);
|
||||
emlGroups.set(key, group);
|
||||
}
|
||||
for (const [intakeNo, entries] of emlGroups) {
|
||||
if (entries.length === 1) {
|
||||
rawTasks.push({
|
||||
...entries[0]!.task,
|
||||
aggregateChildren: entries[0]!.task.aggregateChildren?.length
|
||||
? entries[0]!.task.aggregateChildren
|
||||
: entries[0]!.item.aggregateChildren || [],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const completed = entries.filter(({ item }) => String(item.userStatus ?? item.status).toLowerCase() === 'completed').length;
|
||||
const failed = entries.filter(({ item }) => ['failed', 'retryable'].includes(String(item.userStatus ?? item.status).toLowerCase())).length;
|
||||
const needsAction = entries.filter(({ task }) => task.group === 'needs_action').length;
|
||||
const processing = entries.filter(({ task }) => task.group === 'processing').length;
|
||||
const stages = [...new Set(entries.flatMap(({ item }) => [item.userStage, item.stage].filter(Boolean).map(String)))];
|
||||
const reasonCodes = [...new Set(entries.flatMap(({ item }) => [
|
||||
item.blockingReason?.code,
|
||||
item.sourceSummary?.failureReasonCode,
|
||||
].filter(Boolean).map(String)))];
|
||||
const entryGroups = entries.map(({ task, item }) => {
|
||||
const children = item.aggregateChildren || [];
|
||||
const childStatuses = children.map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
|
||||
if (childStatuses.some((value) => value === 'failed')) return 'failed';
|
||||
if (childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready')) return 'waiting_human';
|
||||
if (childStatuses.length > 0 && childStatuses.every((value, index) => value === 'completed' && children[index]?.facts?.uploadState === 'succeeded')) return 'completed';
|
||||
const explicit = String(item.userGroup || '').trim().toLowerCase();
|
||||
if (explicit) return explicit;
|
||||
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
|
||||
if (status === 'failed' || status === 'retryable') return 'failed';
|
||||
if (task.group === 'needs_action') return 'waiting_human';
|
||||
if (task.group === 'completed' && status === 'completed') return 'completed';
|
||||
if (task.group === 'history') return status === 'cancelled' ? 'cancelled' : 'archived';
|
||||
return 'processing';
|
||||
});
|
||||
const aggregateUserGroup = entryGroups.includes('failed')
|
||||
? 'failed'
|
||||
: entryGroups.includes('waiting_human')
|
||||
? 'waiting_human'
|
||||
: entryGroups.includes('processing')
|
||||
? 'processing'
|
||||
: entryGroups.includes('completed') && entryGroups.every((value) => value === 'completed')
|
||||
? 'completed'
|
||||
: entryGroups.includes('cancelled')
|
||||
? 'cancelled'
|
||||
: entryGroups.includes('archived')
|
||||
? 'archived'
|
||||
: 'processing';
|
||||
const group = aggregateUserGroup === 'failed' || aggregateUserGroup === 'waiting_human'
|
||||
? 'needs_action'
|
||||
: aggregateUserGroup === 'completed'
|
||||
? 'completed'
|
||||
: aggregateUserGroup === 'cancelled' || aggregateUserGroup === 'archived'
|
||||
? 'history'
|
||||
: 'processing';
|
||||
const representative = entries[0]!.task;
|
||||
const aggregateChildren = entries.flatMap(({ item }) => item.aggregateChildren || [item]);
|
||||
const documentNames = [...new Set(flattenBusinessFileProjections(aggregateChildren)
|
||||
.map((child) => String(child.sourceSummary?.filename || '').trim())
|
||||
.filter(Boolean))];
|
||||
const fileCount = businessFileKeys(aggregateChildren).length;
|
||||
rawTasks.push({
|
||||
...representative,
|
||||
title: representative.title || `EML ${intakeNo}`,
|
||||
display_kind: fileCount > 1 ? 'multi_document_task' : representative.display_kind,
|
||||
document_names: documentNames,
|
||||
file_count: fileCount,
|
||||
group,
|
||||
available_actions: [...new Set(entries.flatMap(({ task }) => task.available_actions || []))].sort(),
|
||||
aggregateSummary: {
|
||||
intakeNo,
|
||||
total: entries.length,
|
||||
completed,
|
||||
processing,
|
||||
needsAction,
|
||||
failed,
|
||||
stages,
|
||||
reasonCodes,
|
||||
},
|
||||
aggregateChildren,
|
||||
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
|
||||
});
|
||||
}
|
||||
|
||||
if (!rawTasks.length) return null;
|
||||
|
||||
const needs_action_raw: ConversationProcessingUserTask[] = [];
|
||||
const processing_raw: ConversationProcessingUserTask[] = [];
|
||||
const completed_raw: ConversationProcessingUserTask[] = [];
|
||||
const history_raw: ConversationProcessingUserTask[] = [];
|
||||
for (const task of rawTasks) {
|
||||
if (task.group === 'needs_action') needs_action_raw.push(task);
|
||||
else if (task.group === 'processing') processing_raw.push(task);
|
||||
else if (task.group === 'completed') completed_raw.push(task);
|
||||
else history_raw.push(task);
|
||||
}
|
||||
const active = [...needs_action_raw, ...processing_raw, ...completed_raw];
|
||||
if (!active.length && !history_raw.length) return null;
|
||||
|
||||
// 统计口径与卡片完全一致:递归叶子业务文件,排除 EML 容器。
|
||||
const totalFiles = businessFileKeys(orderTasks).length || active.reduce(
|
||||
(sum, task) => sum + Number(task.file_count || 0),
|
||||
0,
|
||||
);
|
||||
|
||||
const stabilizedAll = stabilizeTaskObjects(
|
||||
previousProjection
|
||||
? [
|
||||
...(previousProjection.needs_action || []),
|
||||
...(previousProjection.processing || []),
|
||||
...(previousProjection.completed || []),
|
||||
...(previousProjection.history || []),
|
||||
]
|
||||
: [],
|
||||
rawTasks,
|
||||
);
|
||||
const needs_action = stabilizeTaskObjects(
|
||||
previousProjection?.needs_action || [],
|
||||
stabilizedAll.filter((t) => t.group === 'needs_action'),
|
||||
);
|
||||
const processing = stabilizeTaskObjects(
|
||||
previousProjection?.processing || [],
|
||||
stabilizedAll.filter((t) => t.group === 'processing'),
|
||||
);
|
||||
const completed = stabilizeTaskObjects(
|
||||
previousProjection?.completed || [],
|
||||
stabilizedAll.filter((t) => t.group === 'completed'),
|
||||
);
|
||||
const history = stabilizeTaskObjects(
|
||||
previousProjection?.history || [],
|
||||
stabilizedAll.filter((t) => t.group === 'history'),
|
||||
);
|
||||
|
||||
const status_groups = {
|
||||
failed: stabilizedAll.filter((task) => task.userGroup === 'failed'),
|
||||
waiting_human: stabilizedAll.filter((task) => task.userGroup === 'waiting_human'),
|
||||
processing: stabilizedAll.filter((task) => task.userGroup === 'processing'),
|
||||
completed: stabilizedAll.filter((task) => task.userGroup === 'completed'),
|
||||
cancelled: stabilizedAll.filter((task) => task.userGroup === 'cancelled'),
|
||||
archived: stabilizedAll.filter((task) => task.userGroup === 'archived'),
|
||||
};
|
||||
|
||||
return {
|
||||
summary: {
|
||||
total_tasks: active.length,
|
||||
total_files: totalFiles,
|
||||
processing: processing.length,
|
||||
needs_action: needs_action.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
},
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action,
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
status_groups,
|
||||
};
|
||||
}
|
||||
@@ -82,7 +82,7 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
|
||||
expect(normalized!.sourceSummary.documentId).toBe(17);
|
||||
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
|
||||
expect(normalized!.availableActions).toEqual(['open_review']);
|
||||
expect(normalized!.availableActions).toEqual(['resolve_field_conflicts', 'view_details']);
|
||||
expect(normalized!.uiState).toMatchObject({
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
@@ -108,6 +108,35 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('保留后端五阶段生命周期入口,包括 freight_upload', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'OT-LIFECYCLE-5',
|
||||
work_item_type: 'order_task',
|
||||
status: 'waiting_review',
|
||||
stage: 'freight_uploading',
|
||||
ui_state: {
|
||||
status: 'waiting_human',
|
||||
stage: 'freight_uploading',
|
||||
lifecycle_stage: 'freight_upload',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'order_review', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'current', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', target_surface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(normalized?.uiState?.lifecycleEntries).toEqual([
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'freight_upload', state: 'current', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes structured inventory candidate facts', () => {
|
||||
const projection = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'SN-001',
|
||||
|
||||
@@ -25,25 +25,23 @@ import type {
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
/** 后端可裁决并透传到订单生命周期工作台的阶段;前端不根据本地状态补造入口。 */
|
||||
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
|
||||
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
|
||||
|
||||
/**
|
||||
* 读取原始对象上的字符串字段(兼容 snake / camel)。
|
||||
*/
|
||||
function readString(raw: Record<string, unknown>, snake: string, camel: string): string {
|
||||
const value = raw[snake] ?? raw[camel];
|
||||
/** 读取后端正式 snake_case DTO 的字符串字段。 */
|
||||
function readString(raw: Record<string, unknown>, snake: string, _removedLegacyCamel?: string): string {
|
||||
const value = raw[snake];
|
||||
return value == null ? '' : String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取可空字符串。
|
||||
* 读取后端正式 snake_case DTO 的可空字符串。
|
||||
*/
|
||||
function readNullableString(
|
||||
raw: Record<string, unknown>,
|
||||
snake: string,
|
||||
camel: string,
|
||||
_removedLegacyCamel?: string,
|
||||
): string | null {
|
||||
const value = raw[snake] ?? raw[camel];
|
||||
const value = raw[snake];
|
||||
if (value == null || value === '') return null;
|
||||
return String(value);
|
||||
}
|
||||
@@ -118,7 +116,7 @@ function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
|
||||
details:
|
||||
typeof item.details === 'object' && item.details != null
|
||||
? (item.details as Record<string, unknown>)
|
||||
@@ -136,23 +134,23 @@ function normalizePrimaryAction(raw: unknown): ShippingProcessingPrimaryAction |
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
|
||||
parameters:
|
||||
typeof item.parameters === 'object' && item.parameters != null
|
||||
? (item.parameters as Record<string, unknown>)
|
||||
: {},
|
||||
executionMode: item.execution_mode === 'navigate' || item.executionMode === 'navigate'
|
||||
executionMode: item.execution_mode === 'navigate'
|
||||
? 'navigate'
|
||||
: item.execution_mode === 'execute' || item.executionMode === 'execute'
|
||||
: item.execution_mode === 'execute'
|
||||
? 'execute'
|
||||
: undefined,
|
||||
targetSurface: item.target_surface === 'order_lifecycle_workbench' || item.targetSurface === 'order_lifecycle_workbench'
|
||||
targetSurface: item.target_surface === 'order_lifecycle_workbench'
|
||||
? 'order_lifecycle_workbench'
|
||||
: null,
|
||||
targetLifecycleStage: lifecycleStages.includes(
|
||||
String(item.target_lifecycle_stage ?? item.targetLifecycleStage ?? '') as typeof lifecycleStages[number],
|
||||
String(item.target_lifecycle_stage ?? '') as typeof lifecycleStages[number],
|
||||
)
|
||||
? String(item.target_lifecycle_stage ?? item.targetLifecycleStage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
|
||||
? String(item.target_lifecycle_stage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -165,10 +163,10 @@ function normalizeLifecycleEntries(raw: unknown): NonNullable<ConversationProces
|
||||
.map((item) => ({
|
||||
code: String(item.code ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['code'],
|
||||
state: String(item.state ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['state'],
|
||||
targetSurface: String(item.target_surface ?? item.targetSurface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
|
||||
targetSurface: String(item.target_surface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
|
||||
disabledReasonKey: item.disabled_reason_key != null
|
||||
? String(item.disabled_reason_key)
|
||||
: item.disabledReasonKey != null ? String(item.disabledReasonKey) : null,
|
||||
: null,
|
||||
}))
|
||||
.filter((item) => lifecycleStages.includes(item.code as typeof lifecycleStages[number])
|
||||
&& ['available', 'current', 'unavailable'].includes(item.state)
|
||||
@@ -373,9 +371,13 @@ export function normalizeShippingProcessingProjection(
|
||||
const children = Array.isArray(childrenRaw)
|
||||
? childrenRaw.map(normalizeChildTask).filter((row): row is ShippingOrderTaskSummary => Boolean(row))
|
||||
: [];
|
||||
const actionsRaw = item.available_actions ?? item.availableActions;
|
||||
const availableActions = Array.isArray(actionsRaw)
|
||||
? actionsRaw.map((action) => String(action || '').trim()).filter(Boolean)
|
||||
// ui_state 是处理进度唯一的用户态/动作合同。旧顶层动作字段已下线,
|
||||
// 客户端只能由该合同派生本地展示索引,不能读取或补造历史 available_actions。
|
||||
const uiState = normalizeProcessingUiState(item.ui_state);
|
||||
const availableActions = uiState
|
||||
? [uiState.primary_action, ...uiState.secondary_actions]
|
||||
.map((action) => String(action?.code || '').trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const stageNodesRaw = item.stage_nodes ?? item.stageNodes;
|
||||
const stageNodes = Array.isArray(stageNodesRaw)
|
||||
@@ -428,14 +430,12 @@ export function normalizeShippingProcessingProjection(
|
||||
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
|
||||
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
|
||||
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
|
||||
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
|
||||
uiState: normalizeProcessingUiState(item.ui_state ?? item.uiState),
|
||||
primaryAction: uiState?.primary_action ?? null,
|
||||
uiState,
|
||||
facts: normalizeFacts(item.facts),
|
||||
userGroup: readNullableString(item, 'user_group', 'userGroup') as ShippingProcessingProjection['userGroup'],
|
||||
aggregateSummary: normalizeAggregateSummary(item.aggregate_summary ?? item.aggregateSummary),
|
||||
aggregateChildren: aggregateChildren?.length ? aggregateChildren : undefined,
|
||||
legacyStatus: readNullableString(item, 'legacy_status', 'legacyStatus'),
|
||||
legacyStage: readNullableString(item, 'legacy_stage', 'legacyStage'),
|
||||
hasFormalOt:
|
||||
(item.has_formal_ot as boolean | undefined) == null ? false : Boolean(item.has_formal_ot),
|
||||
inventoryPreparation: normalizeInventoryPreparation(
|
||||
@@ -453,11 +453,11 @@ function normalizeProcessGateSummary(raw: unknown): ShippingProcessGateUserSumma
|
||||
: null;
|
||||
}
|
||||
|
||||
/** 规范化单项后端 UI 裁决;缺失时返回 undefined 以保留旧响应兼容。 */
|
||||
/** 规范化单项后端 UI 裁决;缺失时不展示动作,禁止从旧顶层字段回退。 */
|
||||
function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection['uiState'] {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
const state = raw as Record<string, unknown>;
|
||||
const secondaryRaw = state.secondary_actions ?? state.secondaryActions;
|
||||
const secondaryRaw = state.secondary_actions;
|
||||
const secondaryActions = Array.isArray(secondaryRaw)
|
||||
? secondaryRaw
|
||||
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
|
||||
@@ -470,10 +470,10 @@ function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection[
|
||||
return {
|
||||
status: (readString(state, 'status', 'status') || 'running') as NonNullable<ShippingProcessingProjection['userStatus']>,
|
||||
stage: readString(state, 'stage', 'stage'),
|
||||
lifecycleStage: readString(state, 'lifecycle_stage', 'lifecycleStage') as ConversationProcessingUiState['lifecycleStage'],
|
||||
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries ?? state.lifecycleEntries),
|
||||
blocking_reason: normalizeBlockingReason(state.blocking_reason ?? state.blockingReason),
|
||||
primary_action: normalizePrimaryAction(state.primary_action ?? state.primaryAction),
|
||||
lifecycleStage: readString(state, 'lifecycle_stage') as ConversationProcessingUiState['lifecycleStage'],
|
||||
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries),
|
||||
blocking_reason: normalizeBlockingReason(state.blocking_reason),
|
||||
primary_action: normalizePrimaryAction(state.primary_action),
|
||||
secondary_actions: secondaryActions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface ShippingConversationContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; display_query?: string },
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import {
|
||||
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
|
||||
workspaceShippingNoticeExportUrl,
|
||||
workspaceShippingExportUrl,
|
||||
workspaceShippingInventoryFileUrl,
|
||||
workspaceShippingLineInventoryFileUrl,
|
||||
@@ -16,6 +17,14 @@ export async function downloadWorkspaceShippingExcelFile(taskId: string): Promis
|
||||
await downloadWorkspaceShippingFile(workspaceShippingExportUrl(taskId), `${taskId}.xlsx`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按发货通知单号下载其唯一正式 Excel。
|
||||
* 新货代操作只能传 business_no;task_no 下载函数仅保留给尚未迁移的非货代工作流。
|
||||
*/
|
||||
export async function downloadWorkspaceShippingNoticeExcelFile(businessNo: string): Promise<void> {
|
||||
await downloadWorkspaceShippingFile(workspaceShippingNoticeExportUrl(businessNo), `${businessNo}.xlsx`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载当前任务活动关联的库存快照。
|
||||
* 核心逻辑:浏览器只发起受控 URL;后端复核任务归属、active link 与物理文件,不按库存源猜测文件。
|
||||
@@ -60,8 +69,29 @@ async function downloadWorkspaceShippingFile(url: string, fallbackName: string):
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
|
||||
/** 批次 ZIP 下载只转发后端归档响应;选择和授权均不在前端重算。 */
|
||||
/** 多任务 ZIP 下载只转发后端归档响应;选择和授权均不在前端重算。 */
|
||||
export const downloadWorkspaceShippingExportArchive = (payload: {
|
||||
batch_no?: string;
|
||||
task_nos?: string[];
|
||||
}) => requestShippingExportArchive(payload);
|
||||
|
||||
/** 按多个 business_no 下载各自唯一 Excel 的 ZIP。 */
|
||||
export async function downloadWorkspaceShippingNoticeExportArchive(businessNos: string[]): Promise<void> {
|
||||
const response = await fetch('/api/workspace/shipping-notices/batch/export', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({ business_nos: businessNos }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({}));
|
||||
throw new Error((body as { error?: string; message?: string }).error || response.statusText);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = objectUrl;
|
||||
anchor.download = 'shipping_notices.zip';
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
document.body.removeChild(anchor);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingStepper.spec.ts
|
||||
* 用途:验证发货通知四阶段 Stepper 只消费后端 UI State 投影。
|
||||
* 用途:验证发货通知五阶段 Stepper 只消费后端 UI State 投影。
|
||||
* 依赖:shippingStepper 纯函数、vitest。
|
||||
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
|
||||
*/
|
||||
@@ -12,19 +12,20 @@ import {
|
||||
} from './shippingStepper';
|
||||
|
||||
describe('shippingStepper', () => {
|
||||
it('renders exactly four stages from backend ui_state', () => {
|
||||
it('renders exactly five stages from backend ui_state', () => {
|
||||
const steps = resolveShippingWorkflowSteps({
|
||||
ui_state: {
|
||||
steps: [
|
||||
{ id: 'shipping-stage-1', code: 'intake_parse', label: '接收解析', status: 'completed' },
|
||||
{ id: 'shipping-stage-2', code: 'order_review', label: '订单复核', status: 'completed' },
|
||||
{ id: 'shipping-stage-3', code: 'fulfillment_prep', label: '通知准备', status: 'blocked' },
|
||||
{ id: 'shipping-stage-4', code: 'upload_complete', label: '通知完成', status: 'pending' },
|
||||
{ id: 'shipping-stage-4', code: 'freight_upload', label: '货代上传', status: 'pending' },
|
||||
{ id: 'shipping-stage-5', code: 'upload_complete', label: '通知完成', status: 'pending' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(steps).toHaveLength(4);
|
||||
expect(steps).toHaveLength(5);
|
||||
expect(steps[2]?.status).toBe('blocked');
|
||||
});
|
||||
|
||||
@@ -33,17 +34,18 @@ describe('shippingStepper', () => {
|
||||
expect(normalizeShippingWorkflowSteps(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it('maps technical processing stages into the four business stages', () => {
|
||||
it('maps technical processing stages into the five business stages', () => {
|
||||
const base = normalizeShippingWorkflowSteps([
|
||||
{ code: 'intake_parse', status: 'pending' },
|
||||
{ code: 'order_review', status: 'pending' },
|
||||
{ code: 'fulfillment_prep', status: 'pending' },
|
||||
{ code: 'freight_upload', status: 'pending' },
|
||||
{ code: 'upload_complete', status: 'pending' },
|
||||
]);
|
||||
const steps = applyShippingProcessingStageToSteps(base, {
|
||||
stage: 'inventory_matching',
|
||||
status: 'running',
|
||||
});
|
||||
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending']);
|
||||
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending', 'pending']);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingStepper.ts
|
||||
* 用途:基于后端 ui_state 投影渲染四阶段业务 Stepper。
|
||||
* 用途:基于后端 ui_state 投影渲染五阶段业务 Stepper。
|
||||
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
|
||||
* 逻辑:只消费后端 ui_state.steps 四阶段投影;缺失投影时 fail-closed。
|
||||
* 逻辑:只消费后端 ui_state.steps 五阶段投影;缺失投影时 fail-closed。
|
||||
*/
|
||||
import {
|
||||
FULFILLMENT_PROGRESS_NODES,
|
||||
@@ -32,6 +32,7 @@ export const SHIPPING_WORKFLOW_STEP_LABELS = [
|
||||
'chat.shippingNoticeUi.stage.intakeParse',
|
||||
'chat.shippingNoticeUi.stage.orderReview',
|
||||
'chat.shippingNoticeUi.stage.fulfillmentPrep',
|
||||
'chat.shippingNoticeUi.stage.freightUpload',
|
||||
'chat.shippingNoticeUi.stage.uploadComplete',
|
||||
] as const;
|
||||
|
||||
@@ -90,7 +91,7 @@ const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
|
||||
inventory_matching: 2,
|
||||
excel_generating: 2,
|
||||
freight_uploading: 3,
|
||||
completed: 3,
|
||||
completed: 4,
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,12 +34,10 @@ export function resolveShippingChatTurn(
|
||||
/**
|
||||
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
|
||||
*/
|
||||
export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record<string, string> {
|
||||
export function buildShippingTurnRefs(taskNo: string): Record<string, string> {
|
||||
const refs: Record<string, string> = {};
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
const batch = String(batchNo || '').trim();
|
||||
if (task) refs.task_no = task;
|
||||
if (batch) refs.batch_no = batch;
|
||||
return refs;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/shippingUploadPrompt.ts
|
||||
* 用途:通知上传后提示语构建、文件格式识别与临时库存声明判断。
|
||||
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
|
||||
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify 完整动态订单抽取。
|
||||
* 逻辑:按提交结果生成 follow-up 提示;通知进入 Intake 后触发完整动态订单抽取。
|
||||
*/
|
||||
import i18n from '@/i18n';
|
||||
|
||||
@@ -10,17 +10,12 @@ import i18n from '@/i18n';
|
||||
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
|
||||
*/
|
||||
/**
|
||||
* 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发完整订单抽取链)。
|
||||
* 根据通知提交 API 响应生成发给 Dify 的 follow-up 提示语(触发完整订单抽取链)。
|
||||
*/
|
||||
export function buildShippingNoticeUploadPrompt(
|
||||
result: Record<string, unknown> | null | undefined,
|
||||
options?: { fileCount?: number; fileName?: string },
|
||||
): string {
|
||||
const batchNo = String(
|
||||
(result?.batch_no as string | undefined)
|
||||
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|
||||
|| '',
|
||||
).trim();
|
||||
const taskId = String(
|
||||
((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|
||||
|| (result?.task_id as string | undefined)
|
||||
@@ -39,9 +34,6 @@ export function buildShippingNoticeUploadPrompt(
|
||||
? String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelMulti', { fileCount }))
|
||||
: String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelDefault')));
|
||||
const parts = [String(i18n.global.t('chat.shippingNoticePrompt.notice.uploadedPrefix', { fileLabel }))];
|
||||
if (batchNo) {
|
||||
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.batchLabel', { batchNo })));
|
||||
}
|
||||
if (taskId) {
|
||||
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.taskLabel', { taskId })));
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ const createContext = (
|
||||
isThinking: ref(false),
|
||||
currentAgentId: computed(() => 42),
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
getActiveShippingBatchNo: () => 'BATCH-001',
|
||||
messages: ref([]),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
openShippingInventoryPicker: vi.fn((_taskId?: string) => true),
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface ShippingMenuHandlerContext {
|
||||
getActiveShippingTaskId: () => string;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
openShippingInventoryPicker: (taskId?: string) => boolean;
|
||||
openShippingNoticePicker: (taskId?: string) => boolean;
|
||||
openShippingCustomerDialog: (taskId: string) => Promise<void>;
|
||||
executeShippingDecision: (
|
||||
@@ -76,6 +77,10 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
ctx.openShippingNoticePicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
ctx.openShippingInventoryPicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id && [
|
||||
'freeze_order', 'match_inventory', 'rematch',
|
||||
'generate_excel', 'retry_upload', 'mark_manual_uploaded', 'reparse_inventory',
|
||||
|
||||
@@ -21,18 +21,18 @@ describe('useChatShippingRefresh', () => {
|
||||
getWorkspaceShippingTaskUiState.mockReset();
|
||||
});
|
||||
|
||||
it('prefers current batch focus task over other explicit anchors', () => {
|
||||
it('prefers active task over message, resolved and query anchors', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: 'sn-batch-001',
|
||||
activeTaskId: 'sn-active-001',
|
||||
messageTaskId: 'sn-message-001',
|
||||
resolvedTaskId: 'sn-resolved-001',
|
||||
queryTaskId: 'sn-query-001',
|
||||
})).toBe('SN-BATCH-001');
|
||||
})).toBe('SN-ACTIVE-001');
|
||||
});
|
||||
|
||||
it('returns empty string when no explicit task anchor is available', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: '',
|
||||
activeTaskId: '',
|
||||
messageTaskId: '',
|
||||
resolvedTaskId: '',
|
||||
queryTaskId: '',
|
||||
@@ -42,7 +42,6 @@ describe('useChatShippingRefresh', () => {
|
||||
it('syncs ui_state for notifications without attaching chat action buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-FOCUS-B',
|
||||
batch_no: 'SB-FOCUS-001',
|
||||
checkpoint: 'ready_export',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
@@ -70,7 +69,7 @@ describe('useChatShippingRefresh', () => {
|
||||
const messages = ref([
|
||||
{
|
||||
role: 'assistant' as const,
|
||||
content: '请继续处理当前批次',
|
||||
content: '请继续处理当前任务',
|
||||
shipping_actions: [
|
||||
{
|
||||
id: 'old-action',
|
||||
@@ -89,7 +88,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-FOCUS-B',
|
||||
getActiveShippingTaskId: () => 'SN-FOCUS-B',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
@@ -103,7 +102,6 @@ describe('useChatShippingRefresh', () => {
|
||||
it('clears legacy shipping_actions even when api returns action_buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-SOURCE-001',
|
||||
batch_no: 'SB-SOURCE-001',
|
||||
checkpoint: 'ready_export',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
@@ -158,7 +156,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId: ref('SN-SOURCE-001'),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-SOURCE-001',
|
||||
getActiveShippingTaskId: () => 'SN-SOURCE-001',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
@@ -181,7 +179,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => '',
|
||||
getActiveShippingTaskId: () => '',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
|
||||
@@ -19,25 +19,27 @@ export interface ShippingRefreshContext {
|
||||
isThinking: Ref<boolean>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
getActiveBatchTaskId: () => string;
|
||||
getActiveShippingTaskId: () => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前聊天页最可靠的发货任务编号。
|
||||
*
|
||||
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
|
||||
* 核心逻辑:优先使用消息内嵌任务号,再回退到已解析状态和路由参数;
|
||||
* 禁止再按 conversation 标题“猜”一票,避免多票会话把状态挂错任务。
|
||||
* @param params - 当前聊天页中可用的任务定位线索
|
||||
* @returns 可信的任务编号;无法明确定位时返回空字符串
|
||||
*/
|
||||
export function resolvePreferredShippingTaskId(params: {
|
||||
activeTaskId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
messageTaskId?: string | null;
|
||||
resolvedTaskId?: string | null;
|
||||
queryTaskId?: string | null;
|
||||
}) {
|
||||
return String(
|
||||
params.batchTaskId
|
||||
params.activeTaskId
|
||||
|| params.batchTaskId
|
||||
|| params.messageTaskId
|
||||
|| params.resolvedTaskId
|
||||
|| params.queryTaskId
|
||||
@@ -71,7 +73,7 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
const msgs = ctx.messages.value;
|
||||
if (!msgs.length) return;
|
||||
const taskId = resolvePreferredShippingTaskId({
|
||||
batchTaskId: ctx.getActiveBatchTaskId(),
|
||||
activeTaskId: ctx.getActiveShippingTaskId(),
|
||||
messageTaskId: findLatestShippingTaskId(msgs),
|
||||
resolvedTaskId: ctx.resolvedShippingTaskId.value,
|
||||
queryTaskId: ctx.shippingTaskIdFromQuery.value,
|
||||
|
||||
@@ -19,7 +19,6 @@ const createContext = (
|
||||
attachments: ref([]),
|
||||
shippingAutoFlowRequested: ref(true),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
getActiveShippingBatchNo: () => '',
|
||||
currentAgentId: computed(() => 1),
|
||||
selectedKb: ref(''),
|
||||
attachmentPolicy: computed(() => ({ anyEnabled: true })),
|
||||
@@ -47,7 +46,6 @@ const createContext = (
|
||||
getParsedIntakeNos: () => [],
|
||||
startOrderExtractionRun: vi.fn(async () => true),
|
||||
applyShippingMessageRecovery: vi.fn(async () => false),
|
||||
applyShippingBatchSnapshot: vi.fn(() => false),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
shippingSuggestedPrompt: computed(() => ''),
|
||||
@@ -254,7 +252,6 @@ describe('useChatShippingSendHandler', () => {
|
||||
|
||||
it('warns and consumes send when user tries batch task switching (co8 batch API retired)', async () => {
|
||||
const ctx = createContext({
|
||||
getActiveShippingBatchNo: () => 'SB-TEST',
|
||||
});
|
||||
const { tryHandleShippingSend } = createShippingSendHandlers(ctx);
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ export interface ShippingSendHandlerContext {
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
shippingAutoFlowRequested: Ref<boolean>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
getActiveShippingBatchNo: () => string;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
@@ -45,7 +44,7 @@ export interface ShippingSendHandlerContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
@@ -72,8 +71,6 @@ export interface ShippingSendHandlerContext {
|
||||
uploadBatchId?: string,
|
||||
) => Promise<boolean>;
|
||||
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
|
||||
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
isShippingShortageQueryIntent: (text: string) => boolean;
|
||||
|
||||
@@ -7,9 +7,7 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
clearPendingNoticeBatchRetry,
|
||||
createShippingUploadHandlers,
|
||||
onNoticeBatchConversationChanging,
|
||||
resetShippingNoticeBatchSubmitStateForTests,
|
||||
type ShippingUploadHandlerContext,
|
||||
} from './useChatShippingUploadHandler';
|
||||
@@ -47,9 +45,6 @@ const createContext = (
|
||||
pendingShippingNoticeTaskId: ref(''),
|
||||
pendingShippingInventoryFile: ref(null),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
resolvedShippingBatchNo: ref(''),
|
||||
shippingBatchSummary: ref(null),
|
||||
shippingBatchTasks: ref([]),
|
||||
shippingInventorySelectionActive: ref(false),
|
||||
shippingInventorySelectionTaskId: ref(''),
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
@@ -222,12 +217,6 @@ describe('useChatShippingUploadHandler', () => {
|
||||
expect(ctx.msg.warning).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('compatibility hooks for pending batch retry remain callable after co8', () => {
|
||||
clearPendingNoticeBatchRetry();
|
||||
onNoticeBatchConversationChanging('conv-b', 'conv-a');
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
|
||||
it('does not open notice picker when both explicit taskId and active task are missing', () => {
|
||||
const noticeClick = vi.fn();
|
||||
const warning = vi.fn();
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
* 单票覆盖仍经 replace_notice Turn;库存文件先成为私有临时资产再进 Dify 分析分支。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
|
||||
@@ -18,25 +17,6 @@ import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
let noticeBatchSubmitting = false;
|
||||
|
||||
/**
|
||||
* 显式清理待重试建批幂等状态(co8 后建批已下线,保留空实现供会话切换调用方兼容)。
|
||||
*/
|
||||
export function clearPendingNoticeBatchRetry(): void {
|
||||
/* no-op: shipping_batches 已 DROP */
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户主动切换会话时的钩子(co8 后无幂等键可清)。
|
||||
* @param _nextId - 新会话 ID
|
||||
* @param _prevId - 旧会话 ID
|
||||
*/
|
||||
export function onNoticeBatchConversationChanging(
|
||||
_nextId: string,
|
||||
_prevId?: string | null,
|
||||
): void {
|
||||
/* no-op */
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。
|
||||
*/
|
||||
@@ -47,7 +27,6 @@ export function isShippingNoticeBatchSubmitting(): boolean {
|
||||
/** 单测重置模块级建批提交状态。 */
|
||||
export function resetShippingNoticeBatchSubmitStateForTests(): void {
|
||||
noticeBatchSubmitting = false;
|
||||
clearPendingNoticeBatchRetry();
|
||||
}
|
||||
|
||||
export interface ShippingUploadHandlerContext {
|
||||
@@ -62,9 +41,6 @@ export interface ShippingUploadHandlerContext {
|
||||
pendingShippingNoticeTaskId: Ref<string>;
|
||||
pendingShippingInventoryFile: Ref<File | null>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
resolvedShippingBatchNo: Ref<string>;
|
||||
shippingBatchSummary: Ref<unknown | null>;
|
||||
shippingBatchTasks: Ref<ShippingTaskSummary[]>;
|
||||
shippingInventorySelectionActive: Ref<boolean>;
|
||||
shippingInventorySelectionTaskId: Ref<string>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
@@ -160,11 +136,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
|
||||
const syncBatchContextFromTurnMessage = (assistantMsg: ChatMessage) => {
|
||||
const payload = assistantMsg.payload && typeof assistantMsg.payload === 'object'
|
||||
? assistantMsg.payload as { batch_no?: string; task_no?: string; orchestrator_started?: boolean }
|
||||
? assistantMsg.payload as { task_no?: string; orchestrator_started?: boolean }
|
||||
: {};
|
||||
const batchNo = String(payload.batch_no || assistantMsg.shipping_ui_state?.batch_no || '').trim();
|
||||
const taskId = String(payload.task_no || assistantMsg.shipping_ui_state?.task_no || '').trim();
|
||||
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
};
|
||||
|
||||
|
||||
@@ -201,6 +201,42 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('uses summary PDF leaves as the minimal live work items for the batch center', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [{
|
||||
workItemType: 'order_task', workItemNo: 'DOCUMENT:1', rootOrderTaskNo: 'OT-1',
|
||||
sourceType: 'direct_pdf', status: 'processing', stage: 'document_parsing',
|
||||
sourceSummary: { documentId: 1, filename: 'po.pdf', documentCount: 1 },
|
||||
}],
|
||||
conversation_processing: buildProcessing(),
|
||||
});
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processingWorkItems.value[0]?.sourceSummary.filename).toBe('po.pdf');
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('applies a current conversation response that completes after 10 seconds', async () => {
|
||||
const pending = deferred<ReturnType<typeof buildUnifiedProcessing>>();
|
||||
api.getShippingProcessing.mockImplementation(() => pending.promise);
|
||||
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
// API 层拥有共享请求的 30 秒超时;10 秒后当前会话不能先把消费者标为取消。
|
||||
await vi.advanceTimersByTimeAsync(10_001);
|
||||
pending.resolve(buildUnifiedProcessing('conv-1'));
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
|
||||
expect(ctl.processing.value?.conversation_id).toBe('conv-1');
|
||||
expect(ctl.initialLoading.value).toBe(false);
|
||||
expect(ctl.error.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('records recoverable error without throwing', async () => {
|
||||
const conversationId = ref('conv-1');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
@@ -243,7 +279,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('uses unified work_items as the sole processing read source', async () => {
|
||||
it('does not rebuild conversation processing from work_items without status_groups', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [buildOrderTaskWorkItem('OT-UNIFIED', {
|
||||
@@ -265,12 +301,12 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(api.getShippingProcessing).toHaveBeenCalled();
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(1);
|
||||
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-UNIFIED');
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(0);
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('preserves previous order_task work_items when stabilizer keeps previous projection', async () => {
|
||||
it('does not retain a legacy work_items-derived projection across sparse responses', async () => {
|
||||
api.getShippingProcessing
|
||||
.mockResolvedValueOnce({
|
||||
conversation_id: 'conv-1',
|
||||
@@ -310,21 +346,17 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(1);
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemNo).toBe('OT-STABLE');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('aggregates sibling EML OT work_items into one highest-attention Intake card', async () => {
|
||||
it('does not aggregate sibling work_items in the browser when status_groups is absent', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [
|
||||
@@ -409,15 +441,8 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
|
||||
expect(ctl.processing.value?.processing).toEqual([]);
|
||||
expect(ctl.processing.value?.needs_action[0]?.aggregateSummary).toMatchObject({
|
||||
intakeNo: 'SNI-1',
|
||||
total: 2,
|
||||
processing: 1,
|
||||
});
|
||||
expect(ctl.processing.value?.focused_task_no).toBe('OT-ROOT');
|
||||
expect(ctl.processing.value?.recent_task_no).toBe('OT-SIBLING');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
expect(ctl.processingWorkItems.value).toEqual([]);
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
@@ -436,7 +461,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(api.getShippingProcessing).toHaveBeenCalledTimes(2);
|
||||
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-conv-1');
|
||||
expect(ctl.processing.value?.status_groups?.waiting_human[0]?.user_task_no).toBe('OT-conv-1');
|
||||
expect(ctl.error.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。
|
||||
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing;
|
||||
* focus/viewed 写路径优先应用响应中的 work_items;
|
||||
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;
|
||||
* 前台 2s / 后台 8s;共享请求的超时由 API 层统一管理;会话切换/卸载才取消当前消费者;失败指数退避至 8s;
|
||||
* 分层轮询:仅系统处理中 2s 轮询;外部 Run 轮询不会在待人工处理时反复唤醒本读接口;
|
||||
* 区分 initialLoading / manualRefreshing / polling 三种 loading 态;
|
||||
* 语义签名比较:业务状态未变化时不替换投影对象,防止按钮闪烁与 DOM 重建。
|
||||
@@ -40,7 +40,6 @@ const FIRST_ACTIVE_POLL_MS = 2000;
|
||||
const MID_ACTIVE_POLL_MS = 5000;
|
||||
const LONG_ACTIVE_POLL_MS = 10000;
|
||||
const BACKGROUND_POLL_MS = 30000;
|
||||
const REQUEST_TIMEOUT_MS = 10000;
|
||||
const MAX_BACKOFF_MS = 30000;
|
||||
const SNAPSHOT_CACHE_LIMIT = 20;
|
||||
|
||||
@@ -137,7 +136,7 @@ export function shouldContinueProcessingPolling(
|
||||
processing?: ConversationProcessingProjection | null,
|
||||
): boolean {
|
||||
const processingCount = Number(
|
||||
processing?.summary?.processing || processing?.processing?.length || 0,
|
||||
processing?.summary?.processing ?? processing?.status_groups?.processing.length ?? 0,
|
||||
);
|
||||
return processingCount > 0;
|
||||
}
|
||||
@@ -200,10 +199,22 @@ export function useShippingNoticeWorkflow(
|
||||
return JSON.stringify(items.map((item) => ({
|
||||
no: item.workItemNo,
|
||||
type: item.workItemType,
|
||||
status: item.uiState?.status ?? item.userStatus ?? item.status,
|
||||
stage: item.uiState?.stage ?? item.userStage ?? item.stage,
|
||||
gate: item.uiState?.blocking_reason?.code ?? item.blockingReason?.code ?? null,
|
||||
action: item.uiState?.primary_action?.code ?? item.primaryAction?.code ?? null,
|
||||
status: item.uiState?.status ?? null,
|
||||
stage: item.uiState?.stage ?? null,
|
||||
runNo: item.runNo ?? null,
|
||||
caseNo: item.caseNo ?? null,
|
||||
gate: item.uiState?.blocking_reason?.code ?? null,
|
||||
action: (() => {
|
||||
const action = item.uiState?.primary_action ?? null;
|
||||
return action
|
||||
? {
|
||||
code: action.code,
|
||||
executionMode: action.executionMode ?? null,
|
||||
targetSurface: action.targetSurface ?? null,
|
||||
targetLifecycleStage: action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null;
|
||||
})(),
|
||||
lifecycleEntries: item.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -215,6 +226,16 @@ export function useShippingNoticeWorkflow(
|
||||
no: child.workItemNo,
|
||||
status: child.uiState?.status ?? child.userStatus ?? child.status,
|
||||
stage: child.uiState?.stage ?? child.userStage ?? child.stage,
|
||||
runNo: child.runNo ?? null,
|
||||
caseNo: child.caseNo ?? null,
|
||||
primaryAction: child.uiState?.primary_action
|
||||
? {
|
||||
code: child.uiState.primary_action.code,
|
||||
executionMode: child.uiState.primary_action.executionMode ?? null,
|
||||
targetSurface: child.uiState.primary_action.targetSurface ?? null,
|
||||
targetLifecycleStage: child.uiState.primary_action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null,
|
||||
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -292,20 +313,22 @@ export function useShippingNoticeWorkflow(
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带超时的 AbortController。
|
||||
* 创建当前会话代际的 AbortController。
|
||||
*
|
||||
* 共享 API 请求自行持有 30 秒超时,不能在此再设更短的消费者超时:
|
||||
* 否则底层请求虽仍可成功返回,当前代际会因 signal 已 aborted 而丢弃响应,
|
||||
* 导致首屏永久停留在权威投影骨架。这里仅用于会话切换或组件卸载的真实取消。
|
||||
*/
|
||||
function createRequestController(): AbortController {
|
||||
requestController?.abort();
|
||||
const controller = new AbortController();
|
||||
requestController = controller;
|
||||
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||
controller.signal.addEventListener('abort', () => clearTimeout(timeout), { once: true });
|
||||
return controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅拉取统一 shipping-processing 投影。
|
||||
* 核心逻辑:后端 status_groups 存在时直接使用;仅旧响应缺状态组才由 work_items 合成;
|
||||
* 核心逻辑:只消费后端 status_groups;
|
||||
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据;
|
||||
* 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。
|
||||
*
|
||||
@@ -450,7 +473,7 @@ export function useShippingNoticeWorkflow(
|
||||
|
||||
/**
|
||||
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
|
||||
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块;
|
||||
* 核心逻辑:只回写后端返回的 status_groups;work_items 仅提供最小附件叶子。
|
||||
* 每次回写后更新语义签名,避免下一轮轮询误判为「无变化」。
|
||||
*/
|
||||
function applyMutationProcessingResponse(response: {
|
||||
@@ -458,12 +481,12 @@ export function useShippingNoticeWorkflow(
|
||||
work_items?: unknown[];
|
||||
}): void {
|
||||
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
|
||||
if (workItems.length > 0) {
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
if (nextProjection) {
|
||||
processingWorkItems.value = resolveStableWorkItems(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
processing.value,
|
||||
@@ -476,13 +499,6 @@ export function useShippingNoticeWorkflow(
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (response.processing) {
|
||||
const nextKey = buildProcessingSemanticKey(response.processing);
|
||||
if (nextKey !== lastSemanticKey) {
|
||||
processing.value = response.processing;
|
||||
lastSemanticKey = nextKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -136,7 +136,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('merges sibling Runs from one upload batch into one chat status card', async () => {
|
||||
it('keeps the submitted Run card independent from sibling Runs in the same upload batch', async () => {
|
||||
const first = Object.assign(run({
|
||||
run_no: 'SNER-BATCH-1',
|
||||
conversation_id: 'conv-batch',
|
||||
@@ -191,7 +191,6 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
operation_id: 'op-batch',
|
||||
});
|
||||
api.getRun.mockResolvedValue(first);
|
||||
api.listRuns.mockResolvedValue({ items: [first, second] });
|
||||
const harness = createHarness();
|
||||
|
||||
await harness.runs.startRun('', ['SNI-BATCH-1', 'SNI-BATCH-2'], [], 'upload-batch-1');
|
||||
@@ -199,14 +198,14 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
const cards = harness.messages.value.filter((message) => message.shipping_order_extraction_state);
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.shipping_order_extraction_state?.summary).toMatchObject({
|
||||
totalDocuments: 2,
|
||||
totalDocuments: 1,
|
||||
pendingDocuments: 1,
|
||||
processingDocuments: 1,
|
||||
processingDocuments: 0,
|
||||
});
|
||||
expect(cards[0]?.shipping_order_extraction_state?.documents?.map((item) => item.fileName)).toEqual([
|
||||
'notice-a.pdf',
|
||||
'notice-b.pdf',
|
||||
]);
|
||||
expect(api.listRuns).not.toHaveBeenCalled();
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
@@ -290,25 +289,27 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
api.getRun.mockReturnValueOnce(pending.promise);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-old';
|
||||
await harness.runs.restoreForConversation('conv-old');
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
const oldRestore = harness.runs.restoreForConversation('conv-old');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-OLD', expect.any(AbortSignal));
|
||||
|
||||
harness.conversationId.value = 'conv-new';
|
||||
await expect(harness.runs.restoreForConversation('conv-new')).resolves.toBeUndefined();
|
||||
pending.resolve(run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'completed' }));
|
||||
await Promise.resolve();
|
||||
await oldRestore;
|
||||
expect(harness.runs.getActiveRunNo()).toBe('');
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('processing');
|
||||
expect(harness.messages.value).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('notifies session work items refresh after restoring a terminal run', async () => {
|
||||
api.listRuns.mockResolvedValue({
|
||||
items: [run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' })],
|
||||
});
|
||||
const summary = run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' });
|
||||
const detail = run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [summary] });
|
||||
api.getRun.mockResolvedValue(detail);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-DONE', expect.any(AbortSignal));
|
||||
expect(harness.options.onWorkflowRefresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -348,7 +349,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
const queued = run({ run_no: 'SNER-RETRY', status: 'queued', phase: 'manual_retry_queued', error: null });
|
||||
api.listRuns.mockResolvedValue({ items: [failed] });
|
||||
api.retryRun.mockResolvedValue({ run: queued, reused: false });
|
||||
api.getRun.mockResolvedValue(queued);
|
||||
api.getRun.mockResolvedValueOnce(failed).mockResolvedValue(queued);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
@@ -381,7 +382,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [source] });
|
||||
api.reparseRun.mockResolvedValue({ run: replacement, reused: false });
|
||||
api.getRun.mockResolvedValue(replacement);
|
||||
api.getRun.mockResolvedValueOnce(source).mockResolvedValueOnce(source).mockResolvedValue(replacement);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
@@ -393,6 +394,21 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(harness.messages.value).toHaveLength(2);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('uses a lightweight Run list only to locate the latest Run before loading one detail', async () => {
|
||||
const latest = run({ run_no: 'SNER-LATEST', conversation_id: 'conv-1', status: 'processing' });
|
||||
const older = run({ run_no: 'SNER-OLDER', conversation_id: 'conv-1', status: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [latest, older] });
|
||||
api.getRun.mockResolvedValue(latest);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
expect(api.getRun).toHaveBeenCalledTimes(1);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-LATEST', expect.any(AbortSignal));
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -644,6 +660,7 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
|
||||
const terminal = run({ run_no: 'SNER-SEEN', status: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [terminal] });
|
||||
api.getRun.mockResolvedValue(terminal);
|
||||
api.markSeen.mockResolvedValue({ seen: true });
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
@@ -36,7 +36,6 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
refreshNoticeIntakeStatuses: () => Promise<void>;
|
||||
getOrderExtractionReview: (intakeNos: string[]) => ShippingOrderExtractionReviewAttachment[];
|
||||
clearConsumedNoticeAttachments: () => void;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
onConversationResolved: (conversationId: string) => Promise<void> | void;
|
||||
@@ -54,69 +53,6 @@ const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/**
|
||||
* 将同一上传批次的独立 Run 合成单张聊天状态卡。
|
||||
*
|
||||
* 核心逻辑:Run 仍按 Intake 独立执行、审计和复核;仅把同会话同 upload_batch_id
|
||||
* 的用户态摘要相加,保证一次文件选择在聊天区只出现一个卡片。
|
||||
*/
|
||||
function mergeUploadBatchRuns(primary: ShippingOrderExtractionRun, runs: ShippingOrderExtractionRun[]): ShippingOrderExtractionRun {
|
||||
const batchId = String(primary.upload_batch_id || '').trim();
|
||||
if (!batchId) return primary;
|
||||
const members = runs.filter((item) => (
|
||||
item.conversation_id === primary.conversation_id
|
||||
&& String(item.upload_batch_id || '').trim() === batchId
|
||||
));
|
||||
if (members.length <= 1) return primary;
|
||||
const activeMembers = members.filter((item) => ACTIVE_RUN_STATUSES.has(item.status));
|
||||
const status = activeMembers.some((item) => item.status === 'processing')
|
||||
? 'processing'
|
||||
: activeMembers.length > 0
|
||||
? 'queued'
|
||||
: members.some((item) => item.status === 'failed')
|
||||
? 'failed'
|
||||
: members.some((item) => item.status === 'review_required')
|
||||
? 'review_required'
|
||||
: members.some((item) => item.status === 'partially_completed')
|
||||
? 'partially_completed'
|
||||
: 'completed';
|
||||
const failedParseMembers = members.filter((item) => (
|
||||
item.documents || []
|
||||
).some((document) => document.reason_code === 'intake_parse_failed' || String(document.user_visible_stage || '') === 'parse_failed'));
|
||||
const effectiveStatus = failedParseMembers.length > 0 && activeMembers.length === 0 ? 'failed' : status;
|
||||
const summaryKeys = [
|
||||
'total_documents', 'pending_documents', 'processing_documents', 'completed_documents',
|
||||
'review_required_documents', 'failed_documents', 'cancelled_documents', 'candidate_count',
|
||||
'opened_existing_documents',
|
||||
] as const;
|
||||
const summary = summaryKeys.reduce((result, key) => {
|
||||
result[key] = members.reduce((total, item) => total + Number(item.summary?.[key] || 0), 0);
|
||||
return result;
|
||||
}, {} as ShippingOrderExtractionRun['summary']);
|
||||
const documentIds = new Set<number>();
|
||||
const documents = members.flatMap((item) => item.documents || []).filter((item) => {
|
||||
const id = Number(item.document_id || 0);
|
||||
if (id && documentIds.has(id)) return false;
|
||||
if (id) documentIds.add(id);
|
||||
return true;
|
||||
});
|
||||
const mostRecent = [...members].sort((left, right) => String(right.last_activity_at || '').localeCompare(String(left.last_activity_at || '')))[0] || primary;
|
||||
return {
|
||||
...primary,
|
||||
status: effectiveStatus,
|
||||
phase: effectiveStatus,
|
||||
intake_nos: [...new Set(members.flatMap((item) => item.intake_nos || []))],
|
||||
summary,
|
||||
documents,
|
||||
current_activity: mostRecent.current_activity || primary.current_activity,
|
||||
available_actions: [...new Set(members.flatMap((item) => item.available_actions || []))],
|
||||
handling_items: members.flatMap((item) => item.handling_items || []),
|
||||
health_tips: members.flatMap((item) => item.health_tips || []),
|
||||
progress_version: Math.max(...members.map((item) => Number(item.progress_version || 0))),
|
||||
last_activity_at: mostRecent.last_activity_at || primary.last_activity_at,
|
||||
};
|
||||
}
|
||||
|
||||
/** 按页面可见性选择轮询间隔;后台放慢,失败退避另算。 */
|
||||
function resolvePollIntervalMs(failureCount = 0): number {
|
||||
if (failureCount > 0) {
|
||||
@@ -296,21 +232,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return composerContextId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取同批次兄弟 Run 后生成聊天展示快照。
|
||||
*
|
||||
* 仅在服务端已返回 upload_batch_id 时查询;旧 Run 或重识别 Run 保持原有单卡逻辑。
|
||||
*/
|
||||
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => {
|
||||
if (!String(run.upload_batch_id || '').trim()) return run;
|
||||
try {
|
||||
const response = await listWorkspaceShippingOrderExtractionRuns(run.conversation_id, 100);
|
||||
return mergeUploadBatchRuns(run, response.items || []);
|
||||
} catch {
|
||||
// 聚合读失败时宁可显示本 Run 的真实状态,也不阻断轮询或误改业务状态。
|
||||
return run;
|
||||
}
|
||||
};
|
||||
/** Run 卡只消费该 Run 的完整权威详情;批次聚合由独立处理投影负责。 */
|
||||
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => run;
|
||||
|
||||
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
|
||||
const stopPolling = () => {
|
||||
@@ -452,14 +375,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
reviewAttachments = options.getOrderExtractionReview(run.intake_nos);
|
||||
}
|
||||
options.clearConsumedNoticeAttachments();
|
||||
try {
|
||||
if (!(await options.syncShippingConversationWorkspace({ preferLatest: true }))) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
await options.syncShippingConversationWorkspace({ preferLatest: true });
|
||||
}
|
||||
} catch {
|
||||
// Run 状态卡已持久化;工作台可由页面下一次刷新继续恢复。
|
||||
}
|
||||
await Promise.allSettled([options.loadHistory()]);
|
||||
options.onWorkflowRefresh?.();
|
||||
return reviewAttachments;
|
||||
@@ -768,8 +683,9 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
const latest = items[0];
|
||||
if (!latest) return;
|
||||
activeRunNo = latest.run_no;
|
||||
const displayRun = mergeUploadBatchRuns(latest, items);
|
||||
const displayRun = await getWorkspaceShippingOrderExtractionRun(latest.run_no, request.signal);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
activeRunNo = displayRun.run_no;
|
||||
const reviewAttachments = ACTIVE_RUN_STATUSES.has(displayRun.status)
|
||||
? undefined
|
||||
: await refreshTerminalFacts(displayRun);
|
||||
|
||||
@@ -33,7 +33,7 @@ export type ShippingProcessingWorkItemTypeArg = 'order_intake' | 'order_task';
|
||||
*
|
||||
* @param workItemType - order_intake | order_task
|
||||
* @param workItemNo - Intake 编号或 OT 编号(MaybeRef)
|
||||
* @param options.enabled - 是否启用;options.pollMs - 轮询间隔;
|
||||
* @param options.enabled - 是否启用;options.pollMs - 轮询间隔;options.continuousPolling - 是否由本 composable 持续轮询;
|
||||
* options.monotonicProgressVersion - 仅工作台:旧 progress_version 不覆盖本地
|
||||
* @returns projection / loading / error / refresh / stop
|
||||
*/
|
||||
@@ -43,6 +43,8 @@ export function useShippingProcessingWorkItem(
|
||||
options: {
|
||||
enabled?: MaybeRefOrGetter<boolean>;
|
||||
pollMs?: number;
|
||||
/** false 时仅由调用方显式 refresh;用于已有页面级协调轮询的工作台。 */
|
||||
continuousPolling?: boolean;
|
||||
/** 仅订单处理工作台开启;任务中心保持默认 false。 */
|
||||
monotonicProgressVersion?: boolean;
|
||||
} = {},
|
||||
@@ -61,6 +63,7 @@ export function useShippingProcessingWorkItem(
|
||||
let stopped = false;
|
||||
let refreshInFlight: { no: string; promise: Promise<void> } | null = null;
|
||||
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
|
||||
const continuousPolling = options.continuousPolling !== false;
|
||||
const monotonic = Boolean(options.monotonicProgressVersion);
|
||||
|
||||
/**
|
||||
@@ -112,7 +115,7 @@ export function useShippingProcessingWorkItem(
|
||||
error.value = null;
|
||||
clearTimer();
|
||||
const next = projection.value;
|
||||
if (next && !TERMINAL_STATUSES.has(next.status) && !stopped) {
|
||||
if (continuousPolling && next && !TERMINAL_STATUSES.has(next.status) && !stopped) {
|
||||
timer = window.setTimeout(() => {
|
||||
void refresh();
|
||||
}, pollMs);
|
||||
@@ -128,7 +131,7 @@ export function useShippingProcessingWorkItem(
|
||||
}
|
||||
error.value = err instanceof BusinessError ? err.message : 'network_recoverable';
|
||||
clearTimer();
|
||||
if (!stopped) {
|
||||
if (continuousPolling && !stopped) {
|
||||
timer = window.setTimeout(() => {
|
||||
void refresh();
|
||||
}, pollMs);
|
||||
|
||||
@@ -9,7 +9,7 @@ export type ChatTurnInputType = 'text' | 'action' | 'form_submit' | 'upload_foll
|
||||
|
||||
/**
|
||||
* 会话级业务锚点。
|
||||
* 货代双工作台阶段 2 优先键:conversation_id / run_no / candidate_no / task_no / batch_no;
|
||||
* 货代对话优先键:conversation_id / run_no / candidate_no / task_no;
|
||||
* 其他 Agent 可使用各自键名。禁止用本结构承载业务状态机推导结果。
|
||||
*/
|
||||
export type ChatTurnRefs = Record<string, string>;
|
||||
@@ -20,7 +20,6 @@ export const SHIPPING_CHAT_TURN_REF_KEYS = [
|
||||
'run_no',
|
||||
'candidate_no',
|
||||
'task_no',
|
||||
'batch_no',
|
||||
] as const;
|
||||
|
||||
export interface StartChatTurnOptions {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* composerContextId;与 shipping.api.types 提交 DTO 对齐。
|
||||
*/
|
||||
import type { LeaveAgentOption } from './leave.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from './shipping.api.types';
|
||||
import type { ShippingTaskUiState } from './shipping.api.types';
|
||||
import type { ShippingNoticeCandidate } from './shipping.types';
|
||||
|
||||
export type { LeaveAgentOption };
|
||||
@@ -207,9 +207,7 @@ export interface ShippingOrderExtractionReviewAttachment {
|
||||
/** 历史消息中用于恢复发货工作台焦点的最小持久化载荷。 */
|
||||
export interface ShippingMessageRecoveryPayload {
|
||||
task_no?: string;
|
||||
batch_no?: string;
|
||||
shipping_ui_state?: ShippingTaskUiState;
|
||||
shipping_batch_ui_state?: ShippingBatchUiState;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,28 @@ export type ShippingProcessingActionIntent =
|
||||
| 'open_inventory_match_review'
|
||||
| 'open_shortage_review'
|
||||
| 'upload_inventory_file'
|
||||
| 'retry'
|
||||
| 'reload_inventory_result'
|
||||
| 'retry_inventory_preparation'
|
||||
| 'retry_inventory_matching'
|
||||
| 'retry_parse'
|
||||
| 'retry_failed_documents'
|
||||
| 'retry_failed_attachments'
|
||||
| 'retry_freight_upload_rpa'
|
||||
| 'retry_order_extraction'
|
||||
| 'retry_layout_parsing'
|
||||
| 'rematerialize_document'
|
||||
| 'reroute_document_profile'
|
||||
| 'revalidate_reservation'
|
||||
| 'retry_customer_resolution'
|
||||
| 'retry_duplicate_detection'
|
||||
| 'retry_with_latest_rules'
|
||||
| 'recheck_freeze_readiness'
|
||||
| 'retry_task_creation'
|
||||
| 'retry_inventory_field_mapping'
|
||||
| 'recheck_inventory_sufficiency'
|
||||
| 'recheck_excel_readiness'
|
||||
| 'retry_stp_auto_create'
|
||||
| 'reparse'
|
||||
| 'reparse_batch'
|
||||
| 'refresh'
|
||||
| 'regenerate_excel'
|
||||
@@ -163,7 +184,7 @@ export interface ShippingProcessingPrimaryAction {
|
||||
}
|
||||
|
||||
/** 订单生命周期工作台的后端目标阶段。 */
|
||||
export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
|
||||
/** 文件级生命周期入口;状态、目标均由后端裁决。 */
|
||||
export interface ShippingProcessingLifecycleEntry {
|
||||
@@ -354,10 +375,7 @@ export interface ShippingProcessingProjection {
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
/** 唯一主入口按钮建议:{code, i18nKey, parameters};前端只渲染不新建动作码。 */
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
/**
|
||||
* 单项后端展示裁决;存在时状态、阶段、原因和动作必须只消费此对象。
|
||||
* primaryAction / availableActions 仅保留给尚未升级该契约的旧服务端响应。
|
||||
*/
|
||||
/** 单项后端展示裁决;状态、阶段、原因和动作必须只消费此对象。 */
|
||||
uiState?: ConversationProcessingUiState;
|
||||
/** 文件关联的正式 Gate 用户摘要;仅用于执行后端已裁决的 primary_action。 */
|
||||
processGate?: ShippingProcessGateUserSummary | null;
|
||||
@@ -369,10 +387,6 @@ export interface ShippingProcessingProjection {
|
||||
aggregateSummary?: ConversationProcessingUserTask['aggregateSummary'];
|
||||
/** EML Intake 聚合卡的真实子附件工作项;仅展示,不作为写操作目标。 */
|
||||
aggregateChildren?: ShippingProcessingProjection[];
|
||||
/** 旧 status 备份(T8 apply_user_projection_fields.legacy_status);调试用。 */
|
||||
legacyStatus?: string | null;
|
||||
/** 旧 stage 备份(T8 apply_user_projection_fields.legacy_stage);调试用。 */
|
||||
legacyStage?: string | null;
|
||||
/** 正式 OT 是否已挂接真实 ShippingNotice;T1 判定:order_task + shipping_notice_id 非空 + shipping_notice_no 非空。 */
|
||||
hasFormalOt?: boolean;
|
||||
/**
|
||||
@@ -606,8 +620,6 @@ export interface ConversationProcessingUserTask {
|
||||
facts?: ShippingProcessingFacts;
|
||||
/** EML Intake 的用户可见全局分组;前端只消费,不从附件状态自行推导。 */
|
||||
userGroup?: ShippingProcessingProjection['userGroup'];
|
||||
legacyStatus?: string | null;
|
||||
legacyStage?: string | null;
|
||||
/** 同一 EML Intake 聚合后的子任务状态,仅供展示,不作为写操作事实。 */
|
||||
aggregateSummary?: {
|
||||
intakeNo: string;
|
||||
@@ -664,11 +676,17 @@ export interface ConversationProcessingProjection {
|
||||
summary: ConversationProcessingSummary;
|
||||
focused_task_no?: string | null;
|
||||
recent_task_no?: string | null;
|
||||
needs_action: ConversationProcessingUserTask[];
|
||||
processing: ConversationProcessingUserTask[];
|
||||
/** 成功完成待查看;与 needs_action 异常态分离 */
|
||||
/**
|
||||
* @deprecated 仅用于编译期迁移旧夹具;生产响应和生产读取均不得使用。
|
||||
* 新调用必须只消费 status_groups。
|
||||
*/
|
||||
needs_action?: ConversationProcessingUserTask[];
|
||||
/** @deprecated 仅用于编译期迁移旧夹具;生产响应和生产读取均不得使用。 */
|
||||
processing?: ConversationProcessingUserTask[];
|
||||
/** @deprecated 仅用于编译期迁移旧夹具;生产响应和生产读取均不得使用。 */
|
||||
completed?: ConversationProcessingUserTask[];
|
||||
history: ConversationProcessingUserTask[];
|
||||
/** @deprecated 仅用于编译期迁移旧夹具;生产响应和生产读取均不得使用。 */
|
||||
history?: ConversationProcessingUserTask[];
|
||||
/** 按 EML Intake 唯一归组后的六类用户状态;同一 EML 只允许出现一次。 */
|
||||
status_groups?: {
|
||||
failed: ConversationProcessingUserTask[];
|
||||
@@ -678,12 +696,11 @@ export interface ConversationProcessingProjection {
|
||||
cancelled: ConversationProcessingUserTask[];
|
||||
archived: ConversationProcessingUserTask[];
|
||||
};
|
||||
/** 会话批次主进度;后端已将技术阶段折叠为四个业务节点。 */
|
||||
four_stage_nodes?: Array<{
|
||||
code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
/** 会话批次主进度;后端已将技术阶段折叠为五个业务节点。 */
|
||||
lifecycle_nodes?: Array<{
|
||||
code: LifecycleWorkbenchStage;
|
||||
label_key: string;
|
||||
status: 'passed' | 'running' | 'blocked' | 'pending';
|
||||
/** 批次阶段摘要由后端按完整叶子工作项裁决,禁止页面从筛选结果反算。 */
|
||||
summary?: {
|
||||
total: number;
|
||||
completed: number;
|
||||
@@ -693,7 +710,7 @@ export interface ConversationProcessingProjection {
|
||||
blocking_reason?: ShippingProcessingBlockingReason | null;
|
||||
};
|
||||
}>;
|
||||
/** 后端无法归类到四阶段的业务文件数量;页面只提示,不擅自归类。 */
|
||||
/** 后端无法归类到五阶段的业务文件数量;页面只提示,不擅自归类。 */
|
||||
unclassified_summary?: { count: number };
|
||||
/** 批次级用户态:状态、问题与可操作动作必须来自同一次后端裁决。 */
|
||||
ui_state?: ConversationProcessingUiState;
|
||||
@@ -711,8 +728,8 @@ export interface ConversationProcessingProjection {
|
||||
export interface ConversationProcessingUiState {
|
||||
status: ShippingUserProcessingStatus;
|
||||
stage: string;
|
||||
/** 后端从技术节点裁决的四阶段业务编码,批次中心与工作台共同消费。 */
|
||||
lifecycleStage?: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
/** 后端从技术节点裁决的五阶段业务编码,批次中心与工作台共同消费。 */
|
||||
lifecycleStage?: LifecycleWorkbenchStage;
|
||||
lifecycleEntries?: ShippingProcessingLifecycleEntry[];
|
||||
blocking_reason: ShippingProcessingBlockingReason | null;
|
||||
primary_action: ShippingProcessingPrimaryAction | null;
|
||||
@@ -808,10 +825,22 @@ export interface ShippingInventorySnapshot {
|
||||
export interface ShippingTaskSummary {
|
||||
id: number;
|
||||
task_no: string;
|
||||
shipping_case_id?: number | null;
|
||||
case_no?: string | null;
|
||||
business_no?: string | null;
|
||||
batch_no?: string | null;
|
||||
/** 通知单列表只读行摘要;库存数据由后端当前匹配事实投影,前端不得自行计算。 */
|
||||
notice_line_summary?: Array<{
|
||||
line_no?: string | number | null;
|
||||
part_number?: string | null;
|
||||
customer_part_number?: string | null;
|
||||
reservation_id?: string | null;
|
||||
shipment_qty?: string | null;
|
||||
available_qty?: string | null;
|
||||
shortage_qty?: string | null;
|
||||
inventory_status?: string | null;
|
||||
}>;
|
||||
artifact_summary?: {
|
||||
export_file_name?: string | null;
|
||||
export_file_path?: string | null;
|
||||
} | null;
|
||||
source_type: string;
|
||||
source_file_name?: string | null;
|
||||
source_file_type?: string | null;
|
||||
@@ -1038,6 +1067,7 @@ export type ShippingProcessGateActionCode =
|
||||
| 'retry_with_latest_rules'
|
||||
| 'recheck_freeze_readiness'
|
||||
| 'retry_task_creation'
|
||||
| 'reload_inventory_result'
|
||||
| 'retry_inventory_preparation'
|
||||
| 'poll_inventory_preparation'
|
||||
| 'upload_inventory_file'
|
||||
@@ -1414,7 +1444,6 @@ export type ShippingActionKind = 'forward' | 'recovery' | 'view' | 'terminate';
|
||||
|
||||
export interface ShippingTaskUiState {
|
||||
task_no: string;
|
||||
batch_no?: string | null;
|
||||
stage?: {
|
||||
code: ShippingBusinessStage | string;
|
||||
label: string;
|
||||
@@ -1445,7 +1474,7 @@ export interface ShippingTaskUiState {
|
||||
primary?: ShippingUnifiedAction | null;
|
||||
secondary?: ShippingUnifiedAction[];
|
||||
};
|
||||
/** 四阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */
|
||||
/** 五阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */
|
||||
stage_context?: {
|
||||
preparation?: {
|
||||
status?: 'processing' | 'blocked' | 'ready' | string;
|
||||
@@ -1483,6 +1512,14 @@ export interface ShippingTaskUiState {
|
||||
} | null;
|
||||
upload?: {
|
||||
outcome?: 'not_started' | 'running' | 'awaiting_manual' | 'succeeded' | 'failed' | 'unknown' | string;
|
||||
/** 仅 upload_complete 工作面读取的、后端验证过的成功上传事实。 */
|
||||
succeeded_attempt?: {
|
||||
id?: number | null;
|
||||
status?: string | null;
|
||||
mode?: string | null;
|
||||
freight_ref_no?: string | null;
|
||||
finished_at?: string | null;
|
||||
} | null;
|
||||
latest_attempt?: {
|
||||
id?: number | null;
|
||||
status?: string | null;
|
||||
@@ -1567,66 +1604,35 @@ export interface ShippingUnifiedAction {
|
||||
|
||||
/**
|
||||
* `shipping_ui_state` SSE 与历史回放共用的恢复契约。
|
||||
* 核心逻辑:任务锚点 `task_no` 是 open_existing 场景恢复聊天工作台的最小必需字段;
|
||||
* 若后端能解析到所属批次或完整批次快照,应继续补齐 `batch_no`、`batch_ui_state` 与 `ui_state`。
|
||||
* 核心逻辑:任务锚点 `task_no` 是恢复聊天工作台的最小必需字段,`ui_state` 是其只读事实快照。
|
||||
*/
|
||||
export interface ShippingUiStateEventPayload {
|
||||
event?: 'shipping_ui_state';
|
||||
conversation_id?: string;
|
||||
task_no?: string | null;
|
||||
batch_no?: string | null;
|
||||
ui_state?: ShippingTaskUiState;
|
||||
batch_ui_state?: ShippingBatchUiState;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export interface ShippingBatchSummary {
|
||||
id: number;
|
||||
batch_no: string;
|
||||
conversation_id?: string | null;
|
||||
current_focus_task_no?: string | null;
|
||||
file_count?: number | null;
|
||||
process_summary?: Record<string, unknown> & {
|
||||
total?: number;
|
||||
completed?: number;
|
||||
failed?: number;
|
||||
running?: number;
|
||||
pending?: number;
|
||||
needs_human?: number;
|
||||
current_index?: number;
|
||||
current_task_no?: string | null;
|
||||
} | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
/** 订单工作台货代上传区的 Notice 聚合行;一行对应一个 business_no 与唯一 Excel。 */
|
||||
export interface ShippingFreightNoticeGroup {
|
||||
business_no: string;
|
||||
po_number: string | null;
|
||||
upload_status?: string | null;
|
||||
export_file_name?: string | null;
|
||||
available_actions?: string[];
|
||||
lines: Array<{
|
||||
line_no?: string | number | null;
|
||||
part_number?: string | null;
|
||||
reservation_id?: string | null;
|
||||
shipment_qty?: string | number | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ShippingBatchUiState extends ShippingBatchSummary {
|
||||
/** 批次仅作为会话上传集合摘要,非履约写操作面 */
|
||||
role?: 'upload_session_summary' | string;
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
focus_task_ui_state?: ShippingTaskUiState | null;
|
||||
tasks: ShippingTaskSummary[];
|
||||
}
|
||||
|
||||
export interface ShippingConversationWorkspaceSummary {
|
||||
batch_count: number;
|
||||
total: number;
|
||||
completed: number;
|
||||
running: number;
|
||||
failed: number;
|
||||
needs_human: number;
|
||||
pending: number;
|
||||
}
|
||||
|
||||
export interface ShippingConversationBatch extends ShippingBatchSummary {
|
||||
tasks: ShippingTaskSummary[];
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
}
|
||||
|
||||
export interface ShippingConversationWorkspace {
|
||||
conversation_id: string;
|
||||
summary: ShippingConversationWorkspaceSummary;
|
||||
batches: ShippingConversationBatch[];
|
||||
export interface ShippingFreightNoticeGroupsResponse {
|
||||
po_number: string | null;
|
||||
items: ShippingFreightNoticeGroup[];
|
||||
reason?: 'po_missing' | 'no_business_notice' | string | null;
|
||||
}
|
||||
|
||||
export interface ShippingInventoryUploadResponse {
|
||||
@@ -1663,16 +1669,10 @@ export interface ShippingNoticeUploadResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
task_id?: string;
|
||||
batch_no?: string;
|
||||
checkpoint?: string;
|
||||
idempotent_replay?: boolean;
|
||||
file_summary?: ShippingNoticeFileSummary;
|
||||
data?: Record<string, unknown> & {
|
||||
batch?: ShippingBatchSummary;
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
tasks?: Array<Record<string, unknown>>;
|
||||
orchestrator_started?: boolean;
|
||||
};
|
||||
data?: Record<string, unknown> & { orchestrator_started?: boolean };
|
||||
human_options?: string[];
|
||||
}
|
||||
|
||||
@@ -1847,6 +1847,36 @@ export interface ShippingOrderExtractionRunSummary {
|
||||
opened_existing_documents?: number;
|
||||
}
|
||||
|
||||
/** 复核工作台直接消费的 Run 级五阶段进度;字段由后端 Projection 裁决。 */
|
||||
export interface ShippingOrderExtractionLifecycleProgress {
|
||||
lifecycle_stage: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete' | string;
|
||||
lifecycle_status: 'running' | 'waiting' | 'failed' | 'cancelled' | 'completed' | string;
|
||||
current_step_code?: string | null;
|
||||
current_step_i18n_key?: string | null;
|
||||
completed_step_codes: string[];
|
||||
last_activity_at?: string | null;
|
||||
health_status: 'normal' | 'attention' | 'failed' | string;
|
||||
blocking_reason_i18n_key?: string | null;
|
||||
primary_action?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话恢复和任务中心列表的固定成本摘要;完整文档、Case、Gate 投影必须按 Run 编号单独读取。
|
||||
*/
|
||||
export interface ShippingOrderExtractionRunListItem {
|
||||
run_no: string;
|
||||
user_task_no?: string | null;
|
||||
agent_id: number;
|
||||
conversation_id: string;
|
||||
status: ShippingOrderExtractionRunStatus;
|
||||
phase: string;
|
||||
summary: ShippingOrderExtractionRunSummary;
|
||||
progress_version?: number | null;
|
||||
last_activity_at?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivity {
|
||||
unit_id: number;
|
||||
file_name?: string | null;
|
||||
@@ -1883,6 +1913,7 @@ export interface ShippingOrderExtractionDocumentResult {
|
||||
queue_position?: number | null;
|
||||
elapsed_seconds?: number | null;
|
||||
health_tips?: ShippingOrderExtractionHealthTip[];
|
||||
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
|
||||
cancellation?: ShippingOrderExtractionCancellation | null;
|
||||
activity_version?: number | null;
|
||||
selection_batch?: number | null;
|
||||
@@ -1994,11 +2025,12 @@ export interface ShippingOrderExtractionRun {
|
||||
primary_notice?: string | null;
|
||||
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
|
||||
health_tips?: ShippingOrderExtractionHealthTip[];
|
||||
/** Run 解析中或尚无 Case 时的后端用户态进度。 */
|
||||
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
|
||||
cancellation?: ShippingOrderExtractionCancellation | null;
|
||||
progress_version?: number | null;
|
||||
last_activity_at?: string | null;
|
||||
result?: {
|
||||
batch_no?: string | null;
|
||||
created_count?: number;
|
||||
opened_existing_count?: number;
|
||||
pending_count?: number;
|
||||
@@ -2255,6 +2287,8 @@ export interface ShippingOrderReviewCaseSummary {
|
||||
draft_version?: number | null;
|
||||
issue_count: number;
|
||||
available_actions: string[];
|
||||
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
|
||||
intake_no?: string | null;
|
||||
source_run_no?: string | null;
|
||||
}
|
||||
|
||||
@@ -2263,6 +2297,8 @@ export interface ShippingOrderReviewRun {
|
||||
superseded_by_run_no?: string | null;
|
||||
summary: Record<string, number>;
|
||||
items: ShippingOrderReviewCaseSummary[];
|
||||
/** Run 解析中或尚无 Case 时的后端用户态进度。 */
|
||||
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewQueue {
|
||||
@@ -2435,7 +2471,8 @@ export interface ShippingOrderReviewBuildEligibilityIssue {
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewBuildEligibility {
|
||||
can_build: boolean;
|
||||
/** 未执行校验时为 null;只有 validated/needs_review 才返回布尔结论。 */
|
||||
can_build: boolean | null;
|
||||
can_auto_create?: boolean;
|
||||
status: string;
|
||||
gates?: Record<string, boolean>;
|
||||
@@ -2497,12 +2534,8 @@ export interface ShippingOrderReviewFieldConflictOption {
|
||||
evidence_role?: 'primary_pdf' | 'auxiliary' | 'context' | string | null;
|
||||
/** PDF_PRIORITY_EVIDENCE_RANKS 档位名。 */
|
||||
evidence_rank?: string | null;
|
||||
/** Vendor Comments 三来源专属:字段来源种类(header_region / table_column / vendor_comments)。 */
|
||||
vc_source_kind?: string | null;
|
||||
/** Vendor Comments 三来源专属:来源种类的本地化展示标签。 */
|
||||
vc_source_kind_label?: string | null;
|
||||
/** Vendor Comments 三来源专属:vc:<doc>:p<N>:region:<rid> 证据引用,可跳转证据查看器定位对应区域。 */
|
||||
evidence_ref?: string | null;
|
||||
/** 结构化文档证据或兼容字符串,可跳转证据查看器定位对应区域。 */
|
||||
evidence_ref?: Record<string, unknown> | string | null;
|
||||
}
|
||||
|
||||
/** 建单前 Candidate 字段冲突投影(复核工作台集中裁决区)。 */
|
||||
@@ -2517,18 +2550,8 @@ export interface ShippingOrderReviewFieldConflict {
|
||||
reason: string;
|
||||
options: ShippingOrderReviewFieldConflictOption[];
|
||||
observation_ids?: string[];
|
||||
/** Vendor Comments 三来源专属:true 表示该冲突来自 VC 三来源合并,conflict_key 以 vc: 开头。 */
|
||||
vc_kind?: boolean | null;
|
||||
/** Vendor Comments 三来源专属:细因码(vc_source_conflict_unresolved / vc_source_format_invalid / vc_source_region_unbound)。 */
|
||||
vc_reason?: string | null;
|
||||
/** Vendor Comments 三来源专属:冲突组稳定键(scope:field_code:line_no),裁决时写回 merged_candidates 使用。 */
|
||||
vc_conflict_group_key?: string | null;
|
||||
/** Vendor Comments 三来源专属:只读诊断,展示 resolution / decision_status / format_valid。 */
|
||||
vc_detail?: {
|
||||
resolution?: string | null;
|
||||
decision_status?: string | null;
|
||||
format_valid?: boolean | null;
|
||||
} | null;
|
||||
/** 后端给出的下一步恢复动作;例如 reparse_current_pdf。 */
|
||||
recovery_action?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewCase {
|
||||
@@ -2632,6 +2655,8 @@ export interface ShippingOrderReviewCase {
|
||||
build_eligibility?: ShippingOrderReviewBuildEligibility;
|
||||
} | null;
|
||||
available_actions: string[];
|
||||
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
|
||||
intake_no?: string | null;
|
||||
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
|
||||
formal_editable_field_ids?: string[];
|
||||
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
|
||||
@@ -2936,6 +2961,14 @@ export interface ShippingOrderReviewProfileMatchCandidate {
|
||||
hard_match?: boolean | null;
|
||||
reason_codes?: string[];
|
||||
missing_required_anchor_ids?: string[];
|
||||
/** 管理员技术详情:共同 matcher 已确认的受限平移,不含正文或完整坐标。 */
|
||||
coordinate_transform?: {
|
||||
status: 'applied' | 'unavailable' | 'rejected' | string;
|
||||
translate_x?: number | null;
|
||||
translate_y?: number | null;
|
||||
anchor_ids?: string[];
|
||||
reason_codes?: string[];
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** 建单前文档模板匹配只读投影。 */
|
||||
@@ -3044,6 +3077,7 @@ export interface ShippingOrderReviewLineFulfillmentDecision {
|
||||
part_number?: string | null;
|
||||
task_id?: number | null;
|
||||
wave_no?: number | null;
|
||||
notice_no?: string | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user