feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程

清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
hugo committed 2026-08-20 20:23:10 +08:00
1 parent 260465b72d
commit 1b6483a4ea
466 files changed
+32115 -33796

No files matched your search

@@ -299,7 +299,6 @@ export function normalizeLifecycleStatus(
const HUMAN_ACTION_CODES = new Set([
'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate',
'open_order_review', 'open_order_processing', 'enter_manual_review',
'open_inventory_source_review', 'confirm_inventory_source',
'open_inventory_match_review', 'rematch', 'match_inventory',
'open_shortage_review', 'upload_inventory_file', 'open_manual_upload',
'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents',
@@ -1318,7 +1317,6 @@ export function projectConversationProcessingFromWorkItems(
primaryAction: userPrimaryAction,
facts: userFacts,
userGroup: item.userGroup ?? null,
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
userCurrentGateCode: item.userCurrentGateCode ?? null,
legacyStatus: item.legacyStatus ?? null,
legacyStage: item.legacyStage ?? null,
@@ -83,7 +83,7 @@ describe('normalizeShippingProcessingProjection', () => {
expect(normalized!.sourceSummary.documentId).toBe(17);
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
expect(normalized!.availableActions).toEqual(['open_review']);
expect(normalized!.uiState).toEqual({
expect(normalized!.uiState).toMatchObject({
status: 'waiting_human',
stage: 'order_review',
blocking_reason: { code: 'pdf_preferred_critical_conflict', i18nKey: null, details: {} },
@@ -291,7 +291,7 @@ function normalizeAggregateSummary(
/**
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
* 注意:failed_sources 会进一步透传到 exhausted_sources 分开(二者互斥;仅 max_attempts 耗尽的源进 exhausted)。
* 注意:只投影当前准备结果;失败后由具体 Gate 动作决定下一步。
*/
function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparationSummary | null {
if (!raw || typeof raw !== 'object') return null;
@@ -308,7 +308,6 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
const preparedSources = toStrArr(item.prepared_sources ?? item.preparedSources);
const pendingSources = toStrArr(item.pending_sources ?? item.pendingSources);
const failedSources = toStrArr(item.failed_sources ?? item.failedSources);
const exhaustedSources = toStrArr(item.exhausted_sources ?? item.exhaustedSources);
const activeAttemptCount = Number(item.active_attempt_count ?? item.activeAttemptCount ?? 0) || 0;
const gateAttemptActive = Boolean(item.gate_attempt_active ?? item.gateAttemptActive ?? false);
const latestRaw = (item.latest_attempts ?? item.latestAttempts) as Record<string, unknown> | undefined;
@@ -348,7 +347,6 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
preparedSources,
pendingSources,
failedSources,
exhaustedSources,
activeAttemptCount,
gateAttemptActive,
latestAttempts: Object.keys(latestAttempts).length ? latestAttempts : undefined,
@@ -424,14 +422,12 @@ export function normalizeShippingProcessingProjection(
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
},
childOrderTasks: children,
// [T9 用户态 Projection 7 字段] 优先读后端 user_* / blocking_reason / retryable / primary_action / facts;
// [T9 用户态 Projection 6 字段] 优先读后端 user_* / blocking_reason / primary_action / facts;
// 缺省为 null(旧后端不会下发,旧前端不读取,完全兼容)。
userStatus: readNullableString(item, 'user_status', 'userStatus') as ShippingProcessingProjection['userStatus'],
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
retryable:
(item.retryable as boolean | undefined) == null ? false : Boolean(item.retryable),
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
uiState: normalizeProcessingUiState(item.ui_state ?? item.uiState),
facts: normalizeFacts(item.facts),
@@ -8,6 +8,7 @@ import {
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
workspaceShippingExportUrl,
workspaceShippingInventoryFileUrl,
workspaceShippingLineInventoryFileUrl,
} from '@/features/chat/api/shipping.api';
import { getAuthHeaders } from '@/shared/utils/auth';
@@ -25,6 +26,17 @@ export async function downloadWorkspaceShippingInventoryFile(taskId: string): Pr
await downloadWorkspaceShippingFile(workspaceShippingInventoryFileUrl(taskId), `${taskId}-inventory.xlsx`);
}
/** 下载某订单行实际匹配的库存快照;后端复核该文件号是否为当前行事实。 */
export async function downloadWorkspaceShippingLineInventoryFile(
taskId: string,
inventoryFileNo: string,
): Promise<void> {
await downloadWorkspaceShippingFile(
workspaceShippingLineInventoryFileUrl(taskId, inventoryFileNo),
`${inventoryFileNo}.xlsx`,
);
}
async function downloadWorkspaceShippingFile(url: string, fallbackName: string): Promise<void> {
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) {
@@ -4,7 +4,6 @@
* 依赖:shippingMenu.resolveShippingNumericChoice、types/shipping.types。
* 逻辑:useChatShippingSendHandler 调用;覆盖手工上传、库存上传、Excel 生成/下载与切票。
*/
import { resolveShippingNumericChoice } from './shippingMenu';
import type { ShippingMenuAction } from '../types/shipping.types';
export interface ShippingTaskSwitchIntent {
@@ -27,20 +26,6 @@ export function isShippingManualUploadIntent(text: string): boolean {
].some((pattern) => pattern.test(normalized));
}
export function isShippingInventoryUploadIntent(text: string, assistantContext: string): boolean {
const normalized = text.trim();
if (!normalized) return false;
const choice = resolveShippingNumericChoice(normalized, assistantContext);
if (choice === 'upload') return true;
return [
/^上传库存$/,
/上传库存文件/,
/手工上传/,
/选择库存/,
/upload.*inventory/i,
].some((pattern) => pattern.test(normalized));
}
export function isShippingGenerateExcelIntent(text: string): boolean {
const normalized = text.trim();
if (!normalized) return false;
@@ -29,7 +29,6 @@ export function classifyShippingMenuLine(desc: string): ShippingMenuAction | nul
const normalized = String(desc || '').trim();
if (!normalized) return null;
if (/已确认/.test(normalized)) return null;
if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload';
if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa';
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
if (/驳回|取消|reject/i.test(desc)) return 'reject';
@@ -1,24 +1,21 @@
/**
* features/chat/shipping/shippingTurnActions.spec.ts
* 用途:验证决策/冻结等 Chat Turn 映射(不含已下线的 create_batch)。
* 用途:验证聊天仅构造仍允许的非履约 Chat Turn。
*/
import { describe, expect, it } from 'vitest';
import { resolveShippingChatTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('maps freeze_order only with the version shown to the user', () => {
// 关键断言:缺版本不得构造 freeze Turn,避免乐观锁盲写。
it('does not map legacy fulfillment writes to Chat Turns', () => {
// 关键断言:冻结、库存源、匹配、Excel 与上传写入必须由正式 OT Gate 裁决。
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001')).toBeNull();
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001', { expectedOrderDataVersion: 7 })).toEqual({
actionType: 'shipping.freeze_order',
payload: { task_no: 'SN-FREEZE-001', expected_order_data_version: 7 },
});
expect(resolveShippingChatTurn('confirm_inventory_source', 'sn-source-001', { sourceCode: 'WH-A' })).toBeNull();
expect(resolveShippingChatTurn('match_inventory', 'sn-match-001')).toBeNull();
expect(resolveShippingChatTurn('generate_excel', 'sn-excel-001')).toBeNull();
expect(resolveShippingChatTurn('retry_upload', 'sn-upload-001')).toBeNull();
});
it('maps confirm decision to submit_decision', () => {
expect(resolveShippingChatTurn('confirm', 'sn-1')).toEqual({
actionType: 'shipping.submit_decision',
payload: { task_no: 'SN-1', decision: 'confirm' },
});
it('does not map a legacy confirm decision to a Chat Turn', () => {
expect(resolveShippingChatTurn('confirm', 'sn-1')).toBeNull();
});
});
@@ -1,11 +1,9 @@
/**
* features/chat/shipping/shippingTurnActions.ts
* 用途:将发货通知菜单/决策 action.id 映射为 Chat Turn action_type + payload。
* 依赖:constants/shipping。
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息;
* co8 后已移除 create_batch / switch_batch_focus Turn 构造器,上传改走 Intake + order extraction。
* 用途:仅构造仍允许的发货通知 Chat Turn。
* 依赖:无。
* 逻辑:履约写操作已统一迁入正式 OT Gate,本模块只保留非履约的聊天辅助 Turn。
*/
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
export interface ShippingChatTurnSpec {
actionType: string;
@@ -13,10 +11,10 @@ export interface ShippingChatTurnSpec {
}
/**
* 将发货 UI 动作 id 解析为平台 Chat Turn 规格。
* 将仍允许的 Chat 动作解析为平台 Turn 规格。
* @param actionId - 状态机 action_buttons.id
* @param taskNo - 任务编号
* @param extra - 额外参数,如 confirm_inventory_source 的 source_code
* @param extra - 保留参数,供调用方类型兼容;履约写不再使用。
* @returns Chat Turn 规格;无法映射时返回 null
*/
export function resolveShippingChatTurn(
@@ -29,59 +27,9 @@ export function resolveShippingChatTurn(
const id = String(actionId || '').trim();
if (!id) return null;
if (SHIPPING_DECISION_ACTIONS.has(id)) {
return {
actionType: 'shipping.submit_decision',
payload: { task_no: normalizedTaskNo, decision: id },
};
}
switch (id) {
case 'freeze_order':
const expectedOrderDataVersion = extra?.expectedOrderDataVersion;
if (!Number.isInteger(expectedOrderDataVersion) || !expectedOrderDataVersion || expectedOrderDataVersion < 1) return null;
return {
actionType: 'shipping.freeze_order',
payload: {
task_no: normalizedTaskNo,
expected_order_data_version: expectedOrderDataVersion,
},
};
case 'generate_excel':
return { actionType: 'shipping.generate_excel', payload: { task_no: normalizedTaskNo } };
case 'retry_upload':
return { actionType: 'shipping.retry_upload', payload: { task_no: normalizedTaskNo } };
case 'match_inventory':
return { actionType: 'shipping.match_inventory', payload: { task_no: normalizedTaskNo } };
case 'mark_manual_uploaded':
return { actionType: 'shipping.mark_manual_uploaded', payload: { task_no: normalizedTaskNo } };
case 'confirm_inventory_source': {
const sourceCode = String(extra?.sourceCode || '').trim().toUpperCase();
if (!sourceCode) return null;
return {
actionType: 'shipping.confirm_inventory_source',
payload: { task_no: normalizedTaskNo, source_code: sourceCode },
};
}
default:
return null;
}
}
/**
* 构造 submit_decision Chat Turn(文本/菜单决策共用)。
*/
export function buildShippingSubmitDecisionTurn(
taskNo: string,
decision: string,
): ShippingChatTurnSpec {
return {
actionType: 'shipping.submit_decision',
payload: {
task_no: String(taskNo || '').trim().toUpperCase(),
decision: String(decision || '').trim(),
},
};
void id;
void extra;
return null;
}
/**
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
@@ -1,102 +1,57 @@
/**
* features/chat/shipping/useChatShippingDecision.spec.ts
* 用途:验证发货通知决策处理器经 Chat Turn 发起,silent 模式不追加用户气泡。
* 用途:验证发货 Chat 不再承载履约写,操作只刷新权威 OT 投影。
* 依赖:vitest、vue refs、useChatShippingDecision。
* 逻辑:mock startChatTurn,覆盖 silent/普通决策与显式 taskId 分支。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision';
import type { ChatMessage } from '../types/chat.types';
const defaultStartChatTurn = vi.fn(async (options: {
hooks?: { onAssistantMessageFinished?: (msg: ChatMessage) => Promise<void> };
}) => {
await options?.hooks?.onAssistantMessageFinished?.(
{ role: 'assistant', content: 'mock assistant' },
);
return true;
});
const createContext = (
overrides: Partial<ShippingDecisionContext> = {},
): ShippingDecisionContext => ({
messages: ref([]),
conversationId: ref('conv-001'),
history: ref([{ conversation_id: 'conv-001' }]),
isShippingNoticeAgent: computed(() => true),
currentAgentId: computed(() => 42),
getActiveShippingTaskId: () => 'SN-FOCUS-001',
getActiveShippingBatchNo: () => 'BATCH-001',
loadHistory: vi.fn(async () => undefined),
refreshShippingActions: vi.fn(async () => undefined),
startChatTurn: defaultStartChatTurn,
msg: {
warning: vi.fn(),
success: vi.fn(),
},
t: (key: string) => key,
...overrides,
});
describe('useChatShippingDecision', () => {
beforeEach(() => {
defaultStartChatTurn.mockClear();
});
it('does not append local chat messages when decision runs in silent mode', async () => {
it('does not dispatch a Chat Turn for a legacy decision', async () => {
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('reparse_inventory', '重新上传库存', { silent: true });
expect(ok).toBe(true);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
inputType: 'action',
actionType: 'shipping.submit_decision',
payload: { task_no: 'SN-FOCUS-001', decision: 'reparse_inventory' },
silent: true,
}),
);
expect(ctx.messages.value).toEqual([]);
expect(ok).toBe(false);
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('delegates normal decisions to startChatTurn with display text', async () => {
it('does not dispatch a Chat Turn for a normal legacy decision', async () => {
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('confirm', '确认');
expect(ok).toBe(true);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
actionType: 'shipping.submit_decision',
displayText: expect.stringContaining('SN-FOCUS-001'),
payload: { task_no: 'SN-FOCUS-001', decision: 'confirm' },
}),
);
expect(ok).toBe(false);
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('does not show success toast for retry_rpa inside shipping agent workspace', async () => {
it('refreshes authoritative actions when Chat decision is rejected', async () => {
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('retry_rpa', '重新获取库存');
expect(ok).toBe(true);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
payload: { task_no: 'SN-FOCUS-001', decision: 'retry_rpa' },
}),
);
expect(ctx.msg.success).not.toHaveBeenCalled();
expect(ok).toBe(false);
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('prefers explicit taskId for workspace retry decisions', async () => {
it('does not dispatch even when a legacy decision supplies an explicit taskId', async () => {
const ctx = createContext({
getActiveShippingTaskId: () => '',
});
@@ -104,22 +59,14 @@ describe('useChatShippingDecision', () => {
const ok = await executeShippingDecision('retry_rpa', '重新获取库存', { taskId: 'sn-target-009' });
expect(ok).toBe(true);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
payload: { task_no: 'SN-TARGET-009', decision: 'retry_rpa' },
}),
);
expect(ctx.msg.warning).not.toHaveBeenCalled();
expect(ok).toBe(false);
});
it('returns false when startChatTurn reports failure', async () => {
const ctx = createContext({
startChatTurn: vi.fn(async () => false),
});
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
it('does not dispatch manual upload through Chat', async () => {
const ctx = createContext();
const { executeShippingManualUpload } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('confirm', '确认');
const ok = await executeShippingManualUpload('SN-FOCUS-001');
expect(ok).toBe(false);
});
@@ -1,28 +1,13 @@
/**
* features/chat/shipping/useChatShippingDecision.ts
* 用途:封装人工决策提交与手工上传标记逻辑,统一走 Chat Turn SSE。
* 依赖:shippingTurnActions、chat-turn.types、chat.types。
* 逻辑:由 useChatShipping 调用;所有决策/手工上传经 startChatTurn,不再 push 本地消息或直调 workspace API。
* 用途:阻止 Chat 提交已迁入正式 OT Gate 的履约写操作。
* 依赖:chat.types。
* 逻辑:历史聊天指令只刷新权威投影并提示进入任务处理页;不再构造 Chat Turn 或上传凭据。
*/
import { buildShippingSubmitDecisionTurn, buildShippingTurnRefs } from './shippingTurnActions';
import { reportShippingDebugEvent } from './shippingDebugReporter';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
export interface ShippingDecisionContext {
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
history: Ref<ChatSessionItem[]>;
isShippingNoticeAgent: ComputedRef<boolean>;
currentAgentId: ComputedRef<number>;
getActiveShippingTaskId: () => string;
getActiveShippingBatchNo: () => string;
loadHistory: () => Promise<void>;
refreshShippingActions: () => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
msg: { warning: (text: string) => void; success: (text: string) => void };
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
@@ -34,139 +19,36 @@ export interface ExecuteShippingDecisionOptions {
/**
* 创建发货通知决策处理器。
*
* 核心逻辑:构造 shipping.submit_decision Chat Turn,由平台 SSE 统一渲染 user/assistant 与 ChatLog。
* 核心逻辑:Chat 不再有履约写执行权,只刷新后端 Gate 投影。
* @param ctx - 决策处理上下文
* @returns 人工决策与手工上传确认处理函数
*/
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
const manualUploadInFlightTaskIds = new Set<string>();
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
reportShippingDebugEvent('useChatShippingDecision.ts', hypothesisId, msg, data);
const syncHistoryIfNeeded = async () => {
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
await ctx.loadHistory();
} else if (ctx.conversationId.value) {
const exists = ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value);
if (!exists) await ctx.loadHistory();
}
};
const afterDecisionTurn = async () => {
await syncHistoryIfNeeded();
void ctx.refreshShippingActions();
};
/**
* 在 Chat 操作中选择并上传人工货代回执,返回当前用户私有的 FileAsset 编号。
* 取消选择不会提交“已手工上传”动作,确保后端的证据门禁没有绕过路径。
*/
const selectManualUploadEvidence = () => new Promise<File | null>((resolve) => {
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = 'image/*,.pdf';
picker.style.display = 'none';
document.body.appendChild(picker);
let settled = false;
const finish = (file: File | null) => {
if (settled) return;
settled = true;
picker.remove();
resolve(file);
};
picker.addEventListener('change', () => finish(picker.files?.[0] || null), { once: true });
picker.addEventListener('cancel', () => finish(null), { once: true });
// 部分浏览器不会触发 cancel;窗口重新获得焦点后仍未选择文件即视为取消。
window.addEventListener('focus', () => setTimeout(() => finish(picker.files?.[0] || null), 0), { once: true });
picker.click();
});
/**
* 提交发货人工决策,经 Chat Turn 统一 SSE 返回。
*/
/** 历史 Chat 决策只刷新 Gate 投影,禁止绕过正式 OT。 */
const executeShippingDecision = async (
decision: string,
displayText?: string,
options?: ExecuteShippingDecisionOptions,
) => {
const taskId = String(options?.taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
void reportRetryRpaDebug('D', 'executeShippingDecision entry', {
decision,
taskId,
conversationId: ctx.conversationId.value,
silent: Boolean(options?.silent),
});
void decision;
void displayText;
void options;
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return false;
}
const userText = (displayText || decision).trim();
const turnSpec = buildShippingSubmitDecisionTurn(taskId, decision);
try {
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: options?.silent ? userText : `${userText}\n任务编号:${taskId}`,
actionType: turnSpec.actionType,
payload: turnSpec.payload,
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
silent: options?.silent,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
void assistantMsg;
await afterDecisionTurn();
},
},
});
return ok;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.streamError.generic');
ctx.msg.warning(errorMessage);
return false;
}
await ctx.refreshShippingActions();
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return false;
};
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
if (!normalizedTaskId || manualUploadInFlightTaskIds.has(normalizedTaskId)) return false;
manualUploadInFlightTaskIds.add(normalizedTaskId);
const userText = (displayText || '我已在货代系统完成上传').trim();
try {
const evidenceFile = await selectManualUploadEvidence();
if (!evidenceFile) {
ctx.msg.warning('请先选择货代上传截图或回执文件');
return false;
}
const evidence = await uploadFileAsset(evidenceFile);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: userText,
actionType: 'shipping.mark_manual_uploaded',
payload: { task_no: normalizedTaskId, evidence_asset_no: evidence.asset_no },
refs: buildShippingTurnRefs(normalizedTaskId, ctx.getActiveShippingBatchNo()),
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
assistantMsg.shipping_actions_used = true;
assistantMsg.shipping_actions = undefined;
ctx.messages.value.forEach((rawMsg) => {
if (rawMsg.role === 'assistant') {
rawMsg.shipping_actions = undefined;
}
});
void ctx.refreshShippingActions();
},
},
});
return ok;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
ctx.msg.warning(errorMessage);
return false;
} finally {
manualUploadInFlightTaskIds.delete(normalizedTaskId);
}
void taskId;
void displayText;
await ctx.refreshShippingActions();
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return false;
};
return { executeShippingDecision, executeShippingManualUpload };
@@ -8,23 +8,10 @@ import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createShippingMenuHandlers, type ShippingMenuHandlerContext } from './useChatShippingMenuHandler';
const {
confirmWorkspaceShippingInventorySource,
getWorkspaceShippingTask,
} = vi.hoisted(() => ({
confirmWorkspaceShippingInventorySource: vi.fn(),
getWorkspaceShippingTask: vi.fn(),
}));
const { downloadWorkspaceShippingExcelFile } = vi.hoisted(() => ({
downloadWorkspaceShippingExcelFile: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
confirmWorkspaceShippingInventorySource,
getWorkspaceShippingTask,
}));
vi.mock('./shippingDownload', () => ({
downloadWorkspaceShippingExcelFile,
}));
@@ -54,12 +41,10 @@ const createContext = (
describe('useChatShippingMenuHandler', () => {
beforeEach(() => {
confirmWorkspaceShippingInventorySource.mockReset();
getWorkspaceShippingTask.mockReset();
downloadWorkspaceShippingExcelFile.mockReset();
});
it('uses explicit taskId for retry_rpa workspace actions', async () => {
it('does not execute retry_rpa from a Chat menu', async () => {
const ctx = createContext();
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
@@ -69,16 +54,8 @@ describe('useChatShippingMenuHandler', () => {
{ taskId: 'sn-target-009' },
);
expect(ctx.executeShippingDecision).toHaveBeenCalledWith(
'retry_rpa',
'重新获取库存',
{ taskId: 'SN-TARGET-009' },
);
expect(ctx.executeShippingDecision).not.toHaveBeenCalledWith(
'retry_rpa',
'重新获取库存',
{ taskId: 'SN-ACTIVE-001' },
);
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
expect(ctx.refreshShippingActions).toHaveBeenCalledOnce();
});
it('does not dispatch legacy generate_excel Chat Turn', async () => {
@@ -109,8 +86,7 @@ describe('useChatShippingMenuHandler', () => {
expect(ctx.refreshShippingActions).toHaveBeenCalled();
});
it('reads the displayed order version before freezing through Chat Turn', async () => {
getWorkspaceShippingTask.mockResolvedValue({ order_data_version: 9 });
it('does not dispatch a legacy freeze action through Chat Turn', async () => {
const ctx = createContext();
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
@@ -120,10 +96,7 @@ describe('useChatShippingMenuHandler', () => {
{ taskId: 'sn-freeze-901' },
);
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
actionType: 'shipping.freeze_order',
payload: { task_no: 'SN-FREEZE-901', expected_order_data_version: 9 },
}));
expect(ctx.startChatTurn).not.toHaveBeenCalled();
});
it('passes explicit taskId into inventory picker actions', async () => {
@@ -1,26 +1,19 @@
/**
* features/chat/shipping/useChatShippingMenuHandler.ts
* 用途:分发聊天气泡动作按钮点击;业务动作统一走 Chat Turn SSE。
* 依赖:shippingTurnActions、shipping.api(只读 task 详情)、shippingDownload、chat.types。
* 逻辑:可映射为 action_type 的按钮走 startChatTurn;纯 UI(下载/选文件/表单)仍走本地行为。
* 用途:分发聊天气泡的只读与导航辅助操作。
* 依赖:shippingDownload、chat.types。
* 逻辑:履约写只由正式 OT Gate 执行;历史聊天写动作仅刷新,不再创建 Chat Turn。
*/
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import { buildShippingTurnRefs, resolveShippingChatTurn } from './shippingTurnActions';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingActionButton } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
import type { Ref } from 'vue';
export interface ShippingMenuHandlerContext {
isThinking: Ref<boolean>;
currentAgentId: ComputedRef<number>;
getActiveShippingTaskId: () => string;
getActiveShippingBatchNo: () => string;
messages: Ref<ChatMessage[]>;
sendShippingMenuMessage: (message: string) => Promise<void>;
openShippingInventoryPicker: (taskId?: string) => boolean;
openShippingNoticePicker: (taskId?: string) => boolean;
openShippingCustomerDialog: (taskId: string) => Promise<void>;
executeShippingDecision: (
@@ -30,7 +23,6 @@ export interface ShippingMenuHandlerContext {
) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string, ...args: unknown[]) => string;
}
@@ -43,78 +35,6 @@ export interface HandleShippingMenuActionOptions {
* 创建发货通知动作菜单处理器。
*/
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
const normalizeInventorySourceText = (value: string) =>
String(value || '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '');
const recentInventorySourceHint = () => {
const parts: string[] = [];
for (let i = ctx.messages.value.length - 1; i >= 0 && parts.length < 6; i -= 1) {
const content = String(ctx.messages.value[i]?.content || '').trim();
if (content) parts.push(content);
}
return parts.join('\n');
};
const resolveInventorySourceCodeFromContext = async (taskId: string): Promise<string> => {
const detail = await getWorkspaceShippingTask(taskId);
const resolution = detail.inventory_source_resolution;
const candidates = resolution && typeof resolution === 'object'
? (resolution as { candidates?: unknown }).candidates
: null;
if (!Array.isArray(candidates) || candidates.length === 0) return '';
if (candidates.length === 1) {
const only = candidates[0];
return only && typeof only === 'object'
? String((only as { source_code?: unknown }).source_code || '').trim().toUpperCase()
: '';
}
const hint = normalizeInventorySourceText(recentInventorySourceHint());
if (!hint) return '';
const matches = candidates.filter((item) => {
if (!item || typeof item !== 'object') return false;
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
const values = [
source.source_code,
source.display_name,
source.warehouse_code,
source.program_name,
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
return values.some((value) => hint.includes(value) || value.includes(hint));
});
if (matches.length !== 1) return '';
return String((matches[0] as { source_code?: unknown }).source_code || '').trim().toUpperCase();
};
const runShippingActionTurn = async (
action: ShippingActionButton | { id?: string; message: string; label?: string },
taskId: string,
extra?: { sourceCode?: string; expectedOrderDataVersion?: number },
) => {
const actionId = String(action.id || '').trim();
const turnSpec = resolveShippingChatTurn(actionId, taskId, extra);
if (!turnSpec) return false;
const displayBase = String(action.message || actionId || '操作').trim();
const displayText = actionId === 'confirm_inventory_source'
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmWithTask', { taskId })
: ctx.t('chat.shippingNoticeUi.inventorySource.actionWithTask', { message: displayBase, taskId });
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText,
actionType: turnSpec.actionType,
payload: turnSpec.payload,
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
hooks: {
onAssistantMessageFinished: async () => {
void ctx.refreshShippingActions();
},
},
});
return true;
};
const handleShippingMenuAction = async (
action: ShippingActionButton | { id?: string; message: string },
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
@@ -152,105 +72,17 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
return;
}
// 旧匹配/Excel 动作仅保留历史文案兼容;业务执行必须由 Projection
// 下发的正式 Gate Action 驱动,Chat 不得再创建 legacy Turn。
if (action.id === 'match_inventory' || action.id === 'generate_excel') {
await ctx.refreshShippingActions();
ctx.msg.info(ctx.t('chat.shippingNoticeRefreshDone'));
return;
}
const chatTurnActionIds = new Set([
'freeze_order',
'generate_excel',
'retry_upload',
'match_inventory',
'mark_manual_uploaded',
'confirm_inventory_source',
]);
if (action.id && chatTurnActionIds.has(action.id)) {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
try {
let sourceCode = '';
let expectedOrderDataVersion: number | undefined;
if (action.id === 'freeze_order') {
const detail = await getWorkspaceShippingTask(taskId);
const version = Number(detail.order_data_version);
if (!Number.isInteger(version) || version < 1) {
ctx.msg.warning(ctx.t('chat.shippingNoticeRefreshRequired'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
expectedOrderDataVersion = version;
}
if (action.id === 'confirm_inventory_source') {
sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
if (!sourceCode) {
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
}
if (!sourceCode) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.inventorySource.inputHint'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
}
if (action.id === 'mark_manual_uploaded') {
await ctx.executeShippingManualUpload(taskId, '我已在货代系统完成上传');
return;
}
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
const displayMessage = action.id === 'confirm_inventory_source'
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label: label || sourceCode })
: action.message;
await runShippingActionTurn(
{ ...action, message: displayMessage },
taskId,
sourceCode ? { sourceCode } : { expectedOrderDataVersion },
);
} catch (e: unknown) {
ctx.msg.warning(e instanceof Error ? e.message : '操作失败');
if (chatMsg) chatMsg.shipping_actions_used = false;
}
return;
}
if (action.id === 'retry_resolve_inventory_source') {
await ctx.refreshShippingActions();
ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone'));
return;
}
if (action.id === 'upload_inventory_file') {
ctx.openShippingInventoryPicker(resolveTaskId());
return;
}
if (action.id === 'replace_notice_file') {
ctx.openShippingNoticePicker(resolveTaskId());
return;
}
if (action.id === 'reparse_inventory') {
if (chatMsg?.shipping_actions_used) return;
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
if (chatMsg) chatMsg.shipping_actions_used = true;
const ok = await ctx.executeShippingDecision('reparse_inventory', action.message, { silent: true, taskId });
if (ok) ctx.openShippingInventoryPicker(taskId);
return;
}
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
await ctx.executeShippingDecision(action.id, action.message, { taskId: resolveTaskId() });
if (action.id && [
'freeze_order', 'match_inventory', 'rematch',
'generate_excel', 'retry_upload', 'mark_manual_uploaded', 'reparse_inventory',
'confirm', 'retry_rpa', 'reject', 'reparse',
].includes(action.id)) {
await ctx.refreshShippingActions();
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return;
}
if (chatMsg?.shipping_actions_used) return;
@@ -4,15 +4,11 @@
* 依赖:shipping.api(任务详情)、shippingIntents、shippingMenu、shippingDownload、chat.types。
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;co8 后切票不再调用 shipping_batches API,改提示用户使用 processing 工作台。
*/
import {
getWorkspaceShippingTask,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import {
isShippingDownloadExcelIntent,
isShippingGenerateExcelIntent,
isShippingInventoryUploadIntent,
isShippingManualUploadIntent,
parseShippingTaskSwitchIntent,
} from './shippingIntents';
@@ -56,7 +52,6 @@ export interface ShippingSendHandlerContext {
loadHistory: () => Promise<void>;
sendShippingMenuMessage: (message: string) => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
openShippingInventoryPicker: () => boolean;
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise<void>;
@@ -95,55 +90,6 @@ export interface ShippingSendHandlerContext {
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
*/
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const normalizeInventorySourceText = (value: string) =>
String(value || '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '');
const tryConfirmInventorySourceFromText = async (content: string): Promise<boolean> => {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) return false;
const normalized = normalizeInventorySourceText(content);
if (!normalized) return false;
try {
const detail = await getWorkspaceShippingTask(taskId);
if (detail.pending_human_reason !== 'inventory_source_unresolved') return false;
const resolution = detail.inventory_source_resolution;
const candidates = resolution && typeof resolution === 'object'
? (resolution as { candidates?: unknown }).candidates
: null;
if (!Array.isArray(candidates) || candidates.length === 0) return false;
const hit = candidates.find((item) => {
if (!item || typeof item !== 'object') return false;
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
const values = [
source.source_code,
source.display_name,
source.warehouse_code,
source.program_name,
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
return values.some((value) => normalized === value || normalized.includes(value) || value.includes(normalized));
}) as { source_code?: unknown; display_name?: unknown } | undefined;
const sourceCode = String(hit?.source_code || '').trim().toUpperCase();
if (!sourceCode) return false;
if (typeof content !== 'string') return false;
ctx.input.value = '';
ctx.attachments.value = [];
const label = String(hit?.display_name || sourceCode).trim();
await ctx.handleShippingMenuAction({
id: 'confirm_inventory_source',
message: ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label }),
label,
source_code: sourceCode,
});
return true;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUi.inventorySource.confirmFailed');
ctx.msg.warning(errorMessage);
return true;
}
};
/**
* 拦截切票/切任务意图(co8 已下线批次 API)。
*
@@ -280,11 +226,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.attachments.value = [];
return true;
}
if (await tryConfirmInventorySourceFromText(content)) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
return true;
}
const assistantCtx = ctx.lastAssistantMessageContent();
const numericText = content.trim();
if (/^[1-91-9](?:[\.\、\)::]?)$/.test(numericText)) {
@@ -303,9 +244,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
if (menuChoice) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
if (menuChoice === 'upload') {
if (ctx.openShippingInventoryPicker()) return true;
} else if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
const spec = SHIPPING_MENU_ACTION_SPECS[menuChoice];
await ctx.executeShippingDecision(menuChoice, spec?.label || spec?.message || menuChoice);
return true;
@@ -320,32 +259,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
if (await ctx.executeShippingDecision(shippingDecision, content.trim())) return true;
}
if (isShippingManualUploadIntent(content)) {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning('未找到任务编号,请先完成前面的步骤');
return true;
}
ctx.resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.executeShippingManualUpload(taskId, content.trim());
return true;
}
if (isShippingInventoryUploadIntent(content, assistantCtx)) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
if (ctx.openShippingInventoryPicker()) return true;
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return true;
}
if (isShippingGenerateExcelIntent(content)) {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning('未找到任务编号,请先完成解析与库存匹配');
return true;
}
ctx.resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.handleShippingMenuAction({ id: 'generate_excel', message: content.trim() });
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
return true;
}
if (isShippingDownloadExcelIntent(content)) {
@@ -23,7 +23,6 @@ import { normalizeShippingProcessingProjection } from './normalizeShippingProces
const DEFAULT_POLL_MS = 3000;
const TERMINAL_STATUSES = new Set([
'completed',
'failed',
'cancelled',
]);