refactor(shipping-notice): 统一料号字段,移除过时的 SKU 相关字段,更新相关逻辑以支持新字段命名
This commit is contained in:
1 parent
dde25344ca
commit
46eb63f5bb
111 files changed
+3116
-1250
No files matched your search
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingConversationContext {
|
||||
@@ -21,7 +22,7 @@ export interface ShippingConversationContext {
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
}
|
||||
|
||||
/** 发送菜单类消息后,若当前会话尚未出现在侧栏历史中则刷新列表 */
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 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', () => {
|
||||
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',
|
||||
'操作已完成',
|
||||
);
|
||||
|
||||
expect(text).toContain('- part_number → Supplier Sku');
|
||||
expect(text).not.toContain('- sku →');
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ export function formatShippingDecisionAssistantMessage(
|
||||
lines.push('', `当前表头:${headers.join(' | ')}`);
|
||||
}
|
||||
const mappingLines = [
|
||||
suggested.sku ? `- sku → ${suggested.sku}` : null,
|
||||
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));
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ export interface ShippingTaskSwitchIntent {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从自然语言文本解析库存列映射(sku / available_qty / reservation_id → Excel 列名)。
|
||||
* 从自然语言文本解析库存列映射(part_number / reservation_id / available_qty → Excel 列名)。
|
||||
*/
|
||||
export function parseShippingColumnMappingFromText(content: string): Record<string, string> | null {
|
||||
const raw = String(content || '').trim();
|
||||
@@ -31,7 +31,9 @@ export function parseShippingColumnMappingFromText(content: string): Record<stri
|
||||
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('sku') || left.includes('料号') || left.includes('物料')) return 'sku';
|
||||
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) {
|
||||
@@ -46,7 +48,7 @@ export function parseShippingColumnMappingFromText(content: string): Record<stri
|
||||
if (!col) continue;
|
||||
mapping[key] = col;
|
||||
}
|
||||
if (!mapping.sku || !mapping.available_qty) return null;
|
||||
if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) return null;
|
||||
return mapping;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ export function buildShippingFieldAlignmentText(payload: { data?: { field_alignm
|
||||
const invCols = (alignment as { inventory_columns?: { mapping?: Record<string, { source_column?: string }> } }).inventory_columns || {};
|
||||
const mapping = invCols.mapping || {};
|
||||
const rows: Array<[string, string]> = [
|
||||
['sku', normalizeShippingHeaderForDisplay(mapping?.sku?.source_column) || '(未识别)'],
|
||||
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别/可选)'],
|
||||
['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[] = [];
|
||||
|
||||
@@ -50,7 +50,7 @@ export const formatShortageLine = (
|
||||
t: (key: string, params?: Record<string, unknown>) => string,
|
||||
) => t('chat.shippingNoticeUi.diagnosisShortageLine', {
|
||||
index: index + 1,
|
||||
sku: line.sku || '-',
|
||||
partNumber: line.part_number || '-',
|
||||
reservationId: line.reservation_id || '-',
|
||||
required: formatShippingQty(line.required_qty),
|
||||
available: formatShippingQty(line.available_qty),
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* 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 列与可用数量列');
|
||||
});
|
||||
});
|
||||
@@ -79,9 +79,11 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
|
||||
const rawLines = Array.isArray((detail as { lines?: unknown[] } | null)?.lines)
|
||||
? (detail as { lines: unknown[] }).lines
|
||||
: [];
|
||||
const pickSku = (line: Record<string, unknown>) =>
|
||||
String(line?.sku || line?.SKU || line?.['AWS Sku'] || line?.['AWS SKU'] || '').trim();
|
||||
const skus = [...new Set(rawLines.map((line) => pickSku(line as Record<string, unknown>)).filter(Boolean))].slice(0, 40);
|
||||
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',
|
||||
@@ -93,9 +95,9 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
|
||||
payload: {
|
||||
taskId: id,
|
||||
schema_preview: schemaPreview,
|
||||
order: { line_count: rawLines.length, skus },
|
||||
order: { line_count: rawLines.length, part_numbers: partNumbers },
|
||||
form: {
|
||||
sku: String(suggested?.sku || '').trim(),
|
||||
part_number: String(suggested?.part_number || '').trim(),
|
||||
available_qty: String(suggested?.available_qty || '').trim(),
|
||||
reservation_id: String(suggested?.reservation_id || '').trim(),
|
||||
},
|
||||
@@ -120,17 +122,14 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
|
||||
return;
|
||||
}
|
||||
const mapping: Record<string, string> = {
|
||||
sku: String(payload.form?.sku || '').trim(),
|
||||
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.sku || !mapping.available_qty) {
|
||||
ctx.msg.warning('请先选择 SKU 列 与 可用数量列');
|
||||
if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) {
|
||||
ctx.msg.warning('请先选择内部料号列、Reservation ID 列与可用数量列');
|
||||
return;
|
||||
}
|
||||
if (!mapping.reservation_id) {
|
||||
delete mapping.reservation_id;
|
||||
}
|
||||
payload.applying = true;
|
||||
try {
|
||||
const turn = buildShippingApplyMappingTurn(taskId, mapping);
|
||||
|
||||
@@ -39,7 +39,7 @@ const createContext = (
|
||||
getActiveShippingTaskId: () => '',
|
||||
lastAssistantMessageContent: () => '',
|
||||
lastAssistantShippingActions: () => [],
|
||||
sendMessage: vi.fn(async () => true),
|
||||
sendMessage: vi.fn(async () => ({ accepted: true, completed: true })),
|
||||
buildFileSpecsForSend: vi.fn(async () => []),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
@@ -263,7 +263,7 @@ describe('useChatShippingSendHandler', () => {
|
||||
intakeNo: 'SNI-HANDLED-FAILURE',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
|
||||
sendMessage: vi.fn(async () => false),
|
||||
sendMessage: vi.fn(async () => ({ accepted: false, completed: false })),
|
||||
rollbackOrderExtractionStarted: rollback,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
@@ -274,4 +274,37 @@ describe('useChatShippingSendHandler', () => {
|
||||
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
|
||||
expect(ctx.loadHistory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes submitted notice attachments after acceptance even when the assistant stream fails', async () => {
|
||||
const submitted = {
|
||||
id: 'notice-accepted-error',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-ACCEPTED-ERROR',
|
||||
};
|
||||
const retained = {
|
||||
...submitted,
|
||||
id: 'notice-retained',
|
||||
originalFilename: 'other.eml',
|
||||
intakeNo: 'SNI-RETAINED',
|
||||
};
|
||||
const ctx = createContext({
|
||||
attachments: ref([submitted, retained]),
|
||||
getParsedIntakeNos: () => ['SNI-ACCEPTED-ERROR'],
|
||||
sendMessage: vi.fn(async () => ({ accepted: true, completed: false, chatLogId: 42 })),
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.rollbackOrderExtractionStarted).not.toHaveBeenCalled();
|
||||
expect(ctx.attachments.value).toEqual([retained]);
|
||||
expect(ctx.loadHistory).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ import { classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
|
||||
import type { SendMessageLifecycleHooks } from '../composables/useChat';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessageSendResult, StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
@@ -54,7 +54,7 @@ export interface ShippingSendHandlerContext {
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
@@ -251,10 +251,16 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
},
|
||||
},
|
||||
);
|
||||
if (sent === false) {
|
||||
if (!sent.accepted) {
|
||||
ctx.rollbackOrderExtractionStarted?.(intakeNos);
|
||||
return true;
|
||||
}
|
||||
const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase()));
|
||||
ctx.attachments.value = ctx.attachments.value.filter(
|
||||
(item) => item.kind !== 'shipping_notice'
|
||||
|| !item.intakeNo
|
||||
|| !submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
|
||||
);
|
||||
await ctx.loadHistory();
|
||||
} catch (e: unknown) {
|
||||
ctx.rollbackOrderExtractionStarted?.(intakeNos);
|
||||
|
||||
@@ -132,6 +132,9 @@ function mapServerCandidate(remote: ShippingNoticeCandidateResponse): ShippingNo
|
||||
? remote.field_confidence
|
||||
: {},
|
||||
evidence: Array.isArray(remote.evidence) ? remote.evidence : [],
|
||||
fieldAdjudication: remote.field_adjudication && typeof remote.field_adjudication === 'object'
|
||||
? remote.field_adjudication
|
||||
: null,
|
||||
businessSummary: remote.business_summary || {},
|
||||
duplicate,
|
||||
duplicateResolution: remote.duplicate_resolution
|
||||
@@ -282,7 +285,6 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
local.orderExtractionStatus,
|
||||
remote.order_extraction_status,
|
||||
),
|
||||
orderExtractionVersion: remote.order_extraction_version || undefined,
|
||||
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
errorCode: remote.order_extraction_error_code || remote.error_code || undefined,
|
||||
errorMessage: remote.order_extraction_error_message || remote.error_message || undefined,
|
||||
@@ -313,7 +315,6 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
intakeNo: intake.intake_no,
|
||||
parseStatus: mapServerParseStatus(intake.parse_status),
|
||||
orderExtractionStatus: intake.order_extraction_status || undefined,
|
||||
orderExtractionVersion: intake.order_extraction_version || undefined,
|
||||
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
errorCode: intake.order_extraction_error_code || intake.error_code || undefined,
|
||||
errorMessage: intake.order_extraction_error_message || intake.error_message || undefined,
|
||||
@@ -430,7 +431,6 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: mapServerParseStatus(item.parse_status),
|
||||
orderExtractionStatus: item.order_extraction_status || undefined,
|
||||
orderExtractionVersion: item.order_extraction_version || undefined,
|
||||
uploadProgress: 100,
|
||||
originalFilename: item.original_filename || item.intake_no,
|
||||
fileSize: Number(item.file_size || 0),
|
||||
|
||||
Reference in new issue
Block a user