feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议
This commit is contained in:
1 parent
46eb63f5bb
commit
e9bdd81f1a
320 files changed
+28361
-10487
No files matched your search
@@ -7,7 +7,6 @@
|
||||
export * from './shippingText';
|
||||
export * from './shippingMenu';
|
||||
export * from './shippingIntents';
|
||||
export * from './shippingMapping';
|
||||
export * from './shippingTaskId';
|
||||
export * from './shippingDownload';
|
||||
export * from './shippingDecisionFormat';
|
||||
@@ -18,7 +17,6 @@ export * from './shippingStepper';
|
||||
export * from './shippingLocalMessages';
|
||||
export * from './shippingConversation';
|
||||
export * from './useChatShippingRefresh';
|
||||
export * from './useChatShippingMappingForm';
|
||||
export * from './useChatShippingParseReview';
|
||||
export * from './useChatShippingDecision';
|
||||
export * from './useChatShippingMenuHandler';
|
||||
|
||||
@@ -1,34 +1,24 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingDecisionFormat.spec.ts
|
||||
* 用途:验证库存映射人工修正摘要使用 v2 系统字段名。
|
||||
* 用途:验证库存重新上传决策只输出业务引导,不再暴露任务级字段映射。
|
||||
* 依赖:vitest、shippingDecisionFormat。
|
||||
* 逻辑:锁死建议映射展示中的 part_number,防止旧 sku 契约回流。
|
||||
* 逻辑:断言重新上传提示和任务编号完整,同时排除旧技术字段。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat';
|
||||
|
||||
describe('formatShippingDecisionAssistantMessage', () => {
|
||||
it('renders part_number for inventory mapping suggestions', () => {
|
||||
it('guides inventory reupload without legacy mapping terms', () => {
|
||||
const text = formatShippingDecisionAssistantMessage(
|
||||
'correct_inventory_mapping',
|
||||
{
|
||||
message: '请修正映射',
|
||||
data: {
|
||||
schema_preview: {
|
||||
headers: ['Supplier Sku', 'COM ID', 'Qty Available'],
|
||||
suggested_mapping: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'SN-MAP-001',
|
||||
'reparse_inventory',
|
||||
{ message: '当前库存已解除关联。' },
|
||||
'SN-REUPLOAD-001',
|
||||
'操作已完成',
|
||||
);
|
||||
|
||||
expect(text).toContain('- part_number → Supplier Sku');
|
||||
expect(text).not.toContain('- sku →');
|
||||
expect(text).toContain('选择库存文件');
|
||||
expect(text).toContain('SN-REUPLOAD-001');
|
||||
expect(text).not.toContain('schema_preview');
|
||||
expect(text).not.toContain('map_json');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/shippingDecisionFormat.ts
|
||||
* 用途:决策 API 响应格式化为助手 Markdown 消息。
|
||||
* 依赖:无;useChatShippingDecision 在 submit_decision 成功后调用。
|
||||
* 逻辑:按 decision 类型追加映射提示、下一步指引与任务编号尾注。
|
||||
* 逻辑:按 decision 类型追加业务提示与任务编号尾注。
|
||||
*/
|
||||
/**
|
||||
* 将 submit_decision 结果格式化为本地 assistant 消息 Markdown。
|
||||
@@ -14,34 +14,8 @@ export function formatShippingDecisionAssistantMessage(
|
||||
fallbackDoneMessage: string,
|
||||
): string {
|
||||
const lines: string[] = [result.message || fallbackDoneMessage];
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
const preview = (result.data?.schema_preview || {}) as Record<string, unknown>;
|
||||
const headers = Array.isArray(preview.headers) ? (preview.headers as unknown[]).filter(Boolean) : [];
|
||||
const suggested = (preview.suggested_mapping || {}) as Record<string, string>;
|
||||
if (preview.header_row_index) {
|
||||
lines.push('', `表头在第 ${preview.header_row_index} 行:${headers.join(' | ')}`);
|
||||
} else if (headers.length) {
|
||||
lines.push('', `当前表头:${headers.join(' | ')}`);
|
||||
}
|
||||
const mappingLines = [
|
||||
suggested.part_number ? `- part_number → ${suggested.part_number}` : null,
|
||||
suggested.reservation_id ? `- reservation_id → ${suggested.reservation_id}` : null,
|
||||
suggested.available_qty ? `- available_qty → ${suggested.available_qty}` : null,
|
||||
].filter((line): line is string => Boolean(line));
|
||||
if (mappingLines.length) {
|
||||
lines.push('', '建议列映射:', ...mappingLines);
|
||||
}
|
||||
lines.push(
|
||||
'',
|
||||
'如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。',
|
||||
'也可点击「选择库存文件」重新上传。',
|
||||
);
|
||||
} else if (decision === 'confirm_inventory_mapping') {
|
||||
if (String(result.checkpoint || '').trim() === 'map_ok') {
|
||||
lines.push('', '下一步:匹配库存与发货需求。');
|
||||
}
|
||||
} else if (decision === 'reparse_inventory') {
|
||||
lines.push('', '请重新上传或粘贴库存 Excel。');
|
||||
if (decision === 'reparse_inventory') {
|
||||
lines.push('', '请点击「选择库存文件」重新上传。');
|
||||
}
|
||||
lines.push('', `任务编号:${taskId}`);
|
||||
return lines.join('\n');
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingIntents.spec.ts
|
||||
* 用途:验证发货聊天自然语言库存映射遵循 v2 字段契约。
|
||||
* 依赖:vitest、shippingIntents。
|
||||
* 逻辑:覆盖完整三字段映射与缺 Reservation 拒绝分支。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseShippingColumnMappingFromText } from './shippingIntents';
|
||||
|
||||
describe('parseShippingColumnMappingFromText', () => {
|
||||
it('normalizes SKU wording to the v2 part_number key', () => {
|
||||
expect(parseShippingColumnMappingFromText([
|
||||
'SKU -> Supplier Sku',
|
||||
'Reservation ID -> COM ID',
|
||||
'Available Qty -> Qty Available',
|
||||
].join('\n'))).toEqual({
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects mappings that omit Reservation ID', () => {
|
||||
expect(parseShippingColumnMappingFromText([
|
||||
'part_number -> Supplier Sku',
|
||||
'available_qty -> Qty Available',
|
||||
].join('\n'))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/shippingIntents.ts
|
||||
* 用途:发货聊天用户输入意图识别,供 handleSend 前置拦截。
|
||||
* 依赖:shippingMenu.resolveShippingNumericChoice、types/shipping.types。
|
||||
* 逻辑:useChatShippingSendHandler 调用;覆盖手工上传、库存上传、Excel 生成/下载、列映射与切票。
|
||||
* 逻辑:useChatShippingSendHandler 调用;覆盖手工上传、库存上传、Excel 生成/下载与切票。
|
||||
*/
|
||||
import { resolveShippingNumericChoice } from './shippingMenu';
|
||||
import type { ShippingMenuAction } from '../types/shipping.types';
|
||||
@@ -15,43 +15,6 @@ export interface ShippingTaskSwitchIntent {
|
||||
/**
|
||||
* 从自然语言文本解析库存列映射(part_number / reservation_id / available_qty → Excel 列名)。
|
||||
*/
|
||||
export function parseShippingColumnMappingFromText(content: string): Record<string, string> | null {
|
||||
const raw = String(content || '').trim();
|
||||
if (!raw) return null;
|
||||
if (!/[→>=-]/.test(raw)) return null;
|
||||
const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
||||
const mapping: Record<string, string> = {};
|
||||
const normalizeRight = (s: string) => String(s || '')
|
||||
.replace(/[::]/g, '')
|
||||
.replace(/列$/g, '')
|
||||
.replace(/字段$/g, '')
|
||||
.replace(/^\[|\]$/g, '')
|
||||
.trim();
|
||||
const toKey = (left: string) => {
|
||||
const s = left.toLowerCase();
|
||||
if (s.includes('reservation') || left.includes('预留') || left.includes('预定')) return 'reservation_id';
|
||||
if (s.includes('qty') || s.includes('available') || left.includes('可用') || left.includes('数量')) return 'available_qty';
|
||||
if (s.includes('part_number') || s.includes('part number') || s.includes('sku') || left.includes('料号') || left.includes('物料')) {
|
||||
return 'part_number';
|
||||
}
|
||||
return '';
|
||||
};
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^\s*(.+?)\s*(?:→|->|=>|=|:|:)\s*(.+?)\s*$/);
|
||||
if (!m) continue;
|
||||
const left = m[1];
|
||||
const right = m[2];
|
||||
if (!left || !right) continue;
|
||||
const key = toKey(left.trim());
|
||||
if (!key) continue;
|
||||
const col = normalizeRight(right);
|
||||
if (!col) continue;
|
||||
mapping[key] = col;
|
||||
}
|
||||
if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) return null;
|
||||
return mapping;
|
||||
}
|
||||
|
||||
export function isShippingManualUploadIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingMapping.ts
|
||||
* 用途:库存列映射消息 payload 读取与字段对齐 Markdown 生成。
|
||||
* 依赖:shippingText.normalizeShippingHeaderForDisplay、chat.types、shipping.types。
|
||||
* 逻辑:ShippingInventoryMappingMessage 与 useChatShippingMappingForm 读取 mapping 消息数据。
|
||||
*/
|
||||
import { normalizeShippingHeaderForDisplay } from './shippingText';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types';
|
||||
|
||||
/**
|
||||
* 从 shipping-inventory-mapping 类型消息中提取 taskId、schema_preview 与 form。
|
||||
*/
|
||||
export function getShippingInventoryMappingPayload(chatMsg: ChatMessage): ShippingInventoryMappingFormPayload | null {
|
||||
if (!chatMsg || chatMsg.type !== 'shipping-inventory-mapping') return null;
|
||||
const payload = chatMsg.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const taskId = String((payload as ShippingInventoryMappingFormPayload).taskId || '').trim();
|
||||
const schemaPreview = (payload as ShippingInventoryMappingFormPayload).schema_preview;
|
||||
const form = (payload as ShippingInventoryMappingFormPayload).form;
|
||||
if (!taskId || !schemaPreview || !form) return null;
|
||||
return payload as ShippingInventoryMappingFormPayload;
|
||||
}
|
||||
|
||||
export function hasShippingInventorySampleRows(chatMsg: ChatMessage): boolean {
|
||||
const rows = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows;
|
||||
return Array.isArray(rows) && rows.length > 0;
|
||||
}
|
||||
|
||||
export function getShippingInventorySampleRowText(chatMsg: ChatMessage): string {
|
||||
const row = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows?.[0];
|
||||
return Array.isArray(row) ? row.map((cell) => String(cell)).join(' | ') : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 field_alignment API 响应转为 Markdown 表格文本,供发送给 Agent 确认。
|
||||
*/
|
||||
export function buildShippingFieldAlignmentText(payload: { data?: { field_alignment?: Record<string, unknown> } }): string {
|
||||
const alignment = payload?.data?.field_alignment;
|
||||
if (!alignment || typeof alignment !== 'object') return '';
|
||||
const invCols = (alignment as { inventory_columns?: { mapping?: Record<string, { source_column?: string }> } }).inventory_columns || {};
|
||||
const mapping = invCols.mapping || {};
|
||||
const rows: Array<[string, string]> = [
|
||||
['part_number', normalizeShippingHeaderForDisplay(mapping?.part_number?.source_column) || '(未识别)'],
|
||||
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别)'],
|
||||
['available_qty', normalizeShippingHeaderForDisplay(mapping?.available_qty?.source_column) || '(未识别)'],
|
||||
];
|
||||
const lines: string[] = [];
|
||||
const matchRule = String((alignment as { match_rule?: string }).match_rule || '').trim();
|
||||
if (matchRule) lines.push(`匹配规则:${matchRule}`);
|
||||
lines.push('', '字段对齐表:', '', '|系统字段|库存列|', '|---|---|');
|
||||
for (const [k, v] of rows) {
|
||||
lines.push(`|${k}|${v}|`);
|
||||
}
|
||||
const warnings = Array.isArray((alignment as { warnings?: unknown[] }).warnings)
|
||||
? (alignment as { warnings: unknown[] }).warnings.filter(Boolean)
|
||||
: [];
|
||||
if (warnings.length) {
|
||||
lines.push('', '提示:', ...warnings.map((w) => `- ${String(w)}`));
|
||||
}
|
||||
return lines.join('\n').trim();
|
||||
}
|
||||
@@ -30,7 +30,6 @@ export function classifyShippingMenuLine(desc: string): ShippingMenuAction | nul
|
||||
if (!normalized) return null;
|
||||
if (/已确认/.test(normalized)) return null;
|
||||
if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload';
|
||||
if (/粘贴|文本|小量|直接发/i.test(desc)) return 'paste';
|
||||
if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa';
|
||||
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
|
||||
if (/驳回|取消|reject/i.test(desc)) return 'reject';
|
||||
@@ -78,11 +77,9 @@ export function normalizeApiShippingButtons(
|
||||
/**
|
||||
* 从用户文本与助手上下文识别 submit_decision 所需的 action id。
|
||||
*/
|
||||
export function resolveShippingDecisionFromText(text: string, assistantContext: string): string | null {
|
||||
export function resolveShippingDecisionFromText(text: string, _assistantContext: string): string | null {
|
||||
const normalized = text.trim();
|
||||
const direct: Record<string, string> = {
|
||||
更正映射: 'correct_inventory_mapping',
|
||||
更正列映射: 'correct_inventory_mapping',
|
||||
重新上传库存: 'reparse_inventory',
|
||||
重新上传: 'reparse_inventory',
|
||||
驳回: 'reject',
|
||||
@@ -92,9 +89,6 @@ export function resolveShippingDecisionFromText(text: string, assistantContext:
|
||||
};
|
||||
if (direct[normalized]) return direct[normalized];
|
||||
if (normalized === '确认') {
|
||||
if (assistantContext.includes('字段对齐') || assistantContext.includes('field_alignment') || assistantContext.includes('库存字段对齐')) {
|
||||
return 'confirm_inventory_mapping';
|
||||
}
|
||||
return 'confirm';
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -111,11 +111,9 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined):
|
||||
if (processStatus === 'waiting_upload' || processStatus === 'upload_failed' || hasExport) return 5;
|
||||
if (processStatus === 'matched') return 4;
|
||||
if (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage') return 4;
|
||||
if (reviewStatus === 'align_review' || pendingReason === 'align_review') return 3;
|
||||
if (processStatus === 'inventory_ready' || matchStatus) return 4;
|
||||
if (
|
||||
processStatus === 'waiting_inventory'
|
||||
|| pendingReason === 'map_infer'
|
||||
|| pendingReason === 'rpa_pending'
|
||||
|| pendingReason === 'inv_unavail'
|
||||
|| pendingReason === 'rpa_exhausted'
|
||||
@@ -167,7 +165,6 @@ export function buildShippingWorkflowSteps(
|
||||
|| pendingReason === 'inventory_source_unresolved'
|
||||
))
|
||||
|| (index === 2 && (pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted'))
|
||||
|| (index === 3 && (reviewStatus === 'align_review' || pendingReason === 'align_review'))
|
||||
|| (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage'))
|
||||
|| (index === 6 && processStatus === 'upload_failed')
|
||||
) {
|
||||
|
||||
@@ -249,18 +249,6 @@ export function stripShippingActionListByButtons(
|
||||
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
|
||||
if (!enabled) return text;
|
||||
let result = sanitizeShippingRuntimeStatusText(String(text || ''))
|
||||
.replace(
|
||||
/已回到列映射步骤。?请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi,
|
||||
'已回到库存字段确认步骤。请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。',
|
||||
)
|
||||
.replace(
|
||||
/请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi,
|
||||
'请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。',
|
||||
)
|
||||
.replace(
|
||||
/根据\s*data\.schema_preview\.headers\s*与\s*sample_rows\s*推断\s*JSON[^。.\n]*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi,
|
||||
'请根据库存表头和样例行确认字段对应关系。',
|
||||
)
|
||||
.replace(/通过\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传')
|
||||
.replace(/在\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传')
|
||||
.replace(/(?:Hxops|HXOPS|hxops)\s*聊天区/gi, '当前对话')
|
||||
@@ -278,12 +266,6 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
|
||||
.replace(/\bgenerate_excel\b/gi, '生成发货 Excel')
|
||||
.replace(/\bgenerate_shipment_excel\b/gi, '生成发货 Excel')
|
||||
.replace(/\bupload_to_freight\b/gi, '上传货代系统')
|
||||
.replace(/\bapply_inventory_mapping\b/gi, '应用库存字段映射')
|
||||
.replace(/\bget_inventory_schema_preview\b/gi, '读取库存表头预览')
|
||||
.replace(/\bschema_preview(?:\.headers)?\b/gi, '库存表头预览')
|
||||
.replace(/\bdata\.库存表头预览\b/gi, '库存表头预览')
|
||||
.replace(/\bmap_json\b/gi, '字段映射')
|
||||
.replace(/\bsample_rows\b/gi, '样例行')
|
||||
.replace(/\bretry_rpa\b/gi, '重新获取库存')
|
||||
.replace(/\bretry_upload\b/gi, '重试上传货代')
|
||||
.replace(/\bstructured\b/gi, '结构化内容')
|
||||
@@ -309,11 +291,3 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
|
||||
export function stripShippingActionsDirectiveComment(rawText: string): string {
|
||||
return String(rawText || '').replace(/<!--\s*HXOPS_SHIPPING_ACTIONS\s*:\s*[\s\S]*?\s*-->/gi, '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 库存表头列名展示规范化(空格转 NBSP,避免 Markdown 表格换行)。
|
||||
*/
|
||||
export function normalizeShippingHeaderForDisplay(raw: unknown): string {
|
||||
const text = String(raw ?? '').replace(/\s+/g, ' ').trim();
|
||||
return text.replace(/ /g, '\u00A0');
|
||||
}
|
||||
@@ -133,17 +133,6 @@ export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record<
|
||||
return refs;
|
||||
}
|
||||
|
||||
export function buildShippingUploadInventoryTurn(taskNo: string, file: File) {
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
return {
|
||||
actionType: 'shipping.upload_inventory',
|
||||
displayText: `上传库存文件:${file.name}`,
|
||||
payload: { task_no: task },
|
||||
files: [file],
|
||||
refs: buildShippingTurnRefs(task),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
return {
|
||||
@@ -155,16 +144,6 @@ export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
|
||||
};
|
||||
}
|
||||
|
||||
export function buildShippingApplyMappingTurn(taskNo: string, mapping: Record<string, string>) {
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
return {
|
||||
actionType: 'shipping.apply_inventory_mapping',
|
||||
displayText: `应用库存列映射(任务 ${task})`,
|
||||
payload: { task_no: task, map_json: mapping },
|
||||
refs: buildShippingTurnRefs(task),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildShippingSwitchFocusTurn(batchNo: string, taskNo: string, displayText: string) {
|
||||
const batch = String(batchNo || '').trim();
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingUploadPrompt.ts
|
||||
* 用途:库存/通知上传后发给 Dify 的提示语构建与附件类型分类。
|
||||
* 用途:通知上传后提示语构建、文件格式识别与临时库存声明判断。
|
||||
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
|
||||
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify LLM 解析续办。
|
||||
*/
|
||||
@@ -9,40 +9,6 @@ import i18n from '@/i18n';
|
||||
/**
|
||||
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
|
||||
*/
|
||||
export function buildShippingInventoryUploadPrompt(
|
||||
result: Record<string, unknown> | null | undefined,
|
||||
fileName?: string,
|
||||
): string {
|
||||
const checkpoint = String(result?.checkpoint || '').trim();
|
||||
const hasAlignment = Boolean(result?.data && typeof result.data === 'object'
|
||||
&& (result.data as { field_alignment?: unknown }).field_alignment
|
||||
&& typeof (result.data as { field_alignment?: unknown }).field_alignment === 'object');
|
||||
const suggestOk = Boolean((result?.data as { suggest_ok?: boolean } | undefined)?.suggest_ok);
|
||||
const batchNo = String(
|
||||
(result?.batch_no as string | undefined)
|
||||
|| ((result?.data as { batch_no?: string } | undefined)?.batch_no)
|
||||
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|
||||
|| '',
|
||||
).trim();
|
||||
const prefix = batchNo
|
||||
? (fileName
|
||||
? String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixBatchWithFile', { fileName, batchNo }))
|
||||
: String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixBatch', { batchNo })))
|
||||
: (fileName
|
||||
? String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixWithFile', { fileName }))
|
||||
: String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefix')));
|
||||
if (checkpoint === 'map_infer') {
|
||||
if (suggestOk) {
|
||||
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.mapInferSuggested', { prefix }));
|
||||
}
|
||||
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.mapInferPending', { prefix }));
|
||||
}
|
||||
if (checkpoint === 'align_review' || hasAlignment) {
|
||||
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.alignReview', { prefix }));
|
||||
}
|
||||
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.default', { prefix }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发画布 LLM 抽取 + parse_notice)。
|
||||
*/
|
||||
@@ -94,13 +60,30 @@ export function buildShippingNoticeUploadPrompt(
|
||||
}
|
||||
|
||||
/**
|
||||
* 按扩展名判断附件是库存 Excel 还是发货通知文件。
|
||||
* 判断文件是否为后端当前可受控分析的表格格式。
|
||||
* 格式只是技术能力,不能据此推断文件一定是库存或订单。
|
||||
*/
|
||||
export function classifyShippingUploadFile(
|
||||
export function isShippingSpreadsheetFile(
|
||||
file: File,
|
||||
extractExt: (name: string) => string,
|
||||
): 'inventory' | 'notice' {
|
||||
): boolean {
|
||||
const ext = extractExt(file.name || '').toLowerCase();
|
||||
if (['xlsx', 'xls', 'csv'].includes(ext)) return 'inventory';
|
||||
return 'notice';
|
||||
return ['xlsx', 'xls', 'csv'].includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断用户是否明确声明当前附件是库存文件。
|
||||
* 仅用于临时库存分支门禁;不能从文件名、表格后缀或模型猜测推导。
|
||||
*/
|
||||
export function isTemporaryInventoryDeclaration(text: string): boolean {
|
||||
const value = String(text || '').trim();
|
||||
if (!value) return false;
|
||||
return [
|
||||
/这是.*库存(?:文件|表|excel|csv)?/i,
|
||||
/(?:请|帮我|麻烦).*(?:分析|解析|识别).*(?:库存|stock)/i,
|
||||
/(?:上传|附件|这个|该).*(?:库存文件|库存表|库存excel|库存csv)/i,
|
||||
/(?:库存文件|库存表|库存excel|库存csv).*(?:分析|解析|识别|使用)/i,
|
||||
/(?:this|the).*(?:is|are).*(?:inventory|stock)/i,
|
||||
/(?:analyse|analyze|parse).*(?:inventory|stock)/i,
|
||||
].some((pattern) => pattern.test(value));
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/useChatShippingDecision.spec.ts
|
||||
* 用途:验证发货通知决策处理器经 Chat Turn 发起,silent 模式不追加用户气泡。
|
||||
* 依赖:vitest、vue refs、useChatShippingDecision。
|
||||
* 逻辑:mock startChatTurn,覆盖 silent/普通决策、显式 taskId 与 inventory_mapping 分支。
|
||||
* 逻辑:mock startChatTurn,覆盖 silent/普通决策与显式 taskId 分支。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
@@ -26,11 +26,9 @@ const createContext = (
|
||||
history: ref([{ conversation_id: 'conv-001' }]),
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
currentAgentId: computed(() => 42),
|
||||
shippingInventorySchemaPreviewCache: ref({}),
|
||||
getActiveShippingTaskId: () => 'SN-FOCUS-001',
|
||||
getActiveShippingBatchNo: () => 'BATCH-001',
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
startChatTurn: defaultStartChatTurn,
|
||||
msg: {
|
||||
@@ -115,21 +113,6 @@ describe('useChatShippingDecision', () => {
|
||||
expect(ctx.msg.warning).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submits confirm_inventory_mapping via submit_decision Chat Turn', async () => {
|
||||
const ctx = createContext();
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('confirm_inventory_mapping', '确认');
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
actionType: 'shipping.submit_decision',
|
||||
payload: { task_no: 'SN-FOCUS-001', decision: 'confirm_inventory_mapping' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('returns false when startChatTurn reports failure', async () => {
|
||||
const ctx = createContext({
|
||||
startChatTurn: vi.fn(async () => false),
|
||||
|
||||
@@ -16,11 +16,9 @@ export interface ShippingDecisionContext {
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
getActiveShippingBatchNo: () => string;
|
||||
loadHistory: () => Promise<void>;
|
||||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
||||
msg: { warning: (text: string) => void; success: (text: string) => void };
|
||||
@@ -54,23 +52,9 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
}
|
||||
};
|
||||
|
||||
const afterDecisionTurn = async (decision: string, taskId: string, assistantMsg?: ChatMessage) => {
|
||||
if (decision === 'correct_inventory_mapping' && assistantMsg?.payload && typeof assistantMsg.payload === 'object') {
|
||||
const toolResult = (assistantMsg.payload as { tool_result?: { data?: { schema_preview?: unknown } } }).tool_result;
|
||||
const preview = toolResult?.data?.schema_preview;
|
||||
const key = String(taskId || '').trim().toUpperCase();
|
||||
if (key && preview && typeof preview === 'object') {
|
||||
ctx.shippingInventorySchemaPreviewCache.value = {
|
||||
...ctx.shippingInventorySchemaPreviewCache.value,
|
||||
[key]: preview,
|
||||
};
|
||||
}
|
||||
}
|
||||
const afterDecisionTurn = async () => {
|
||||
await syncHistoryIfNeeded();
|
||||
void ctx.refreshShippingActions();
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
await ctx.openShippingInventoryMappingFormForTask(taskId);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -105,7 +89,8 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
silent: options?.silent,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
await afterDecisionTurn(decision, taskId, assistantMsg);
|
||||
void assistantMsg;
|
||||
await afterDecisionTurn();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMappingForm.spec.ts
|
||||
* 用途:验证库存人工列映射严格使用 v2 料号与 Reservation 契约。
|
||||
* 依赖:vitest、Vue refs、shipping.api、useChatShippingMappingForm。
|
||||
* 逻辑:覆盖表单预填、完整映射提交和缺 Reservation 本地阻断。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingMappingFormHandlers, type ShippingMappingFormContext } from './useChatShippingMappingForm';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
const { getWorkspaceShippingTask } = vi.hoisted(() => ({
|
||||
getWorkspaceShippingTask: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
getWorkspaceShippingTask,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingMappingFormContext> = {},
|
||||
): ShippingMappingFormContext => ({
|
||||
messages: ref<ChatMessage[]>([]),
|
||||
chatScrollContainer: ref(null),
|
||||
shippingInventorySchemaPreviewCache: ref({
|
||||
'SN-MAP-001': {
|
||||
headers: ['Supplier Sku', 'COM ID', 'Qty Available'],
|
||||
suggested_mapping: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
}),
|
||||
shippingInventoryPickerRef: ref(null),
|
||||
pendingShippingUploadTaskId: ref(''),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
newLocalMessageId: () => 'local-mapping-1',
|
||||
saveLocalMessageToBackend: vi.fn(async () => undefined),
|
||||
startChatTurn: vi.fn(async () => true),
|
||||
currentAgentId: computed(() => 42),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn() },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingMappingForm', () => {
|
||||
beforeEach(() => {
|
||||
getWorkspaceShippingTask.mockReset();
|
||||
getWorkspaceShippingTask.mockResolvedValue({
|
||||
lines: [{ part_number: 'D4-A08AR12000002', reservation_id: '3000092917', qty: 10 }],
|
||||
});
|
||||
});
|
||||
|
||||
it('prefills and submits the v2 inventory mapping fields', async () => {
|
||||
const ctx = createContext();
|
||||
const handlers = createShippingMappingFormHandlers(ctx);
|
||||
|
||||
expect(await handlers.openShippingInventoryMappingFormForTask('sn-map-001')).toBe(true);
|
||||
const message = ctx.messages.value[0];
|
||||
expect(message.payload).toMatchObject({
|
||||
order: { line_count: 1, part_numbers: ['D4-A08AR12000002'] },
|
||||
form: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
});
|
||||
|
||||
await handlers.applyShippingInventoryMappingForm(message);
|
||||
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
|
||||
actionType: 'shipping.apply_inventory_mapping',
|
||||
payload: {
|
||||
task_no: 'SN-MAP-001',
|
||||
map_json: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
it('blocks submission when the Reservation ID mapping is missing', async () => {
|
||||
const ctx = createContext();
|
||||
const handlers = createShippingMappingFormHandlers(ctx);
|
||||
await handlers.openShippingInventoryMappingFormForTask('SN-MAP-001');
|
||||
const message = ctx.messages.value[0];
|
||||
const payload = message.payload as { form: { reservation_id: string } };
|
||||
payload.form.reservation_id = '';
|
||||
|
||||
await handlers.applyShippingInventoryMappingForm(message);
|
||||
|
||||
expect(ctx.startChatTurn).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('请先选择内部料号列、Reservation ID 列与可用数量列');
|
||||
});
|
||||
});
|
||||
@@ -1,174 +0,0 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMappingForm.ts
|
||||
* 用途:管理库存列映射表单的打开、提交和重新上传交互。
|
||||
* 依赖:shipping.api、shippingMapping、chat.types、Vue nextTick。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 schema preview 渲染成聊天卡片,并把表单提交回后端映射接口。
|
||||
*/
|
||||
import { nextTick } from 'vue';
|
||||
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
|
||||
import { buildShippingApplyMappingTurn } from './shippingTurnActions';
|
||||
import { getShippingInventoryMappingPayload } from './shippingMapping';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingMappingFormContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
chatScrollContainer: Ref<HTMLElement | null>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
|
||||
pendingShippingUploadTaskId: Ref<string>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
||||
currentAgentId: import('vue').ComputedRef<number>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建库存列映射表单处理器。
|
||||
*
|
||||
* 核心逻辑:按任务号打开或复用映射卡片,提交 map_json 到后端,并在成功后刷新动作按钮。
|
||||
* @param ctx - 库存映射表单上下文
|
||||
* @returns 打开、应用和重传库存映射表单的处理函数
|
||||
*/
|
||||
export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContext) {
|
||||
const scrollToLastShippingInventoryMapping = async (): Promise<boolean> => {
|
||||
const container = ctx.chatScrollContainer.value;
|
||||
if (!container) return false;
|
||||
let idx = -1;
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
if ((ctx.messages.value[i] as ChatMessage)?.type === 'shipping-inventory-mapping') {
|
||||
idx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (idx < 0) return false;
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
const el = container.querySelector(`[data-msg-index="${idx}"]`) as HTMLElement | null;
|
||||
if (!el) return false;
|
||||
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
return true;
|
||||
};
|
||||
|
||||
const openShippingInventoryMappingFormForTask = async (taskId: string): Promise<boolean> => {
|
||||
const id = String(taskId || '').trim().toUpperCase();
|
||||
if (!id) return false;
|
||||
const existingIdx = (() => {
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const chatMsg = ctx.messages.value[i] as ChatMessage;
|
||||
if (chatMsg?.type !== 'shipping-inventory-mapping') continue;
|
||||
const payload = getShippingInventoryMappingPayload(chatMsg);
|
||||
if (payload?.taskId?.trim().toUpperCase() === id) return i;
|
||||
}
|
||||
return -1;
|
||||
})();
|
||||
if (existingIdx >= 0) {
|
||||
return scrollToLastShippingInventoryMapping();
|
||||
}
|
||||
const schemaPreview = ctx.shippingInventorySchemaPreviewCache.value[id];
|
||||
if (!schemaPreview || typeof schemaPreview !== 'object') {
|
||||
ctx.msg.warning('未找到表头预览,请重新上传库存文件后再点击“修改映射”');
|
||||
return false;
|
||||
}
|
||||
const detail = await getWorkspaceShippingTask(id).catch(() => null);
|
||||
const rawLines = Array.isArray((detail as { lines?: unknown[] } | null)?.lines)
|
||||
? (detail as { lines: unknown[] }).lines
|
||||
: [];
|
||||
const partNumbers = [...new Set(
|
||||
rawLines
|
||||
.map((line) => String((line as Record<string, unknown>)?.part_number || '').trim())
|
||||
.filter(Boolean),
|
||||
)].slice(0, 40);
|
||||
const suggested = (schemaPreview as { suggested_mapping?: Record<string, string> }).suggested_mapping || {};
|
||||
const mappingMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'shipping-inventory-mapping',
|
||||
content: [
|
||||
'请用下拉框选择库存列映射(必须从表头中选择)。',
|
||||
`任务编号:${id}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
payload: {
|
||||
taskId: id,
|
||||
schema_preview: schemaPreview,
|
||||
order: { line_count: rawLines.length, part_numbers: partNumbers },
|
||||
form: {
|
||||
part_number: String(suggested?.part_number || '').trim(),
|
||||
available_qty: String(suggested?.available_qty || '').trim(),
|
||||
reservation_id: String(suggested?.reservation_id || '').trim(),
|
||||
},
|
||||
applying: false,
|
||||
} as ShippingInventoryMappingFormPayload,
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(mappingMsg);
|
||||
await ctx.saveLocalMessageToBackend(mappingMsg);
|
||||
await scrollToLastShippingInventoryMapping();
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyShippingInventoryMappingForm = async (msgObj: ChatMessage) => {
|
||||
const payload = getShippingInventoryMappingPayload(msgObj);
|
||||
if (!payload) return;
|
||||
if (payload.applying) return;
|
||||
const taskId = String(payload.taskId || '').trim();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号');
|
||||
return;
|
||||
}
|
||||
const mapping: Record<string, string> = {
|
||||
part_number: String(payload.form?.part_number || '').trim(),
|
||||
available_qty: String(payload.form?.available_qty || '').trim(),
|
||||
reservation_id: String(payload.form?.reservation_id || '').trim(),
|
||||
};
|
||||
if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) {
|
||||
ctx.msg.warning('请先选择内部料号列、Reservation ID 列与可用数量列');
|
||||
return;
|
||||
}
|
||||
payload.applying = true;
|
||||
try {
|
||||
const turn = buildShippingApplyMappingTurn(taskId, mapping);
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'form_submit',
|
||||
displayText: turn.displayText,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
refs: turn.refs,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async () => {
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!ok) ctx.msg.warning('应用映射失败');
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '应用映射失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
} finally {
|
||||
payload.applying = false;
|
||||
await ctx.saveLocalMessageToBackend(msgObj);
|
||||
}
|
||||
};
|
||||
|
||||
const reuploadShippingInventoryFromMappingForm = (msgObj: ChatMessage) => {
|
||||
const payload = getShippingInventoryMappingPayload(msgObj);
|
||||
if (!payload) return;
|
||||
const taskId = String(payload.taskId || '').trim();
|
||||
if (!taskId) return;
|
||||
ctx.pendingShippingUploadTaskId.value = taskId;
|
||||
ctx.shippingInventoryPickerRef.value?.click();
|
||||
};
|
||||
|
||||
return {
|
||||
openShippingInventoryMappingFormForTask,
|
||||
applyShippingInventoryMappingForm,
|
||||
reuploadShippingInventoryFromMappingForm,
|
||||
};
|
||||
}
|
||||
@@ -38,7 +38,6 @@ const createContext = (
|
||||
getActiveShippingBatchNo: () => 'BATCH-001',
|
||||
messages: ref([]),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
|
||||
openShippingInventoryPicker: vi.fn((_taskId?: string) => true),
|
||||
openShippingNoticePicker: vi.fn((_taskId?: string) => true),
|
||||
executeShippingDecision: vi.fn(async () => true),
|
||||
|
||||
@@ -20,7 +20,6 @@ export interface ShippingMenuHandlerContext {
|
||||
getActiveShippingBatchNo: () => string;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||||
openShippingInventoryPicker: (taskId?: string) => boolean;
|
||||
openShippingNoticePicker: (taskId?: string) => boolean;
|
||||
openShippingCustomerDialog: (taskId: string) => Promise<void>;
|
||||
@@ -208,15 +207,6 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone'));
|
||||
return;
|
||||
}
|
||||
if (action.id === 'edit_inventory_mapping') {
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
await ctx.openShippingInventoryMappingFormForTask(taskId);
|
||||
return;
|
||||
}
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
ctx.openShippingInventoryPicker(resolveTaskId());
|
||||
return;
|
||||
@@ -225,10 +215,6 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
ctx.openShippingNoticePicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id === 'paste_inventory_json') {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||||
return;
|
||||
}
|
||||
if (action.id === 'reparse_inventory') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
const taskId = resolveTaskId();
|
||||
|
||||
@@ -82,6 +82,40 @@ describe('useChatShippingSendHandler', () => {
|
||||
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
|
||||
});
|
||||
|
||||
it('keeps a spreadsheet pending until the user explicitly declares it as inventory', async () => {
|
||||
const attachment = {
|
||||
id: 'spreadsheet', kind: 'local' as const,
|
||||
file: new File(['sheet'], 'unknown.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
|
||||
type: 'document' as const, uploadStatus: 'waiting' as const, uploadProgress: 0,
|
||||
};
|
||||
const ctx = createContext({ attachments: ref([attachment]) });
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.handleShippingAutoUploadFile).not.toHaveBeenCalled();
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeSpreadsheetIntentRequired');
|
||||
expect(ctx.attachments.value).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('routes a declared xls spreadsheet to the isolated temporary inventory path', async () => {
|
||||
const attachment = {
|
||||
id: 'legacy-spreadsheet', kind: 'local' as const,
|
||||
file: new File(['sheet'], 'inventory.xls', { type: 'application/vnd.ms-excel' }),
|
||||
type: 'document' as const, uploadStatus: 'waiting' as const, uploadProgress: 0,
|
||||
};
|
||||
const ctx = createContext({ attachments: ref([attachment]), shippingAutoFlowRequested: ref(false) });
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow('这是库存文件,请分析', '这是库存文件,请分析', '这是库存文件,请分析');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.handleShippingAutoUploadFile).toHaveBeenCalledWith(attachment.file);
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
|
||||
const completionOrder: string[] = [];
|
||||
const attachment = {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingSendHandler.ts
|
||||
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本、列映射和附件自动流程。
|
||||
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。
|
||||
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本和附件自动流程。
|
||||
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingDownload、chat.types。
|
||||
* 逻辑:已预处理 Intake 通过普通聊天接口进入现有 Dify Chatflow;其他业务动作经 Chat Turn / handleShippingMenuAction。
|
||||
*/
|
||||
import {
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
getWorkspaceShippingTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||||
import { buildShippingApplyMappingTurn, buildShippingSwitchFocusTurn } from './shippingTurnActions';
|
||||
import { buildShippingSwitchFocusTurn } from './shippingTurnActions';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import {
|
||||
isShippingDownloadExcelIntent,
|
||||
@@ -17,10 +17,9 @@ import {
|
||||
isShippingInventoryUploadIntent,
|
||||
isShippingManualUploadIntent,
|
||||
parseShippingTaskSwitchIntent,
|
||||
parseShippingColumnMappingFromText,
|
||||
} from './shippingIntents';
|
||||
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
|
||||
import { classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import { isShippingSpreadsheetFile, isTemporaryInventoryDeclaration } from './shippingUploadPrompt';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
|
||||
import type { SendMessageLifecycleHooks } from '../composables/useChat';
|
||||
@@ -52,7 +51,7 @@ export interface ShippingSendHandlerContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
@@ -270,7 +269,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
|
||||
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
|
||||
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
|
||||
if (ctx.isShippingNoticeBatchSubmitting?.()) {
|
||||
@@ -285,8 +283,15 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
ctx.msg.warning('当前仅支持本地附件触发自动流程');
|
||||
return true;
|
||||
}
|
||||
const kind = classifyShippingUploadFile(first.file, extractExt);
|
||||
if (kind === 'inventory') {
|
||||
if (isShippingSpreadsheetFile(first.file, extractExt)) {
|
||||
if (!isTemporaryInventoryDeclaration(trimmed)) {
|
||||
// 仅附件或自动建议时必须先澄清;有其他明确文本则交回普通对话,不把表格擅自归类。
|
||||
if (!trimmed || requestedAutoFlow) {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeSpreadsheetIntentRequired'));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
ctx.attachments.value = [];
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (localFiles.length > 1) {
|
||||
@@ -300,6 +305,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
|
||||
if (!trimmed || requestedAutoFlow) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
@@ -355,9 +361,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (menuChoice === 'upload') {
|
||||
if (ctx.openShippingInventoryPicker()) return true;
|
||||
} else if (menuChoice === 'paste') {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||||
return true;
|
||||
} else if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
|
||||
const spec = SHIPPING_MENU_ACTION_SPECS[menuChoice];
|
||||
await ctx.executeShippingDecision(menuChoice, spec?.label || spec?.message || menuChoice);
|
||||
@@ -372,34 +375,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (await ctx.executeShippingDecision(shippingDecision, content.trim())) return true;
|
||||
}
|
||||
if (assistantCtx.includes('schema_preview') || assistantCtx.includes('列映射') || assistantCtx.includes('字段对齐')) {
|
||||
const mapping = parseShippingColumnMappingFromText(content);
|
||||
if (mapping) {
|
||||
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 = [];
|
||||
const turn = buildShippingApplyMappingTurn(taskId, mapping);
|
||||
await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'form_submit',
|
||||
displayText: `${content.trim()}\n任务编号:${taskId}`,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
refs: turn.refs,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async () => {
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (isShippingManualUploadIntent(content)) {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
@@ -415,6 +390,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
if (isShippingInventoryUploadIntent(content, assistantCtx)) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (ctx.openShippingInventoryPicker()) return true;
|
||||
return true;
|
||||
}
|
||||
if (isShippingGenerateExcelIntent(content)) {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
|
||||
@@ -14,8 +14,8 @@ import {
|
||||
type ShippingUploadHandlerContext,
|
||||
} from './useChatShippingUploadHandler';
|
||||
|
||||
const { createWorkspaceShippingTask } = vi.hoisted(() => ({
|
||||
createWorkspaceShippingTask: vi.fn(),
|
||||
const { uploadFileAsset } = vi.hoisted(() => ({
|
||||
uploadFileAsset: vi.fn(),
|
||||
}));
|
||||
|
||||
const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
|
||||
@@ -25,8 +25,8 @@ const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
createWorkspaceShippingTask,
|
||||
vi.mock('@/shared/api/file-assets.api', () => ({
|
||||
uploadFileAsset,
|
||||
}));
|
||||
|
||||
vi.mock('./shippingNoticeBatchIdempotency', () => ({
|
||||
@@ -52,18 +52,18 @@ const createContext = (
|
||||
shippingBatchTasks: ref([]),
|
||||
shippingInventorySelectionActive: ref(false),
|
||||
shippingInventorySelectionTaskId: ref(''),
|
||||
shippingInventorySchemaPreviewCache: ref({}),
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
startChatTurn: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn() },
|
||||
t: (key: string) => key,
|
||||
sendTemporaryInventoryMessage: vi.fn(async () => undefined),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingUploadHandler', () => {
|
||||
beforeEach(() => {
|
||||
createWorkspaceShippingTask.mockReset();
|
||||
uploadFileAsset.mockReset();
|
||||
computeNoticeFilesContentFingerprint.mockReset();
|
||||
computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
|
||||
const content = await files[0]?.text();
|
||||
@@ -72,6 +72,34 @@ describe('useChatShippingUploadHandler', () => {
|
||||
resetShippingNoticeBatchSubmitStateForTests();
|
||||
});
|
||||
|
||||
it('stores an explicitly declared conversation inventory Excel as a temporary asset without creating a shipping task', async () => {
|
||||
uploadFileAsset.mockResolvedValue({ asset_no: 'FAS-TEMP-001' });
|
||||
const sendTemporaryInventoryMessage = vi.fn(async () => undefined);
|
||||
const ctx = createContext({ sendTemporaryInventoryMessage });
|
||||
const { handleShippingAutoUploadFile } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['inventory'], 'inventory.xlsx', {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
});
|
||||
|
||||
await handleShippingAutoUploadFile(file);
|
||||
|
||||
expect(uploadFileAsset).toHaveBeenCalledWith(file);
|
||||
expect(sendTemporaryInventoryMessage).toHaveBeenCalledWith('FAS-TEMP-001', 'inventory.xlsx');
|
||||
});
|
||||
|
||||
it('accepts a legacy xls inventory file for the isolated temporary upload path', async () => {
|
||||
uploadFileAsset.mockResolvedValue({ asset_no: 'FAS-TEMP-XLS' });
|
||||
const sendTemporaryInventoryMessage = vi.fn(async () => undefined);
|
||||
const ctx = createContext({ sendTemporaryInventoryMessage });
|
||||
const { handleShippingAutoUploadFile } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['legacy inventory'], 'inventory.xls', { type: 'application/vnd.ms-excel' });
|
||||
|
||||
await handleShippingAutoUploadFile(file);
|
||||
|
||||
expect(uploadFileAsset).toHaveBeenCalledWith(file);
|
||||
expect(sendTemporaryInventoryMessage).toHaveBeenCalledWith('FAS-TEMP-XLS', 'inventory.xls');
|
||||
});
|
||||
|
||||
it('opens inventory picker for explicit taskId instead of current active task', () => {
|
||||
const inventoryClick = vi.fn();
|
||||
const ctx = createContext({
|
||||
@@ -86,6 +114,22 @@ describe('useChatShippingUploadHandler', () => {
|
||||
expect(inventoryClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uploads a task-selected inventory file through the formal task Chat Turn, not the temporary path', async () => {
|
||||
const ctx = createContext({ pendingShippingUploadTaskId: ref('SN-TASK-001') });
|
||||
const { handleShippingInventorySelected } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['inventory'], 'task-inventory.xls', { type: 'application/vnd.ms-excel' });
|
||||
const event = { target: { files: [file], value: 'chosen' } } as unknown as Event;
|
||||
|
||||
await handleShippingInventorySelected(event);
|
||||
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
|
||||
actionType: 'shipping.upload_inventory',
|
||||
payload: { task_no: 'SN-TASK-001' },
|
||||
files: [file],
|
||||
}));
|
||||
expect(ctx.sendTemporaryInventoryMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('replaces notice on locked pending task via Chat Turn', async () => {
|
||||
const ctx = createContext({
|
||||
pendingShippingNoticeTaskId: ref('SN-TARGET-200'),
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingUploadHandler.ts
|
||||
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
|
||||
* 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。
|
||||
* 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE;待重试幂等键绑定 conversation_id。
|
||||
* 依赖:shipping.api、file-assets.api、shippingUploadPrompt、shipping 常量、chat.types。
|
||||
* 逻辑:发货通知建批和单票覆盖经 Chat Turn;对话上传库存文件先成为私有临时资产,再进入 Dify 受控分析分支。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
createWorkspaceShippingTask,
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
|
||||
import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
|
||||
import { computeNoticeFilesContentFingerprint, computeNoticeIntakeNosFingerprint } from './shippingNoticeBatchIdempotency';
|
||||
import { classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
@@ -113,7 +110,6 @@ export interface ShippingUploadHandlerContext {
|
||||
shippingBatchTasks: Ref<ShippingTaskSummary[]>;
|
||||
shippingInventorySelectionActive: Ref<boolean>;
|
||||
shippingInventorySelectionTaskId: Ref<string>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
@@ -122,12 +118,13 @@ export interface ShippingUploadHandlerContext {
|
||||
getParsedIntakeNos?: () => string[];
|
||||
getSelectedCandidateNos?: () => string[];
|
||||
clearConsumedNoticeAttachments?: () => void;
|
||||
sendTemporaryInventoryMessage: (assetNo: string, fileName: string) => Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知上传处理器。
|
||||
*
|
||||
* 核心逻辑:识别附件属于发货通知还是库存文件,分别触发建单/建批或库存上传,并维护 task/batch 本地上下文。
|
||||
* 核心逻辑:通知附件触发建单/建批;临时库存文件只能由发送层在用户明确声明后调用,避免根据后缀误判业务类型。
|
||||
* @param ctx - 上传处理上下文
|
||||
* @returns 自动上传、文件选择器和建议提示相关处理函数
|
||||
*/
|
||||
@@ -138,28 +135,17 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
};
|
||||
|
||||
const runInventoryUploadChatTurn = async (taskId: string, file: File) => {
|
||||
const turn = buildShippingUploadInventoryTurn(taskId, file);
|
||||
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'upload_followup',
|
||||
displayText: turn.displayText,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
files: turn.files,
|
||||
refs: turn.refs,
|
||||
displayText: `上传库存文件:${file.name}`,
|
||||
actionType: 'shipping.upload_inventory',
|
||||
payload: { task_no: normalizedTaskId },
|
||||
files: [file],
|
||||
refs: buildShippingTurnRefs(normalizedTaskId),
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
const payload = assistantMsg.payload && typeof assistantMsg.payload === 'object'
|
||||
? assistantMsg.payload as { schema_preview?: unknown; task_no?: string }
|
||||
: {};
|
||||
const key = String(payload.task_no || taskId || '').trim().toUpperCase();
|
||||
const preview = payload.schema_preview;
|
||||
if (key && preview && typeof preview === 'object') {
|
||||
ctx.shippingInventorySchemaPreviewCache.value = {
|
||||
...ctx.shippingInventorySchemaPreviewCache.value,
|
||||
[key]: preview,
|
||||
};
|
||||
}
|
||||
syncBatchContextFromTurnMessage(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
@@ -271,25 +257,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
}
|
||||
};
|
||||
|
||||
const syncBatchContextFromNoticeResponse = (result: Record<string, unknown> | null | undefined) => {
|
||||
const batchNo = String(
|
||||
(result?.batch_no as string | undefined)
|
||||
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|
||||
|| '',
|
||||
).trim();
|
||||
const focusTaskNo = String(
|
||||
((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|
||||
|| (result?.task_id as string | undefined)
|
||||
|| '',
|
||||
).trim();
|
||||
const batchSummary = ((result?.data as { batch?: unknown } | undefined)?.batch) || null;
|
||||
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
|
||||
if (focusTaskNo) ctx.resolvedShippingTaskId.value = focusTaskNo;
|
||||
if (batchSummary && typeof batchSummary === 'object') {
|
||||
ctx.shippingBatchSummary.value = batchSummary;
|
||||
}
|
||||
};
|
||||
|
||||
const runReplaceNoticeChatTurn = async (taskId: string, file: File) => {
|
||||
const turn = buildShippingReplaceNoticeTurn(taskId, file);
|
||||
const ok = await ctx.startChatTurn({
|
||||
@@ -377,32 +344,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
};
|
||||
|
||||
const handleShippingAutoUploadFile = async (file: File) => {
|
||||
const kind = classifyShippingUploadFile(file, extractExt);
|
||||
if (kind === 'inventory') {
|
||||
let taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
const created = await createWorkspaceShippingTask({
|
||||
source_type: 'manual',
|
||||
conversation_id: String(ctx.conversationId.value || '').trim() || undefined,
|
||||
});
|
||||
syncBatchContextFromNoticeResponse(created as unknown as Record<string, unknown>);
|
||||
taskId = String(created.task_id || '').trim();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('自动创建发货任务失败');
|
||||
return;
|
||||
}
|
||||
}
|
||||
await uploadInventoryForTask(taskId, file);
|
||||
return;
|
||||
}
|
||||
const pendingNoticeTaskId = String(ctx.pendingShippingNoticeTaskId.value || '').trim().toUpperCase();
|
||||
ctx.pendingShippingNoticeTaskId.value = '';
|
||||
const targetTaskId = pendingNoticeTaskId || String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (targetTaskId) {
|
||||
await handleReplaceNoticeForCurrentTask(targetTaskId, file);
|
||||
return;
|
||||
}
|
||||
await runNoticeBatchChatTurn([file]);
|
||||
// 调用方已验证用户明确声明库存;此处只创建隔离的临时资产,绝不建单或写正式库存。
|
||||
const asset = await uploadFileAsset(file);
|
||||
await ctx.sendTemporaryInventoryMessage(asset.asset_no, file.name);
|
||||
};
|
||||
|
||||
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
|
||||
@@ -476,8 +420,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
| Extract<PendingAttachment, { kind: 'local' }>
|
||||
| undefined;
|
||||
if (!first) return '';
|
||||
const kind = classifyShippingUploadFile(first.file, extractExt);
|
||||
if (kind === 'inventory') return ctx.t('chat.shippingNoticePrompt.notice.autoInventoryAction');
|
||||
if (['xlsx', 'xls', 'csv'].includes(extractExt(first.file.name || '').toLowerCase())) {
|
||||
return ctx.t('chat.shippingNoticePrompt.notice.autoSpreadsheetAction');
|
||||
}
|
||||
return ctx.t('chat.shippingNoticePrompt.notice.autoNoticeAction');
|
||||
});
|
||||
|
||||
|
||||
@@ -6,11 +6,21 @@
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
isOrderExtractionEligibleIntake,
|
||||
resolveShippingOrderExtractionStatus,
|
||||
shouldRestoreShippingNoticeIntake,
|
||||
shouldPollShippingNoticeIntake,
|
||||
} from './useShippingNoticeIntakes';
|
||||
|
||||
describe('shipping notice order extraction state', () => {
|
||||
it('does not resubmit consumed intakes for a new order extraction turn', () => {
|
||||
expect(isOrderExtractionEligibleIntake({
|
||||
intakeNo: 'SNI-CONSUMED',
|
||||
parseStatus: 'consumed',
|
||||
parseSummary: undefined,
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
|
||||
expect(shouldPollShippingNoticeIntake({
|
||||
parseStatus: 'parsed',
|
||||
@@ -32,4 +42,14 @@ describe('shipping notice order extraction state', () => {
|
||||
expect(resolveShippingOrderExtractionStatus('extracting', 'completed')).toBe('completed');
|
||||
expect(resolveShippingOrderExtractionStatus(undefined, 'not_started')).toBe('not_started');
|
||||
});
|
||||
|
||||
it('restores only in-progress and retryable parsing attachments into the input area', () => {
|
||||
expect(shouldRestoreShippingNoticeIntake('queued')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsing')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true);
|
||||
|
||||
// Parsed files are already persisted in the user message bubble.
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed')).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('consumed')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@
|
||||
* 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。
|
||||
* 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity。
|
||||
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件;
|
||||
* 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐)。
|
||||
* 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐);会话刷新仅恢复未提交的处理中或解析失败附件。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, type Ref } from 'vue';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
@@ -34,6 +34,18 @@ const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed',
|
||||
const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']);
|
||||
const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
|
||||
|
||||
/**
|
||||
* 判断服务端 Intake 是否应恢复到输入栏。
|
||||
* AI 触发时机:无;页面刷新或重新打开会话时调用。
|
||||
* 已解析文件已作为用户消息附件固化在对话气泡中,不能再次显示在输入栏;仅恢复仍在处理中的文件和可手动重试的解析失败文件。
|
||||
* @param parseStatus - 服务端返回的预解析状态
|
||||
* @returns 是否恢复为待发送附件卡片
|
||||
*/
|
||||
export function shouldRestoreShippingNoticeIntake(parseStatus: string | null | undefined): boolean {
|
||||
const status = String(parseStatus || '').trim().toLowerCase();
|
||||
return ACTIVE_PARSE.has(status) || status === 'parse_failed';
|
||||
}
|
||||
|
||||
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
|
||||
export function shouldPollShippingNoticeIntake(
|
||||
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus'>,
|
||||
@@ -42,6 +54,15 @@ export function shouldPollShippingNoticeIntake(
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
|
||||
}
|
||||
|
||||
/** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */
|
||||
export function isOrderExtractionEligibleIntake(
|
||||
item: Pick<ShippingNoticePendingAttachment, 'intakeNo' | 'parseStatus' | 'parseSummary'>,
|
||||
): boolean {
|
||||
return item.parseStatus === 'parsed'
|
||||
&& Boolean(item.intakeNo)
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary);
|
||||
}
|
||||
|
||||
/** 保留刚点击发送的本地 extracting,直到服务端进入真实抽取状态或返回终态。 */
|
||||
export function resolveShippingOrderExtractionStatus(localStatus?: string, remoteStatus?: string | null): string | undefined {
|
||||
const local = String(localStatus || '').trim().toLowerCase();
|
||||
@@ -135,6 +156,7 @@ function mapServerCandidate(remote: ShippingNoticeCandidateResponse): ShippingNo
|
||||
fieldAdjudication: remote.field_adjudication && typeof remote.field_adjudication === 'object'
|
||||
? remote.field_adjudication
|
||||
: null,
|
||||
customerMatches: Array.isArray(remote.customer_matches) ? remote.customer_matches : [],
|
||||
businessSummary: remote.business_summary || {},
|
||||
duplicate,
|
||||
duplicateResolution: remote.duplicate_resolution
|
||||
@@ -376,12 +398,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
|
||||
const getParsedIntakeNos = () =>
|
||||
noticeAttachments.value
|
||||
.filter(
|
||||
(item) =>
|
||||
item.parseStatus === 'parsed'
|
||||
&& item.intakeNo
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
|
||||
)
|
||||
.filter(isOrderExtractionEligibleIntake)
|
||||
.map((item) => String(item.intakeNo));
|
||||
|
||||
/** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */
|
||||
@@ -420,8 +437,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
const restoreForConversation = async (conversationId?: string | null) => {
|
||||
const { items } = await listActiveShippingNoticeIntakes(conversationId);
|
||||
const restored: ShippingNoticePendingAttachment[] = items
|
||||
.filter((item) => !TERMINAL_PARSE.has(String(item.parse_status || '').toLowerCase()) || item.parse_status === 'parsed')
|
||||
.filter((item) => item.parse_status !== 'consumed')
|
||||
.filter((item) => shouldRestoreShippingNoticeIntake(item.parse_status))
|
||||
.map((item) => ({
|
||||
id: `restored_${item.intake_no}`,
|
||||
kind: 'shipping_notice' as const,
|
||||
|
||||
Reference in new issue
Block a user