feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa

把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-19 10:46:06 +08:00
1 parent ffc0d4a430
commit 39fe3c05f2
453 files changed
+17945 -8646

No files matched your search

+100 -100
View File
@@ -41,7 +41,7 @@ const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getA
export type ShippingInventoryReadinessCheck = {
export type ShippingOnhandReadinessCheck = {
code: string;
status: 'passed' | 'pending' | 'failed' | 'stale' | 'empty';
blocking: boolean;
@@ -49,15 +49,15 @@ export type ShippingInventoryReadinessCheck = {
evidence: Record<string, unknown>;
};
export type ShippingInventoryReadiness = {
export type ShippingOnhandReadiness = {
ready: boolean;
checks: ShippingInventoryReadinessCheck[];
checks: ShippingOnhandReadinessCheck[];
missing_requirements: string[];
};
export type ShippingInventoryConfigurationTest = {
export type ShippingOnhandConfigurationTest = {
run_no: string;
inventory_source_id: number;
source_id: number;
source_config_version: number;
rpa_profile_config_version: number;
status: 'awaiting_rpa' | 'processing' | 'completed' | 'completed_empty' | 'failed';
@@ -76,7 +76,7 @@ export type ShippingInventoryConfigurationTest = {
};
};
export type ShippingInventoryValidationBatch = {
export type ShippingOnhandValidationBatch = {
id: number;
batch_no: string;
status: 'queued' | 'running' | 'completed' | 'partial_failed' | 'failed';
@@ -85,7 +85,7 @@ export type ShippingInventoryValidationBatch = {
empty_count: number;
failed_count: number;
stale_count: number;
runs: ShippingInventoryConfigurationTest[];
runs: ShippingOnhandConfigurationTest[];
};
export type ShippingOrderExtractionDiagnosticAutoFreezePolicy = {
@@ -171,8 +171,8 @@ export const getShippingOrderExtractionHealth = (windowHours = 24) => {
};
/** 下载管理员可访问的库存快照,并保留服务端指定的原始文件名。 */
export const downloadShippingInventorySnapshot = async (snapshotId: number, fallbackName: string): Promise<void> => {
const response = await fetch(`/api/admin/shipping-notice/snapshots/${snapshotId}/download`, { headers: getAuthHeaders() });
export const downloadShippingOnhandSnapshot = async (snapshotId: number, fallbackName: string): Promise<void> => {
const response = await fetch(`/api/admin/freight-rpa/onhand/snapshots/${snapshotId}/download`, { headers: getAuthHeaders() });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blob = await response.blob();
const disposition = response.headers.get('Content-Disposition') || '';
@@ -186,18 +186,18 @@ export const downloadShippingInventorySnapshot = async (snapshotId: number, fall
};
/** 货代库存配置统一接口;敏感凭据仅能写入,服务端不会回显。 */
export const getShippingInventoryConfig = async () => Promise.all([
export const getShippingOnhandConfig = async () => Promise.all([
requestJson<unknown[]>('/api/admin/freight-rpa/rpa-profiles', auth()),
requestJson<unknown[]>('/api/admin/shipping-notice/sources', auth()),
requestJson<unknown[]>('/api/admin/shipping-notice/routing-rules', auth()),
requestJson<unknown[]>('/api/admin/shipping-notice/external-mappings', auth()),
requestJson<unknown[]>('/api/admin/shipping-notice/snapshots', auth()),
requestJson<unknown[]>('/api/admin/shipping-notice/export-records', auth()),
requestJson<unknown[]>('/api/admin/shipping-notice/parsing-profiles', auth()),
requestJson<unknown[]>('/api/admin/freight-rpa/sources', auth()),
requestJson<unknown[]>('/api/admin/freight-rpa/onhand/routing-rules', auth()),
requestJson<unknown[]>('/api/admin/freight-rpa/onhand/external-mappings', auth()),
requestJson<unknown[]>('/api/admin/freight-rpa/onhand/snapshots', auth()),
requestJson<unknown[]>('/api/admin/freight-rpa/onhand/export-records', auth()),
requestJson<unknown[]>('/api/admin/freight-rpa/onhand/parsing-profiles', auth()),
requestJson<unknown[]>('/api/admin/shipping-notice/excel-templates', auth()),
]);
export type ShippingInventoryField = {
export type ShippingOnhandField = {
id: number;
display_name: string;
description: string;
@@ -208,20 +208,20 @@ export type ShippingInventoryField = {
};
/** 管理可供不同库存文件解析方案复用的统一库存业务字段。 */
export const getShippingInventoryFields = () => requestJson<ShippingInventoryField[]>(
'/api/admin/shipping-notice/inventory-fields?include_retired=true', auth(),
export const getShippingOnhandFields = () => requestJson<ShippingOnhandField[]>(
'/api/admin/freight-rpa/onhand/fields?include_retired=true', auth(),
);
export const createShippingInventoryField = (payload: Omit<ShippingInventoryField, 'id' | 'status'>) => requestJson<ShippingInventoryField>(
'/api/admin/shipping-notice/inventory-fields', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
export const createShippingOnhandField = (payload: Omit<ShippingOnhandField, 'id' | 'status'>) => requestJson<ShippingOnhandField>(
'/api/admin/freight-rpa/onhand/fields', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
export const updateShippingInventoryField = (id: number, payload: Omit<ShippingInventoryField, 'id' | 'status'>) => requestJson<ShippingInventoryField>(
`/api/admin/shipping-notice/inventory-fields/${id}`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() },
export const updateShippingOnhandField = (id: number, payload: Omit<ShippingOnhandField, 'id' | 'status'>) => requestJson<ShippingOnhandField>(
`/api/admin/freight-rpa/onhand/fields/${id}`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() },
);
export const retireShippingInventoryField = (id: number) => requestJson<ShippingInventoryField>(
`/api/admin/shipping-notice/inventory-fields/${id}/retire`, { method: 'POST', ...jsonAuth() },
export const retireShippingOnhandField = (id: number) => requestJson<ShippingOnhandField>(
`/api/admin/freight-rpa/onhand/fields/${id}/retire`, { method: 'POST', ...jsonAuth() },
);
export const deleteShippingInventoryField = (id: number) => requestJson<void>(
`/api/admin/shipping-notice/inventory-fields/${id}`, { method: 'DELETE', ...auth() },
export const deleteShippingOnhandField = (id: number) => requestJson<void>(
`/api/admin/freight-rpa/onhand/fields/${id}`, { method: 'DELETE', ...auth() },
);
/** 上传或更新版本化发货 Excel 模板;文件仅在创建草稿时提交。 */
@@ -251,15 +251,15 @@ export const deleteShippingExcelTemplate = (id: number) => requestJson<void>(
);
/** 读取库存路由可选的已发布订单字段。 */
export const getShippingInventoryRoutingFields = () => requestJson<{
export const getShippingOnhandRoutingFields = () => requestJson<{
order_fields: Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>;
order_schema_published: boolean;
}>('/api/admin/shipping-notice/routing-fields', auth());
}>('/api/admin/freight-rpa/onhand/routing-fields', auth());
export type ShippingInventoryConfigurationCatalog = {
export type ShippingOnhandConfigurationCatalog = {
order_fields: Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>;
order_schema_published: boolean;
inventory_fields: ShippingInventoryField[];
inventory_fields: ShippingOnhandField[];
template_system_facts: string[];
template_source_kinds: Array<'order_field' | 'inventory_field' | 'system_fact' | 'constant'>;
template_row_modes: Array<'header' | 'line'>;
@@ -267,31 +267,31 @@ export type ShippingInventoryConfigurationCatalog = {
};
/** 读取 Profile 与模板结构化编辑器使用的后端权威白名单。 */
export const getShippingInventoryConfigurationCatalog = () =>
requestJson<ShippingInventoryConfigurationCatalog>(
'/api/admin/shipping-notice/configuration-catalog', auth(),
export const getShippingOnhandConfigurationCatalog = () =>
requestJson<ShippingOnhandConfigurationCatalog>(
'/api/admin/freight-rpa/onhand/configuration-catalog', auth(),
);
/** 保存和发布可复用库存解析 Profile。 */
export const saveShippingInventoryParsingProfile = (payload: Record<string, unknown>, id?: number) => requestJson<unknown>(
`/api/admin/shipping-notice/parsing-profiles${id ? `/${id}` : ''}`,
export const saveShippingOnhandParsingProfile = (payload: Record<string, unknown>, id?: number) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/parsing-profiles${id ? `/${id}` : ''}`,
{ method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
export const publishShippingInventoryParsingProfile = (id: number) => requestJson<unknown>(
`/api/admin/shipping-notice/parsing-profiles/${id}/publish`, { method: 'POST', ...jsonAuth() },
export const publishShippingOnhandParsingProfile = (id: number) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/parsing-profiles/${id}/publish`, { method: 'POST', ...jsonAuth() },
);
export const retireShippingInventoryParsingProfile = (id: number) => requestJson<unknown>(
`/api/admin/shipping-notice/parsing-profiles/${id}/retire`, { method: 'POST', ...jsonAuth() },
export const retireShippingOnhandParsingProfile = (id: number) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/parsing-profiles/${id}/retire`, { method: 'POST', ...jsonAuth() },
);
export const deleteShippingInventoryParsingProfile = (id: number) => requestJson<void>(
`/api/admin/shipping-notice/parsing-profiles/${id}`, { method: 'DELETE', ...auth() },
export const deleteShippingOnhandParsingProfile = (id: number) => requestJson<void>(
`/api/admin/freight-rpa/onhand/parsing-profiles/${id}`, { method: 'DELETE', ...auth() },
);
/** 上传库存样本,由后端分析工作表、表头、栏位样例和字段建议。 */
export const createShippingInventoryStructureAnalysis = (file: File) => {
export const createShippingOnhandStructureAnalysis = (file: File) => {
const form = new FormData();
form.set('file', file);
return requestJson<unknown>('/api/admin/shipping-notice/inventory-structure-analyses', {
return requestJson<unknown>('/api/admin/freight-rpa/onhand/structure-analyses', {
method: 'POST', body: form, ...auth(),
});
};
@@ -300,27 +300,27 @@ export const fetchMovementFields = () => requestJson<Array<{ code: string; value
'/api/admin/shipping-notice/movement-fields', auth(),
);
/** 用已分析的真实栏位创建库存文件解析方案草稿。 */
export const createShippingInventoryParsingDraftFromAnalysis = (id: number, payload: Record<string, unknown>) => requestJson<unknown>(
`/api/admin/shipping-notice/inventory-structure-analyses/${id}/create-profile-draft`,
export const createShippingOnhandParsingDraftFromAnalysis = (id: number, payload: Record<string, unknown>) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/structure-analyses/${id}/create-profile-draft`,
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 样本替换先读取后端结构差异;管理员确认前不会改动草稿的审计证据。 */
export const previewShippingInventorySampleReplacement = (profileId: number, analysisId: number, payload: Record<string, unknown> = {}) => requestJson<unknown>(
`/api/admin/shipping-notice/parsing-profiles/${profileId}/sample-replacement-preview/${analysisId}`,
export const previewShippingOnhandSampleReplacement = (profileId: number, analysisId: number, payload: Record<string, unknown> = {}) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/parsing-profiles/${profileId}/sample-replacement-preview/${analysisId}`,
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 确认复用后端推荐的已发布解析方案;库存站点绑定仍由后续测试流程确认。 */
export const adoptShippingInventoryParsingProfile = (analysisId: number, profileId: number) => requestJson<unknown>(
`/api/admin/shipping-notice/inventory-structure-analyses/${analysisId}/adopt-profile`,
export const adoptShippingOnhandParsingProfile = (analysisId: number, profileId: number) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/structure-analyses/${analysisId}/adopt-profile`,
{ method: 'POST', body: JSON.stringify({ profile_id: profileId }), ...jsonAuth() },
);
/** 列出已确认、可由管理员沉淀为库存文件解析方案草稿的对话临时库存会话。 */
export const listShippingTemporaryInventorySessions = () => requestJson<unknown>(
'/api/admin/shipping-notice/temporary-inventory-sessions', auth(),
/** 列出已确认、可由管理员沉淀为库存文件解析方案草稿的对话临时库存会话。路径留在 /api/admin/shipping-notice/temporary-onhand-sessions。 */
export const listShippingTemporaryOnhandSessions = () => requestJson<unknown>(
'/api/admin/shipping-notice/temporary-onhand-sessions', auth(),
);
/** 使用临时会话锁定的结构和映射创建草稿;前端提交的字段映射不会被接受。 */
/** 使用临时会话锁定的结构和映射创建草稿;前端提交的字段映射不会被接受。路径为 /api/admin/shipping-notice/temporary-onhand-sessions/<sessionNo>/create-profile-draft。 */
export const createShippingParsingDraftFromTemporarySession = (sessionNo: string, payload: Record<string, unknown>) => requestJson<unknown>(
`/api/admin/shipping-notice/temporary-inventory-sessions/${encodeURIComponent(sessionNo)}/create-profile-draft`,
`/api/admin/shipping-notice/temporary-onhand-sessions/${encodeURIComponent(sessionNo)}/create-profile-draft`,
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
@@ -334,100 +334,100 @@ export const deleteShippingRpaProfile = (id: number) => requestJson<void>(
);
/** 保存 Inventory Source,服务端校验其 Driver 与 Profile 一致。 */
export const saveShippingInventorySource = (payload: Record<string, unknown>, id?: number) => requestJson<unknown>(
`/api/admin/shipping-notice/sources${id ? `/${id}` : ''}`,
export const saveShippingOnhandSource = (payload: Record<string, unknown>, id?: number) => requestJson<unknown>(
`/api/admin/freight-rpa/sources${id ? `/${id}` : ''}`,
{ method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 读取/保存站点独立收料配置;严禁通过库存站点保存接口夹带这些字段。 */
/** 读取/保存站点独立入站报表配置(/freight-rpa/sources/<id>/inbound-report-config);严禁通过库存站点保存接口夹带这些字段。 */
export const getShippingReceiptReportConfig = (sourceId: number) => requestJson<Record<string, unknown> | null>(
`/api/admin/shipping-notice/sources/${sourceId}/receipt-report-config`, auth(),
`/api/admin/freight-rpa/sources/${sourceId}/inbound-report-config`, auth(),
);
export const saveShippingReceiptReportConfig = (sourceId: number, payload: Record<string, unknown>) => requestJson<Record<string, unknown>>(
`/api/admin/shipping-notice/sources/${sourceId}/receipt-report-config`,
`/api/admin/freight-rpa/sources/${sourceId}/inbound-report-config`,
{ method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 直接绑定停用库存站点到已发布解析方案;服务端自动写入操作审计。 */
export const bindShippingInventorySourceParsingProfile = (id: number, payload: { parsing_profile_id: number }) => requestJson<unknown>(
`/api/admin/shipping-notice/sources/${id}/bind-parsing-profile`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
export const bindShippingOnhandSourceParsingProfile = (id: number, payload: { parsing_profile_id: number }) => requestJson<unknown>(
`/api/admin/freight-rpa/sources/${id}/bind-parsing-profile`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 原子批量绑定已发布解析方案;任一站点不合格时整批拒绝,避免部分更新。 */
export const bulkBindShippingInventorySourceParsingProfile = (payload: { source_ids: number[]; parsing_profile_id: number }) => requestJson<unknown[]>(
'/api/admin/shipping-notice/sources/bulk-bind-parsing-profile', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
export const bulkBindShippingOnhandSourceParsingProfile = (payload: { source_ids: number[]; parsing_profile_id: number }) => requestJson<unknown[]>(
'/api/admin/freight-rpa/sources/bulk-bind-parsing-profile', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 读取站点解析方案绑定的可追溯审计记录。 */
export const getShippingInventorySourceParsingBindingAudits = (id: number) => requestJson<unknown[]>(
`/api/admin/shipping-notice/sources/${id}/parsing-binding-audits`, auth(),
export const getShippingOnhandSourceParsingBindingAudits = (id: number) => requestJson<unknown[]>(
`/api/admin/freight-rpa/sources/${id}/parsing-binding-audits`, auth(),
);
export const deleteShippingInventorySource = (id: number) => requestJson<void>(
`/api/admin/shipping-notice/sources/${id}`, { method: 'DELETE', ...auth() },
export const deleteShippingOnhandSource = (id: number) => requestJson<void>(
`/api/admin/freight-rpa/sources/${id}`, { method: 'DELETE', ...auth() },
);
/** 仅在站点完成测试和必需绑定后启用正式库存运行。 */
export const activateShippingInventorySource = (id: number) => requestJson<unknown>(
`/api/admin/shipping-notice/sources/${id}/activate`, { method: 'POST', ...jsonAuth() },
export const activateShippingOnhandSource = (id: number) => requestJson<unknown>(
`/api/admin/freight-rpa/sources/${id}/activate`, { method: 'POST', ...jsonAuth() },
);
/** 停用库存站点但保留其既有配置和审计记录。 */
export const deactivateShippingInventorySource = (id: number) => requestJson<unknown>(
`/api/admin/shipping-notice/sources/${id}/deactivate`, { method: 'POST', ...jsonAuth() },
export const deactivateShippingOnhandSource = (id: number) => requestJson<unknown>(
`/api/admin/freight-rpa/sources/${id}/deactivate`, { method: 'POST', ...jsonAuth() },
);
/** 对停用库存站点发起异步 RPA 测试导出,测试文件不会进入生产库存池。 */
export const startShippingInventoryConfigurationTest = (id: number) => requestJson<ShippingInventoryConfigurationTest>(
`/api/admin/shipping-notice/sources/${id}/test-export`, { method: 'POST', ...jsonAuth() },
export const startShippingOnhandConfigurationTest = (id: number) => requestJson<ShippingOnhandConfigurationTest>(
`/api/admin/freight-rpa/sources/${id}/test-export`, { method: 'POST', ...jsonAuth() },
);
/** 查询库存站点测试导出与结构识别的后端真实状态。 */
export const getShippingInventoryConfigurationTest = (id: number, runNo: string) => requestJson<ShippingInventoryConfigurationTest>(
`/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}`, auth(),
export const getShippingOnhandConfigurationTest = (id: number, runNo: string) => requestJson<ShippingOnhandConfigurationTest>(
`/api/admin/freight-rpa/sources/${id}/test-export/${encodeURIComponent(runNo)}`, auth(),
);
/** 读取当前站点配置对应的最近测试,使刷新页面或重开抽屉时可恢复服务端真实状态。 */
export const getLatestShippingInventoryConfigurationTest = (id: number) => requestJson<ShippingInventoryConfigurationTest | null>(
`/api/admin/shipping-notice/sources/${id}/test-export/latest`, auth(),
export const getLatestShippingOnhandConfigurationTest = (id: number) => requestJson<ShippingOnhandConfigurationTest | null>(
`/api/admin/freight-rpa/sources/${id}/test-export/latest`, auth(),
);
/** 管理员确认测试结果使用的已发布解析方案,才更新停用库存站点绑定。 */
export const confirmShippingInventoryConfigurationTestProfile = (id: number, runNo: string, profileId: number) => requestJson<any>(
`/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}/confirm-profile`,
export const confirmShippingOnhandConfigurationTestProfile = (id: number, runNo: string, profileId: number) => requestJson<any>(
`/api/admin/freight-rpa/sources/${id}/test-export/${encodeURIComponent(runNo)}/confirm-profile`,
{ method: 'POST', body: JSON.stringify({ profile_id: profileId }), ...jsonAuth() },
);
/** 对已绑定发布解析方案的多个停用站点发起受控批量测试。 */
export const startShippingInventoryValidationBatch = (sourceIds: number[]) => requestJson<ShippingInventoryValidationBatch>(
'/api/admin/shipping-notice/source-validation-batches', { method: 'POST', body: JSON.stringify({ source_ids: sourceIds }), ...jsonAuth() },
export const startShippingOnhandValidationBatch = (sourceIds: number[]) => requestJson<ShippingOnhandValidationBatch>(
'/api/admin/freight-rpa/onhand/validation-batches', { method: 'POST', body: JSON.stringify({ source_ids: sourceIds }), ...jsonAuth() },
);
/** 读取批量测试进度和逐站点独立结果。 */
export const getShippingInventoryValidationBatch = (batchId: number) => requestJson<ShippingInventoryValidationBatch>(
`/api/admin/shipping-notice/source-validation-batches/${batchId}`, auth(),
export const getShippingOnhandValidationBatch = (batchId: number) => requestJson<ShippingOnhandValidationBatch>(
`/api/admin/freight-rpa/onhand/validation-batches/${batchId}`, auth(),
);
/** 恢复最近尚未结束的批量测试,供刷新页面后继续展示进度。 */
export const getLatestActiveShippingInventoryValidationBatch = () => requestJson<ShippingInventoryValidationBatch | null>(
'/api/admin/shipping-notice/source-validation-batches/latest-active', auth(),
export const getLatestActiveShippingOnhandValidationBatch = () => requestJson<ShippingOnhandValidationBatch | null>(
'/api/admin/freight-rpa/onhand/validation-batches/latest-active', auth(),
);
/** 仅重试批次内失败或已过期的站点。 */
export const retryFailedShippingInventoryValidationBatch = (batchId: number) => requestJson<ShippingInventoryValidationBatch>(
`/api/admin/shipping-notice/source-validation-batches/${batchId}/retry-failed`, { method: 'POST', ...jsonAuth() },
export const retryFailedShippingOnhandValidationBatch = (batchId: number) => requestJson<ShippingOnhandValidationBatch>(
`/api/admin/freight-rpa/onhand/validation-batches/${batchId}/retry-failed`, { method: 'POST', ...jsonAuth() },
);
/** 保存路由规则草稿;规则发布需调用独立接口以生成审计快照。 */
export const saveShippingInventoryRule = (payload: Record<string, unknown>, id?: number) => requestJson<unknown>(
`/api/admin/shipping-notice/routing-rules${id ? `/${id}` : ''}`,
export const saveShippingOnhandRule = (payload: Record<string, unknown>, id?: number) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/routing-rules${id ? `/${id}` : ''}`,
{ method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 发布草稿规则,服务端会保存不可变定义快照。 */
export const publishShippingInventoryRule = (id: number) => requestJson<unknown>(
`/api/admin/shipping-notice/routing-rules/${id}/publish`,
export const publishShippingOnhandRule = (id: number) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/routing-rules/${id}/publish`,
{ method: 'POST', ...jsonAuth() },
);
export const retireShippingInventoryRule = (id: number) => requestJson<unknown>(
`/api/admin/shipping-notice/routing-rules/${id}/retire`, { method: 'POST', ...jsonAuth() },
export const retireShippingOnhandRule = (id: number) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/routing-rules/${id}/retire`, { method: 'POST', ...jsonAuth() },
);
export const deleteShippingInventoryRule = (id: number) => requestJson<void>(
`/api/admin/shipping-notice/routing-rules/${id}`, { method: 'DELETE', ...auth() },
export const deleteShippingOnhandRule = (id: number) => requestJson<void>(
`/api/admin/freight-rpa/onhand/routing-rules/${id}`, { method: 'DELETE', ...auth() },
);
/** 保存精确或 Source 默认外部系统映射。 */
export const saveShippingInventoryExternalMapping = (payload: Record<string, unknown>, id?: number) => requestJson<unknown>(
`/api/admin/shipping-notice/external-mappings${id ? `/${id}` : ''}`,
export const saveShippingOnhandExternalMapping = (payload: Record<string, unknown>, id?: number) => requestJson<unknown>(
`/api/admin/freight-rpa/onhand/external-mappings${id ? `/${id}` : ''}`,
{ method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
export const deleteShippingInventoryExternalMapping = (id: number) => requestJson<void>(
`/api/admin/shipping-notice/external-mappings/${id}`, { method: 'DELETE', ...auth() },
export const deleteShippingOnhandExternalMapping = (id: number) => requestJson<void>(
`/api/admin/freight-rpa/onhand/external-mappings/${id}`, { method: 'DELETE', ...auth() },
);
export const listAdminTrainingConfigs = () =>
requestJson<TrainingConfig[]>('/api/admin/training-configs', auth());
@@ -46,7 +46,7 @@ const iconMap: Record<AdminModuleId, Component> = {
integration_connector: Cable,
transfer_types: ArrowLeftRight,
reports: BarChart2,
shipping_inventory: PackageSearch,
freight_rpa: PackageSearch,
};
const visibleModules = computed(() =>
@@ -55,7 +55,7 @@ const visibleModules = computed(() =>
// 调拨类型(transfer_types)已移入货代管理子菜单(路由规则之下),不再作为顶级入口渲染
const standardModules = computed(() =>
visibleModules.value.filter((item) => item.id !== 'wecom' && item.id !== 'shipping_inventory' && item.id !== 'transfer_types'),
visibleModules.value.filter((item) => item.id !== 'wecom' && item.id !== 'freight_rpa' && item.id !== 'transfer_types'),
);
const isModuleActive = (moduleId: AdminModuleId): boolean =>
@@ -65,7 +65,7 @@ const isReportsActive = computed(() => route.meta.adminModule === 'reports');
const isWecomActive = computed(() => route.meta.adminModule === 'wecom');
// 货代管理激活态涵盖调拨类型:进入该子页时父菜单高亮并自动展开
const isShippingActive = computed(() => (
route.meta.adminModule === 'shipping_inventory' || route.meta.adminModule === 'transfer_types'
route.meta.adminModule === 'freight_rpa' || route.meta.adminModule === 'transfer_types'
));
const shippingGroups = computed(() => [...new Set(SHIPPING_CONFIG_SUB_MODULE_METAS.map((item) => item.groupKey))]);
@@ -210,7 +210,7 @@ watch(
</div>
</div>
<div v-if="config.admin.modules.shipping_inventory !== false" class="flex flex-col flex-shrink-0">
<div v-if="config.admin.modules.freight_rpa !== false" class="flex flex-col flex-shrink-0">
<button
type="button"
class="admin-nav-btn group justify-between"
@@ -16,7 +16,7 @@ export interface AdminModuleMeta {
export interface ShippingConfigSubModuleMeta {
id: ShippingConfigSubModuleId;
routeName:
| 'AdminShippingInventory'
| 'AdminFreightRpa'
| 'AdminShippingFieldAssets'
| 'AdminShippingOrderSchema'
| 'AdminShippingIdentityRules'
@@ -36,13 +36,13 @@ export interface ShippingConfigSubModuleMeta {
| 'shipping-order-document-profiles'
| 'transfer-types';
labelKey: string;
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit';
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.freightRpaManagement' | 'admin.nav.shippingRunAudit';
query?: { section: 'parsing' | 'profiles' | 'sources' | 'mappings' | 'rules' | 'templates' | 'snapshots' | 'exports' };
}
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
'dashboard', 'agents', 'users', 'departments', 'announcements', 'questions', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports', 'training_config', 'integration_connector', 'transfer_types'
'dashboard', 'agents', 'users', 'departments', 'announcements', 'questions', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'freight_rpa', 'procurement_contract', 'reports', 'training_config', 'integration_connector', 'transfer_types'
]);
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
@@ -52,7 +52,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
{ id: 'agents', routeName: 'AdminAgents', path: 'agents', labelKey: 'admin.nav.agents', configKey: 'agents' },
{ id: 'knowledge_base', routeName: 'AdminKnowledgeBase', path: 'knowledge-base', labelKey: 'admin.nav.knowledgeBase', configKey: 'knowledge_base' },
{ id: 'schedules', routeName: 'AdminSchedules', path: 'schedules', labelKey: 'admin.nav.schedules', configKey: 'schedules' },
{ id: 'shipping_inventory', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingConfig', configKey: 'shipping_inventory' },
{ id: 'freight_rpa', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.nav.shippingConfig', configKey: 'freight_rpa' },
{ id: 'announcements', routeName: 'AdminAnnouncements', path: 'announcements', labelKey: 'admin.nav.announcements', configKey: 'announcements' },
{ id: 'questions', routeName: 'AdminQuestions', path: 'questions', labelKey: 'admin.nav.questions', configKey: 'questions' },
{ id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' },
@@ -79,18 +79,18 @@ export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'inventory_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.parsingProfiles', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'parsing' } },
{ id: 'connections', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.connections', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'profiles' } },
{ id: 'inventory_sites', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.sources', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'sources' } },
{ id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } },
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
{ id: 'inventory_fields', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.parsingProfiles', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'parsing' } },
{ id: 'connections', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.connections', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'profiles' } },
{ id: 'inventory_sites', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.sources', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'sources' } },
{ id: 'warehouse_mappings', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.externalMappings', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'mappings' } },
{ id: 'routing_rules', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.rules', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'rules' } },
// 调拨类型(原顶级入口「在途调拨类型」移入货代管理,挂在路由规则之下;路由独立注册于 AdminTransferTypes)
{ id: 'transfer_types', routeName: 'AdminTransferTypes', path: 'transfer-types', labelKey: 'admin.nav.transferTypes', groupKey: 'admin.nav.shippingInventoryManagement' },
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
{ id: 'transfer_types', routeName: 'AdminTransferTypes', path: 'transfer-types', labelKey: 'admin.nav.transferTypes', groupKey: 'admin.nav.freightRpaManagement' },
{ id: 'shipping_templates', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.excelTemplates', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'templates' } },
{ id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
{ id: 'inventory_snapshots', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
{ id: 'export_records', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
];
export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
@@ -102,7 +102,10 @@ export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
'issue_analysis',
];
export const LEGACY_MODULE_QUERY_TO_PATH: Record<string, string> = {};
/** 旧 /admin?module=shipping_inventory 落到货代 RPA 页 /admin/shipping-notice,不再拼出死路径。 */
export const LEGACY_MODULE_QUERY_TO_PATH: Record<string, string> = {
shipping_inventory: 'shipping-notice',
};
export const adminModulePath = (moduleId: AdminModuleId | string): string => {
if (moduleId === 'reports') return '/admin/reports';
@@ -1,10 +1,10 @@
/**
* features/admin/modules/shipping-inventory/movementFieldLabels.spec.ts
* features/admin/modules/freight-rpa/movementFieldLabels.spec.ts
* 用途:锁定库存解析管理页「标准异动字段」标签映射与后端 MOVEMENT_FIELDS 契约一致。
* 依赖:vitest、四语言 locales 下各 admin.json。
* 逻辑:页面用 `movementFields.${item.code}` 动态取标签,code 集合由后端目录接口
* (movement_contract.MOVEMENT_FIELDS)在运行期下发,静态 i18n 工具查不出缺键——
* 后端扩字段而语言包未同步时,界面会把原始 key(如 admin.shippingInventory.
* 后端扩字段而语言包未同步时,界面会把原始 key(如 admin.freightRpa.
* movementFields.order_type)直接渲染给用户(2026-10-15 实测回归)。
*/
@@ -23,10 +23,10 @@ const BACKEND_MOVEMENT_FIELD_CODES = [
] as const;
const LABEL_MAPS: Record<string, Record<string, string>> = {
'zh-CN': (zhCN as Record<string, any>).shippingInventory.movementFields,
'zh-TW': (zhTW as Record<string, any>).shippingInventory.movementFields,
en: (en as Record<string, any>).shippingInventory.movementFields,
th: (th as Record<string, any>).shippingInventory.movementFields,
'zh-CN': (zhCN as Record<string, any>).freightRpa.movementFields,
'zh-TW': (zhTW as Record<string, any>).freightRpa.movementFields,
en: (en as Record<string, any>).freightRpa.movementFields,
th: (th as Record<string, any>).freightRpa.movementFields,
};
describe('movementFieldLabels', () => {
@@ -1,5 +1,5 @@
/**
* features/admin/modules/shipping-inventory/movementParsingProfileForm.spec.ts
* features/admin/modules/freight-rpa/movementParsingProfileForm.spec.ts
* 用途:覆盖收料异动解析规则映射的组装边界。
* 依赖:movementParsingProfileForm、vitest。
* 逻辑:标准异动字段是只读领域契约——映射键必须是契约 code,必填字段缺失要阻断保存。
@@ -1,5 +1,5 @@
/**
* features/admin/modules/shipping-inventory/movementParsingProfileForm.ts
* features/admin/modules/freight-rpa/movementParsingProfileForm.ts
* 用途:组装入站解析规则(purpose='inbound')的标准异动字段映射载荷。
* 依赖:无外部依赖。
* 逻辑:标准异动字段目录由后端 /admin/shipping-notice/movement-fields 只读下发,
@@ -1,5 +1,5 @@
/**
* features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts
* features/admin/modules/freight-rpa/receiptReportConfigForm.spec.ts
* 用途:覆盖收料报表表单的独立载荷边界。
* 依赖:receiptReportConfigForm、vitest。
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口;
@@ -1,8 +1,8 @@
/**
* features/admin/modules/shipping-inventory/receiptReportConfigForm.ts
* features/admin/modules/freight-rpa/receiptReportConfigForm.ts
* 用途:构建独立收料报表配置的受限保存载荷。
* 依赖:无外部依赖。
* 逻辑:页面仅将收料路径与查询条件提交到收料配置 API,与库存同构(查询条件可选,空=页面默认),
* 逻辑:页面仅将收料路径与查询条件提交到 /api/admin/freight-rpa/sources/<id>/inbound-report-config,与库存同构(查询条件可选,空=页面默认),
* 隔离库存站点字段;收料无独立启停字段,是否运行统一由库存站点 enabled 决定。
*/
@@ -1,20 +1,20 @@
/**
* features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts
* features/admin/modules/freight-rpa/shippingOnhandReadiness.spec.ts
* 用途:覆盖库存站点上线检查与测试恢复的纯状态映射。
* 依赖:shippingInventoryReadiness、vitest。
* 依赖:shippingOnhandReadiness、vitest。
* 逻辑:防止页面把已完成项目显示为待办,或持续轮询服务端已结束的测试任务。
*/
import { describe, expect, it } from 'vitest';
import type { ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
import { normaliseInventoryReportPath } from './shippingInventorySourceForm';
import type { ShippingOnhandReadinessCheck } from '@/features/admin/api/admin.api';
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingOnhandReadiness';
import { normaliseInventoryReportPath } from './shippingOnhandSourceForm';
const check = (status: ShippingInventoryReadinessCheck['status'], blocking: boolean): ShippingInventoryReadinessCheck => ({
const check = (status: ShippingOnhandReadinessCheck['status'], blocking: boolean): ShippingOnhandReadinessCheck => ({
code: 'configuration_test', status, blocking, action: 'run_configuration_test', evidence: {},
});
describe('shippingInventoryReadiness', () => {
describe('shippingOnhandReadiness', () => {
it('keeps stale checks actionable and visually distinct from ordinary pending work', () => {
// 关键断言:配置已变更的测试不能被渲染成普通待办,管理员必须重新测试。
expect(readinessMarkerKind('stale')).toBe('attention');
@@ -1,11 +1,11 @@
/**
* features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts
* features/admin/modules/freight-rpa/shippingOnhandReadiness.ts
* 用途:归一库存站点上线检查与配置测试的前端展示状态。
* 依赖:admin.api 中的 Inventory Readiness/Test 类型。
* 逻辑:ShippingInventoryPage 调用本文件决定测试轮询、步骤标记和推荐动作;后端仍是门禁真相源。
* 依赖:admin.api 的 ShippingOnhandReadinessCheck / ShippingOnhandConfigurationTest。
* 逻辑:FreightRpaPage 调用本文件决定测试轮询、步骤标记和推荐动作;后端仍是门禁真相源。
*/
import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
import type { ShippingOnhandConfigurationTest, ShippingOnhandReadinessCheck } from '@/features/admin/api/admin.api';
export type ReadinessMarker = 'complete' | 'attention' | 'pending';
@@ -15,7 +15,7 @@ export type ReadinessMarker = 'complete' | 'attention' | 'pending';
* @param status - 后端 `checks[]` 返回的稳定状态。
* @returns 供页面选择图形和颜色的有限标记,不参与启用门禁计算。
*/
export function readinessMarkerKind(status: ShippingInventoryReadinessCheck['status']): ReadinessMarker {
export function readinessMarkerKind(status: ShippingOnhandReadinessCheck['status']): ReadinessMarker {
if (status === 'passed') return 'complete';
if (status === 'failed' || status === 'stale') return 'attention';
return 'pending';
@@ -27,7 +27,7 @@ export function readinessMarkerKind(status: ShippingInventoryReadinessCheck['sta
* @param check - 后端权威检查项。
* @returns 为 true 时页面可展示对应的单一下一步动作。
*/
export function needsReadinessAction(check: ShippingInventoryReadinessCheck): boolean {
export function needsReadinessAction(check: ShippingOnhandReadinessCheck): boolean {
return check.status !== 'passed' && check.blocking;
}
@@ -37,6 +37,6 @@ export function needsReadinessAction(check: ShippingInventoryReadinessCheck): bo
* @param test - 当前恢复或新发起的测试运行。
* @returns 是否继续轮询。
*/
export function isConfigurationTestRunning(test: ShippingInventoryConfigurationTest | null): boolean {
export function isConfigurationTestRunning(test: ShippingOnhandConfigurationTest | null): boolean {
return Boolean(test && ['awaiting_rpa', 'processing'].includes(test.status));
}
@@ -1,8 +1,8 @@
/**
* features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts
* features/admin/modules/freight-rpa/shippingOnhandSourceForm.ts
* 用途:规范化库存站点表单中仅适用于 DBS 的报表路径字段。
* 依赖:无外部依赖,仅处理库存站点表单的连接器类型和 JSON 路径。
* 逻辑:ShippingInventoryPage 在回填、保存和脏状态比较时调用,避免非 DBS 站点携带 DBS 默认路径。
* 逻辑:FreightRpaPage 在回填、保存和脏状态比较时调用,避免非 DBS 站点携带 DBS 默认路径。
*/
export type InventoryReportPath = Record<string, unknown>;
@@ -2,7 +2,7 @@
* features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts
* 用途:复现「货代库存 RPA」平台任务参数表单的渲染。
* 背景:排程编辑弹窗选择 freight-rpa-onhand 后,库存源多选字段不呈现,且弹窗按钮疑似失效。
* 断言:给定带 source_codes(multi_select/options_source=shipping_inventory_sources) 的定义,
* 断言:给定带 source_codes(multi_select/options_source=freight_rpa_sources) 的定义,
* 挂载后应渲染「库存源」标签及动态选项,而不是抛错或渲染为空。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
@@ -19,26 +19,26 @@ vi.mock('@/features/admin/api/schedule.api', () => ({
),
}));
const shippingInventoryRpaDefinition = {
const shippingOnhandRpaDefinition = {
task_type: 'freight-rpa-onhand',
label: '货代库存 RPA',
label_key: 'admin.schedule.form.platformJobShippingInventory',
label_key: 'admin.schedule.form.platformJobFreightRpaOnhand',
description: '按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。',
description_key: 'admin.schedule.form.shippingInventoryJobHint',
description_key: 'admin.schedule.form.freightRpaOnhandJobHint',
category: 'shipping',
params_schema: [
{
key: 'source_codes',
type: 'multi_select',
label: '库存源',
label_key: 'admin.schedule.form.shippingInventorySources',
label_key: 'admin.schedule.form.freightRpaSources',
required: false,
default: [],
options_source: 'shipping_inventory_sources',
options_source: 'freight_rpa_sources',
placeholder: '留空则导出全部启用库存源',
placeholder_key: 'admin.schedule.form.shippingInventorySourcesPlaceholder',
placeholder_key: 'admin.schedule.form.freightRpaSourcesPlaceholder',
help: '选择需要执行的库存源;选项来自库存源配置,留空则全部执行。',
help_key: 'admin.schedule.form.shippingInventorySourcesHelp',
help_key: 'admin.schedule.form.freightRpaSourcesHelp',
},
],
defaults: { source_codes: [] },
@@ -57,7 +57,7 @@ function mountForm() {
});
return mount(DynamicTaskParamsForm, {
props: {
definition: shippingInventoryRpaDefinition as any,
definition: shippingOnhandRpaDefinition as any,
modelValue: { source_codes: [] },
valid: true,
},
@@ -113,11 +113,12 @@ export const updateTransferType = (code: string, payload: TransferTypePayload) =
/**
* 拉取货代库存外部仓库映射档,仅用于固定仓库编码的存在性黄色提示校验。
* 核心逻辑:请求 /api/admin/freight-rpa/onhand/external-mappings;失败时返回空数组,不阻断类型配置。
* @returns 映射行数组;请求失败返回空数组(校验静默降级为「未命中」语义之外的不提示)
*/
export const listExternalWarehouseMappings = async (): Promise<Array<Record<string, unknown>>> => {
try {
return await requestJson<Array<Record<string, unknown>>>('/api/admin/shipping-notice/external-mappings');
return await requestJson<Array<Record<string, unknown>>>('/api/admin/freight-rpa/onhand/external-mappings');
} catch {
// 校验属辅助提示,加载失败不影响配置主流程
return [];
@@ -11,7 +11,7 @@ import { ADMIN_MODULE_METAS, SHIPPING_CONFIG_SUB_MODULE_METAS } from './constant
import type { ShippingManagementGroupKey } from './stores/admin-nav.store';
const shippingRoutes = adminRoutes[0].children?.filter((route) =>
route.name === 'AdminShippingInventory'
route.name === 'AdminFreightRpa'
|| route.name === 'AdminShippingFieldAssets'
|| route.name === 'AdminShippingOrderSchema'
|| route.name === 'AdminShippingIdentityRules'
@@ -27,7 +27,7 @@ describe('shipping configuration navigation contract', () => {
const moduleIds = ADMIN_MODULE_METAS.map((item) => item.id);
expect(moduleIds.slice(moduleIds.indexOf('schedules'), moduleIds.indexOf('announcements') + 1)).toEqual([
'schedules',
'shipping_inventory',
'freight_rpa',
'announcements',
]);
});
@@ -40,18 +40,18 @@ describe('shipping configuration navigation contract', () => {
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'inventory_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.parsingProfiles', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'parsing' } },
{ id: 'connections', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.connections', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'profiles' } },
{ id: 'inventory_sites', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.sources', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'sources' } },
{ id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } },
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
{ id: 'inventory_fields', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.parsingProfiles', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'parsing' } },
{ id: 'connections', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.connections', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'profiles' } },
{ id: 'inventory_sites', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.sources', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'sources' } },
{ id: 'warehouse_mappings', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.externalMappings', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'mappings' } },
{ id: 'routing_rules', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.rules', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'rules' } },
// 调拨类型(原顶级入口移入,路由独立注册于 AdminTransferTypes,故不在 shippingRoutes 深链集合内)
{ id: 'transfer_types', routeName: 'AdminTransferTypes', path: 'transfer-types', labelKey: 'admin.nav.transferTypes', groupKey: 'admin.nav.shippingInventoryManagement' },
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
{ id: 'transfer_types', routeName: 'AdminTransferTypes', path: 'transfer-types', labelKey: 'admin.nav.transferTypes', groupKey: 'admin.nav.freightRpaManagement' },
{ id: 'shipping_templates', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.excelTemplates', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'templates' } },
{ id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
{ id: 'inventory_snapshots', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
{ id: 'export_records', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
]);
expect(shippingRoutes).toHaveLength(8);
expect(shippingRoutes.some((route) => route.name === 'AdminShippingReviewSupervision')).toBe(false);
@@ -62,7 +62,7 @@ describe('shipping configuration navigation contract', () => {
const groups = [...new Set(SHIPPING_CONFIG_SUB_MODULE_METAS.map((item) => item.groupKey))] satisfies ShippingManagementGroupKey[];
expect(groups).toEqual([
'admin.nav.shippingOrderRecognition',
'admin.nav.shippingInventoryManagement',
'admin.nav.freightRpaManagement',
'admin.nav.shippingRunAudit',
]);
});
@@ -70,14 +70,14 @@ describe('shipping configuration navigation contract', () => {
it('keeps all deep links behind the shared shipping inventory admin boundary', () => {
// 关键断言:菜单可见性不是授权;所有页面均须保留 requiresAdmin 和共享模块权限标识。
expect(shippingRoutes.map((route) => route.meta)).toEqual([
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'inventory' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'field_assets' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_schema' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'identity_rules' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_extraction_runs' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'shipping_audit' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'process_gates' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_document_profiles' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'inventory' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'field_assets' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'order_schema' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'identity_rules' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'order_extraction_runs' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'shipping_audit' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'process_gates' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'order_document_profiles' }),
]);
});
@@ -89,7 +89,7 @@ describe('shipping configuration navigation contract', () => {
expect(editorRoute?.path).toBe('shipping-order-document-profiles/:profileCode/drafts/:profileId/edit');
expect(editorRoute?.meta).toEqual(expect.objectContaining({
requiresAdmin: true,
adminModule: 'shipping_inventory',
adminModule: 'freight_rpa',
adminSubModule: 'order_document_profiles',
}));
});
@@ -17,7 +17,7 @@ export type AdminModuleId =
| 'linked_services'
| 'permissions'
| 'platform_apps'
| 'shipping_inventory'
| 'freight_rpa'
| 'procurement_contract'
| 'training_config'
| 'integration_connector'
@@ -9,7 +9,7 @@ import { describe, expect, it } from 'vitest';
describe('shipping API runtime entrypoints', () => {
it('does not expose direct inventory match or Excel generation actions', () => {
expect(Object.prototype.hasOwnProperty.call(shippingApi, 'matchWorkspaceShippingInventory')).toBe(false);
expect(Object.prototype.hasOwnProperty.call(shippingApi, 'matchWorkspaceShippingOnhand')).toBe(false);
expect(Object.prototype.hasOwnProperty.call(shippingApi, 'generateWorkspaceShippingExcel')).toBe(false);
});
});
@@ -60,7 +60,7 @@ import type {
ShippingOrderReviewLlmSuggestionResponse,
ShippingOrderReviewReparseResponse,
ShippingOrderReviewRun,
ShippingTaskInventoryCandidatesResponse,
ShippingTaskOnhandCandidatesResponse,
ShippingTaskUiState,
} from '../types/shipping.api.types';
@@ -205,7 +205,7 @@ export const workspaceShippingNoticeExportUrl = (businessNo: string) =>
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/export`;
/** 当前任务已关联库存快照的受控下载 URL;后端会再次校验任务归属与活动 link。 */
export const workspaceShippingInventoryFileUrl = (taskNo: string) =>
export const workspaceShippingOnhandFileUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-file`;
/** 当前任务指定明细匹配快照的受控下载 URL;文件号必须由行级投影提供。 */
@@ -622,7 +622,7 @@ export const getWorkspaceTaskInventoryCandidates = (
if (options?.version != null) params.set('version', String(options.version));
if (options?.includeHistory != null) params.set('include_history', String(options.includeHistory));
const query = params.toString();
return requestJson<ShippingTaskInventoryCandidatesResponse>(
return requestJson<ShippingTaskOnhandCandidatesResponse>(
`/api/workspace/shipping-notice/tasks/${encodeURIComponent(taskNo)}/inventory-candidates${query ? `?${query}` : ''}`,
);
};
@@ -1348,7 +1348,7 @@ export async function removeWorkspaceShippingNoticeLine(
* @param file - 已按库存源发布方案导出的 xls/xlsx/csv 文件
* @returns 库存解析与后续匹配结果
*/
export async function uploadWorkspaceShippingInventory(taskNo: string, file: File) {
export async function uploadWorkspaceShippingOnhand(taskNo: string, file: File) {
const form = new FormData();
form.append('file', file);
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
@@ -672,7 +672,7 @@ watch(() => page.currentAgentId, () => {
@add-remote-url="page.addRemoteUrlAttachment"
@shipping-inventory-selected="page.handleShippingInventorySelected"
@shipping-inventory-selected="page.handleShippingOnhandSelected"
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
@@ -15,13 +15,13 @@ const i18n = createI18n({
locale: 'zh-CN',
messages: {
'zh-CN': {
'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching': '重新库存匹配',
'chat.shippingOrderReview.processGate.actionCodes.retry_onhand_matching': '重新库存匹配',
workspace: {
shippingNotice: {
processGate: {
actionCodes: {
reload_inventory_result: '重新读取库存结果',
retry_inventory_preparation: '重新获取库存',
reload_onhand_result: '重新读取库存结果',
retry_onhand_preparation: '重新获取库存',
confirm_customer: '确认客户',
},
inventoryActions: {
@@ -76,7 +76,7 @@ describe('ReviewCurrentProcessingCard', () => {
it('hides a legacy primary action while inventory preparation is running', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_preparation',
stageCode: 'onhand_preparation',
userStatus: 'running',
primaryAction: { code: 'edit_formal_task', i18nKey: 'edit_formal_task' },
},
@@ -90,8 +90,8 @@ describe('ReviewCurrentProcessingCard', () => {
it('keeps the retry action for retryable states', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
primaryAction: { code: 'retry_inventory_preparation', i18nKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' },
stageCode: 'onhand_preparation', userStatus: 'retryable', retryable: true,
primaryAction: { code: 'retry_onhand_preparation', i18nKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' },
},
global: { plugins: [i18n] },
});
@@ -105,8 +105,8 @@ describe('ReviewCurrentProcessingCard', () => {
// 此用例用 reload_inventory_result(仍为写契约有效码)验证卡片对库存动作文案的渲染。
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
primaryAction: { code: 'reload_inventory_result' },
stageCode: 'onhand_preparation', userStatus: 'retryable', retryable: true,
primaryAction: { code: 'reload_onhand_result' },
},
global: { plugins: [i18n] },
});
@@ -131,11 +131,11 @@ describe('ReviewCurrentProcessingCard', () => {
it('renders Gate label_key for every primary action presentation', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
stageCode: 'onhand_matching',
userStatus: 'waiting_human',
primaryAction: {
code: 'retry_inventory_matching',
label_key: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching',
code: 'retry_onhand_matching',
label_key: 'chat.shippingOrderReview.processGate.actionCodes.retry_onhand_matching',
} as any,
},
global: { plugins: [i18n] },
@@ -220,7 +220,7 @@ describe('ReviewCurrentProcessingCard', () => {
it('renders a localized reason instead of an internal blocking code in the next step', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
stageCode: 'onhand_matching',
userStatus: 'waiting_human',
blockingReason: { code: 'inventory_shortage_review_required' },
},
@@ -235,18 +235,18 @@ describe('ReviewCurrentProcessingCard', () => {
it('hides internal inventory recovery targets while retaining the stable primary action', async () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
stageCode: 'onhand_matching',
userStatus: 'waiting_human',
primaryAction: { code: 'retry_inventory_matching', i18nKey: 'retry_inventory_matching' },
primaryAction: { code: 'retry_onhand_matching', i18nKey: 'retry_onhand_matching' },
recoveryActions: [{
code: 'retry_inventory_from_preparation',
i18nKey: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching',
code: 'retry_onhand_from_preparation',
i18nKey: 'chat.shippingOrderReview.processGate.actionCodes.retry_onhand_matching',
}],
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-current-task-recovery-retry_inventory_from_preparation"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-task-recovery-retry_onhand_from_preparation"]').exists()).toBe(false);
expect(wrapper.findAll('button').length).toBe(1);
});
@@ -255,19 +255,19 @@ describe('ReviewCurrentProcessingCard', () => {
props: {
stageCode: 'fulfillment_prep',
userStatus: 'waiting_human',
primaryAction: { code: 'retry_inventory_matching' },
recoveryActions: [{ code: 'retry_inventory_preparation' }],
primaryAction: { code: 'retry_onhand_matching' },
recoveryActions: [{ code: 'retry_onhand_preparation' }],
},
global: { plugins: [i18n] },
});
await wrapper.get('[data-testid="review-current-processing-retry"]').trigger('click');
await wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]').trigger('click');
await wrapper.get('[data-testid="review-current-task-recovery-retry_onhand_preparation"]').trigger('click');
// 两个稳定 action 码分别进入 Gate API:重匹配不可误触 RPA,重新获取库存才会触发 RPA。
expect(wrapper.emitted('action')).toEqual([
['retry_inventory_matching', {}],
['retry_inventory_preparation', {}],
['retry_onhand_matching', {}],
['retry_onhand_preparation', {}],
]);
});
@@ -317,7 +317,7 @@ const businessActionTitle = computed(() => {
});
const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('retry_'));
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_onhand_preparation');
/**
* 阶段能力禁用态裁决:与视图层 submitFormalGateAction 的点击拦截同源(展示=执行同源)。
@@ -31,7 +31,7 @@ const { t, te } = useI18n();
const visible = computed(() => {
const actions = props.fallback?.allowed_actions || [];
return Boolean(props.fallback && actions.includes('retry_inventory_preparation'));
return Boolean(props.fallback && actions.includes('retry_onhand_preparation'));
});
/**
@@ -71,7 +71,7 @@ const reasonLabel = computed(() => {
:disabled="busy"
@click="emit('retry-preparation')"
>
{{ t(inventoryActionLabelKey('retry_inventory_preparation')!) }}
{{ t(inventoryActionLabelKey('retry_onhand_preparation')!) }}
</button>
</section>
</template>
@@ -55,7 +55,7 @@ describe('ReviewLineInventoryOps', () => {
it('keeps inventory actions out of the line even when present', () => {
const wrapper = mountOps({
retryable: false,
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
inventory_allowed_actions: ['retry_onhand_preparation', 'retry_onhand_matching'],
line_allowed_actions: ['close_unfulfillable'],
});
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false);
@@ -474,7 +474,7 @@ describe('ShippingConversationProcessingCard', () => {
customerName: null, poNumber: 'PO-FIRST',
},
childOrderTasks: [{
orderTaskNo: 'OT-EML-WITH-CHILD-OT-C1', status: 'blocked', stage: 'inventory_matching',
orderTaskNo: 'OT-EML-WITH-CHILD-OT-C1', status: 'blocked', stage: 'onhand_matching',
customerName: null, poNumber: 'PO-SECOND', lastActivityAt: null,
}],
});
@@ -976,23 +976,23 @@ describe('ShippingConversationProcessingCard', () => {
status: 'waiting_review',
stage: 'waiting_review',
currentGate: {
gateCode: 'inventory_matching',
nextActionCode: 'open_inventory_match_review',
gateCode: 'onhand_matching',
nextActionCode: 'open_onhand_match_review',
blockingReasonCode: 'inventory_match_not_ready',
},
availableActions: ['open_inventory_match_review'],
availableActions: ['open_onhand_match_review'],
uiState: {
status: 'waiting_human',
stage: 'waiting_review',
lifecycleStage: 'order_review',
lifecycleEntries: [],
blocking_reason: { code: 'inventory_match_not_ready' },
primary_action: { code: 'open_inventory_match_review', i18nKey: null, parameters: {}, executionMode: 'immediate' },
primary_action: { code: 'open_onhand_match_review', i18nKey: null, parameters: {}, executionMode: 'immediate' },
secondary_actions: [],
},
}),
buildWorkItem('OT-PROC', {
stage: 'inventory_matching',
stage: 'onhand_matching',
}),
],
},
@@ -1006,7 +1006,7 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0);
const task = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
expect(task.find('[data-testid="unified-action-primary"]').exists()).toBe(true);
expect(task.find('[data-testid="unified-action-primary"]').text()).toContain('open_inventory_match_review');
expect(task.find('[data-testid="unified-action-primary"]').text()).toContain('open_onhand_match_review');
await task.find('button').trigger('click');
await flushPromises();
@@ -775,7 +775,7 @@ function currentNeedLabel(task: ConversationProcessingUserTask): string {
const labels: Record<string, string> = {
confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer',
resolve_field_conflicts: 'chat.shippingProcessing.currentNeed.resolveFieldConflicts',
open_inventory_match_review: 'chat.shippingProcessing.currentNeed.inventoryMatch',
open_onhand_match_review: 'chat.shippingProcessing.currentNeed.inventoryMatch',
open_order_processing: 'chat.shippingProcessing.currentNeed.orderDraft',
retry: 'chat.shippingProcessing.currentNeed.retry',
retry_parse: 'chat.shippingProcessing.currentNeed.retry',
@@ -280,7 +280,7 @@ describe('ShippingWorkflowTimeline', () => {
it('uses the clicked secondary action lifecycle target instead of falling back to view-result handling', async () => {
const file = fileProjection({
uiState: {
status: 'waiting_human', stage: 'inventory_matching', lifecycleStage: 'fulfillment_prep',
status: 'waiting_human', stage: 'onhand_matching', lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [], blocking_reason: null, primary_action: null,
secondary_actions: [{
code: 'view_result', enabled: true, executionMode: 'navigate',
@@ -459,7 +459,7 @@ export function useChatPage() {
const leaveMessageHandlers = createLeaveMessageHandlers(leave);
const shippingMessageHandlers = createShippingMessageHandlers(shipping);
const trainingHandlers = createTrainingHandlers(training);
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef));
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingOnhandPickerRef));
const shippingNoticePickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingNoticePickerRef));
const showChatRating = ref(false);
@@ -627,13 +627,13 @@ export function useChatPage() {
bumpWorkflowRefresh: shipping.bumpWorkflowRefresh,
focusedConversationTaskNo: shipping.focusedConversationTaskNo,
setFocusedConversationTaskNo: shipping.setFocusedConversationTaskNo,
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
shippingOnhandSelectionActive: shipping.shippingOnhandSelectionActive,
shippingOnhandSelectionTaskId: shipping.shippingOnhandSelectionTaskId,
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
selectShippingOnhandUploadTask: shipping.selectShippingOnhandUploadTask,
cancelShippingOnhandTaskSelection: shipping.cancelShippingOnhandTaskSelection,
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
handleShippingInventorySelected: shipping.handleShippingInventorySelected,
handleShippingOnhandSelected: shipping.handleShippingOnhandSelected,
useShippingSuggestedPrompt: shipping.useShippingSuggestedPrompt,
handleSidebarNewChat,
goToWorkspace: routeSync.goToWorkspace,
@@ -187,13 +187,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
() => isShippingNoticeAgent.value && attachments.value.length > 0,
);
const shippingAutoFlowRequested = ref(false);
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
const shippingOnhandPickerRef = ref<HTMLInputElement | null>(null);
const shippingNoticePickerRef = ref<HTMLInputElement | null>(null);
const pendingShippingUploadTaskId = ref('');
const pendingShippingNoticeTaskId = ref('');
const pendingShippingInventoryFile = ref<File | null>(null);
const shippingInventorySelectionActive = ref(false);
const shippingInventorySelectionTaskId = ref('');
const pendingShippingOnhandFile = ref<File | null>(null);
const shippingOnhandSelectionActive = ref(false);
const shippingOnhandSelectionTaskId = ref('');
const prepareMarkdownDisplayText = (text: string) => {
return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
@@ -264,9 +264,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingAutoFlowRequested.value = false;
pendingShippingUploadTaskId.value = '';
pendingShippingNoticeTaskId.value = '';
pendingShippingInventoryFile.value = null;
shippingInventorySelectionActive.value = false;
shippingInventorySelectionTaskId.value = '';
pendingShippingOnhandFile.value = null;
shippingOnhandSelectionActive.value = false;
shippingOnhandSelectionTaskId.value = '';
resolvedShippingTaskId.value = '';
activeShippingTaskDetail.value = null;
lastConversationSyncKey.value = '';
@@ -667,11 +667,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
const {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
openShippingOnhandPicker,
openShippingNoticePicker,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
handleShippingInventorySelected,
selectShippingOnhandUploadTask,
cancelShippingOnhandTaskSelection,
handleShippingOnhandSelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
isShippingNoticeBatchSubmitting,
@@ -681,14 +681,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
attachments,
input,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
shippingOnhandPickerRef,
shippingNoticePickerRef,
pendingShippingUploadTaskId,
pendingShippingNoticeTaskId,
pendingShippingInventoryFile,
pendingShippingOnhandFile,
resolvedShippingTaskId,
shippingInventorySelectionActive,
shippingInventorySelectionTaskId,
shippingOnhandSelectionActive,
shippingOnhandSelectionTaskId,
getActiveShippingTaskId,
startChatTurn,
refreshShippingActions,
@@ -716,7 +716,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
getActiveShippingTaskId,
messages,
sendShippingMenuMessage,
openShippingInventoryPicker,
openShippingOnhandPicker,
openShippingNoticePicker,
openShippingCustomerDialog,
executeShippingDecision,
@@ -943,11 +943,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
isShippingNoticeAgent,
prepareMarkdownDisplayText,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
shippingOnhandPickerRef,
shippingNoticePickerRef,
pendingShippingUploadTaskId,
shippingInventorySelectionActive,
shippingInventorySelectionTaskId,
shippingOnhandSelectionActive,
shippingOnhandSelectionTaskId,
allowsSendWithAttachmentsOnly,
shippingTaskIdFromQuery,
isShippingActionBusy,
@@ -963,10 +963,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
addShippingParseReviewLine,
removeShippingParseReviewLine,
handleShippingActionClick,
handleShippingInventorySelected,
handleShippingOnhandSelected,
finalizeShippingAssistantMessage,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
selectShippingOnhandUploadTask,
cancelShippingOnhandTaskSelection,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles,
@@ -77,14 +77,14 @@ const createUploadContext = (
attachments: ref([]),
input: ref(''),
shippingAutoFlowRequested: ref(false),
shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
shippingOnhandPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
pendingShippingUploadTaskId: ref(''),
pendingShippingNoticeTaskId: ref(''),
pendingShippingInventoryFile: ref(null),
pendingShippingOnhandFile: ref(null),
resolvedShippingTaskId: ref(''),
shippingInventorySelectionActive: ref(false),
shippingInventorySelectionTaskId: ref(''),
shippingOnhandSelectionActive: ref(false),
shippingOnhandSelectionTaskId: ref(''),
getActiveShippingTaskId: () => '',
startChatTurn: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
@@ -244,7 +244,7 @@ describe('useShippingOrderReview historical readonly', () => {
it('maps confirmed case to non-closed lifecycle for post-confirm automation', () => {
// 关键断言:confirmed 不得映射 closed,否则统一进度轨道会被误判为终态。
expect(mapReviewContextLifecycleStatus('confirmed', null)).toBe('building_order');
expect(mapReviewContextLifecycleStatus('confirmed', 'inventory_matching')).toBe('inventory_matching');
expect(mapReviewContextLifecycleStatus('confirmed', 'onhand_matching')).toBe('onhand_matching');
expect(mapReviewContextLifecycleStatus('closed', null)).toBe('closed');
expect(mapReviewContextLifecycleStatus('quality_issue', null)).toBe('closed');
});
@@ -518,7 +518,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
});
api.getExtractionRun.mockResolvedValue({ run_no: 'RUN-1', status: 'completed' });
api.getProcessingWorkItem.mockResolvedValue({
work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation',
work_item_no: 'OT-1', status: 'processing', stage: 'onhand_preparation',
});
const review = useShippingOrderReview();
@@ -1222,8 +1222,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
workItemNo: 'OT-1',
status: 'waiting_human',
userStatus: 'waiting_human',
stage: 'inventory_matching',
currentGate: { gateCode: 'inventory_matching', status: 'blocked_manual' },
stage: 'onhand_matching',
currentGate: { gateCode: 'onhand_matching', status: 'blocked_manual' },
uiState: {
status: 'waiting_human',
lifecycleStage: 'fulfillment_prep',
@@ -1278,8 +1278,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getProcessingWorkItem.mockResolvedValue({
work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation',
currentGate: { gateCode: 'inventory_preparation', status: 'running' },
work_item_no: 'OT-1', status: 'processing', stage: 'onhand_preparation',
currentGate: { gateCode: 'onhand_preparation', status: 'running' },
});
api.confirmCase.mockResolvedValue({
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
@@ -229,7 +229,7 @@ export function mapReviewContextLifecycleStatus(
if (cs === 'closed') return 'closed';
// [UI-05] confirmed ? closed
if (cs === 'confirmed') {
if (['building_order', 'inventory_matching', 'generating_excel'].includes(rs)) return rs;
if (['building_order', 'onhand_matching', 'generating_excel'].includes(rs)) return rs;
if (['manual_upload_pending', 'upload_rpa_pending', 'upload_rpa_running'].includes(rs)) return rs;
return 'building_order';
}
@@ -240,7 +240,7 @@ export function mapReviewContextLifecycleStatus(
if (['layout_parsing', 'waiting_layout'].includes(rs)) return 'layout_parsing';
if (['routing', 'matching_profile', 'extracting', 'merging_supplement'].includes(rs)) return 'extracting';
if (['review_required', 'partially_completed', 'candidate_ready'].includes(rs)) return 'pending_review';
if (['building_order', 'inventory_matching', 'generating_excel'].includes(rs)) return rs;
if (['building_order', 'onhand_matching', 'generating_excel'].includes(rs)) return rs;
if (['draft', 'ready', 'unreviewed', 'superseded'].includes(cs)) return 'pending_review';
return 'pending_review';
}
@@ -296,8 +296,8 @@ 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_match_review', 'rematch', 'match_inventory',
'open_shortage_review', 'upload_inventory_file', 'open_manual_upload',
'open_onhand_match_review', 'rematch', 'match_inventory',
'open_shortage_review', 'upload_onhand_file', 'open_manual_upload',
'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents',
'retry_failed_attachments', 'open_profile_review',
]);
@@ -308,7 +308,7 @@ const PROCESSING_LIFECYCLES = new Set([
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'onhand_matching',
'generating_excel',
'upload_rpa_pending',
'upload_rpa_running',
@@ -337,7 +337,7 @@ export function mapLifecycleToNodeStatus(
status === 'layout_parsing'
|| status === 'extracting'
|| status === 'building_order'
|| status === 'inventory_matching'
|| status === 'onhand_matching'
|| status === 'generating_excel'
) {
return 'running';
@@ -34,15 +34,15 @@ describe('normalizeShippingProcessingProjection', () => {
process_gate: {
execution_no: 'EXE-1',
status: 'blocked',
current_gate_code: 'inventory_preparation',
current_gate_code: 'onhand_preparation',
expected_gate_version: 3,
current_blocking_gate: {
gate_code: 'inventory_preparation',
gate_code: 'onhand_preparation',
status: 'blocked_manual',
evaluation_version: 3,
},
next_action_code: 'retry_inventory_preparation',
allowed_actions: ['retry_inventory_preparation', 'upload_inventory_file'],
next_action_code: 'retry_onhand_preparation',
allowed_actions: ['retry_onhand_preparation', 'upload_onhand_file'],
},
available_actions: ['open_review'],
ui_state: {
@@ -75,9 +75,9 @@ describe('normalizeShippingProcessingProjection', () => {
expect(normalized!.currentGate?.attemptNo).toBe(1);
expect(normalized!.processGate).toMatchObject({
execution_no: 'EXE-1',
current_gate_code: 'inventory_preparation',
current_gate_code: 'onhand_preparation',
expected_gate_version: 3,
next_action_code: 'retry_inventory_preparation',
next_action_code: 'retry_onhand_preparation',
});
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
expect(normalized!.sourceSummary.documentId).toBe(17);
@@ -199,7 +199,7 @@ describe('normalizeShippingProcessingProjection', () => {
submission_no: 'SUB-1',
intake_no: 'INT-1',
status: 'processing',
stage: 'inventory_matching',
stage: 'onhand_matching',
progress_version: 2,
last_activity_at: '2026-08-08T22:00:00',
source_summary: {},
@@ -259,7 +259,7 @@ describe('normalizeShippingProcessingProjection', () => {
workItemNo: 'OT-1',
workItemType: 'order_task',
status: 'waiting_review',
stage: 'inventory_matching',
stage: 'onhand_matching',
userStatus: 'waiting_human',
uiState: { status: 'waiting_human', lifecycleStage: 'fulfillment_prep' },
})).toBeNull();
@@ -9,8 +9,8 @@ import type {
ConversationProcessingUiState,
OrderIntakeSourceType,
ProcessGateSummary,
ShippingInventoryPerSourceAttempt,
ShippingInventoryPreparationSummary,
ShippingOnhandPerSourceAttempt,
ShippingOnhandPreparationSummary,
ShippingOrderTaskSummary,
ShippingProcessingBlockingReason,
ShippingProcessingFacts,
@@ -304,7 +304,7 @@ function normalizeAggregateSummary(
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
* 注意:只投影当前准备结果;失败后由具体 Gate 动作决定下一步。
*/
function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparationSummary | null {
function normalizeInventoryPreparation(raw: unknown): ShippingOnhandPreparationSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const toStrArr = (value: unknown): string[] => {
@@ -322,7 +322,7 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
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;
const latestAttempts: Record<string, ShippingInventoryPerSourceAttempt> = {};
const latestAttempts: Record<string, ShippingOnhandPerSourceAttempt> = {};
if (latestRaw && typeof latestRaw === 'object') {
for (const [key, val] of Object.entries(latestRaw)) {
if (!val || typeof val !== 'object') continue;
@@ -331,7 +331,7 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
if (!sourceCode) continue;
const attemptNo = Number(row.attempt_no ?? row.attemptNo ?? 0) || 0;
const status = String(row.status || '').trim().toLowerCase() || 'unknown';
const entry: ShippingInventoryPerSourceAttempt = {
const entry: ShippingOnhandPerSourceAttempt = {
sourceCode,
attemptNo,
status,
@@ -8,7 +8,7 @@ import {
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
workspaceShippingNoticeExportUrl,
workspaceShippingExportUrl,
workspaceShippingInventoryFileUrl,
workspaceShippingOnhandFileUrl,
workspaceShippingLineInventoryFileUrl,
} from '@/features/chat/api/shipping.api';
import { getAuthHeaders } from '@/shared/utils/auth';
@@ -31,8 +31,8 @@ export async function downloadWorkspaceShippingNoticeExcelFile(businessNo: strin
* @param taskId - 正式发货任务号,必须来自当前详情快照。
* @returns 下载完成后解析并触发浏览器保存。
*/
export async function downloadWorkspaceShippingInventoryFile(taskId: string): Promise<void> {
await downloadWorkspaceShippingFile(workspaceShippingInventoryFileUrl(taskId), `${taskId}-inventory.xlsx`);
export async function downloadWorkspaceShippingOnhandFile(taskId: string): Promise<void> {
await downloadWorkspaceShippingFile(workspaceShippingOnhandFileUrl(taskId), `${taskId}-inventory.xlsx`);
}
/** 下载某订单行实际匹配的库存快照;后端复核该文件号是否为当前行事实。 */
@@ -2,12 +2,12 @@
* features/chat/shipping/shippingMapping.ts
* 用途:库存列映射消息 payload 读取与字段对齐 Markdown 生成。
* 依赖:shippingText.normalizeShippingHeaderForDisplay、chat.types、shipping.types、vue-i18n。
* 逻辑:ShippingInventoryMappingMessage 与 useChatShippingMappingForm 读取 mapping 消息数据。
* 逻辑:ShippingOnhandMappingFormPayload 与 useChatShippingMappingForm 读取 mapping 消息数据。
*/
import i18n from '@/i18n';
import { normalizeShippingHeaderForDisplay } from './shippingText';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types';
import type { ShippingOnhandMappingFormPayload } from '../types/shipping.types';
const tt = (key: string, params?: Record<string, unknown>) =>
String(params ? i18n.global.t(key, params) : i18n.global.t(key));
@@ -15,24 +15,24 @@ const tt = (key: string, params?: Record<string, unknown>) =>
/**
* 从 shipping-inventory-mapping 类型消息中提取 taskId、schema_preview 与 form。
*/
export function getShippingInventoryMappingPayload(chatMsg: ChatMessage): ShippingInventoryMappingFormPayload | null {
export function getShippingOnhandMappingPayload(chatMsg: ChatMessage): ShippingOnhandMappingFormPayload | 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;
const taskId = String((payload as ShippingOnhandMappingFormPayload).taskId || '').trim();
const schemaPreview = (payload as ShippingOnhandMappingFormPayload).schema_preview;
const form = (payload as ShippingOnhandMappingFormPayload).form;
if (!taskId || !schemaPreview || !form) return null;
return payload as ShippingInventoryMappingFormPayload;
return payload as ShippingOnhandMappingFormPayload;
}
export function hasShippingInventorySampleRows(chatMsg: ChatMessage): boolean {
const rows = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows;
export function hasShippingOnhandSampleRows(chatMsg: ChatMessage): boolean {
const rows = getShippingOnhandMappingPayload(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];
export function getShippingOnhandSampleRowText(chatMsg: ChatMessage): string {
const row = getShippingOnhandMappingPayload(chatMsg)?.schema_preview?.sample_rows?.[0];
return Array.isArray(row) ? row.map((cell) => String(cell)).join(' | ') : '';
}
@@ -12,7 +12,7 @@
/** 复核/任务台共用的履约四节点 stage 键。 */
export const FULFILLMENT_PROGRESS_NODES = [
'building_order',
'inventory_matching',
'onhand_matching',
'generating_excel',
'freight_uploading',
] as const;
@@ -116,7 +116,7 @@ export function fulfillmentNodeIndexFromStage(
if (st === 'completed' || s === 'completed') return 3;
if (s === 'freight_uploading' || st === 'automating') return 3;
if (s === 'excel_generating' || s === 'generating_excel') return 2;
if (s === 'inventory_matching' || s.startsWith('inventory_')) return 1;
if (s === 'onhand_matching' || s.startsWith('inventory_')) return 1;
if (
s === 'building_order'
|| s === 'order_creating'
@@ -43,7 +43,7 @@ describe('shippingStepper', () => {
{ code: 'upload_complete', status: 'pending' },
]);
const steps = applyShippingProcessingStageToSteps(base, {
stage: 'inventory_matching',
stage: 'onhand_matching',
status: 'running',
});
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending', 'pending']);
@@ -86,9 +86,9 @@ const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
duplicate_checking: 1,
waiting_review: 1,
order_creating: 1,
inventory_source_resolving: 2,
inventory_fetching: 2,
inventory_matching: 2,
onhand_source_resolving: 2,
onhand_fetching: 2,
onhand_matching: 2,
excel_generating: 2,
freight_uploading: 3,
completed: 4,
@@ -7,17 +7,17 @@
import { nextTick } from 'vue';
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
import { buildShippingApplyMappingTurn } from './shippingTurnActions';
import { getShippingInventoryMappingPayload } from './shippingMapping';
import { getShippingOnhandMappingPayload } 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 { ShippingOnhandMappingFormPayload } 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>;
shippingOnhandSchemaPreviewCache: Ref<Record<string, unknown>>;
shippingOnhandPickerRef: Ref<HTMLInputElement | null>;
pendingShippingUploadTaskId: Ref<string>;
resolvedShippingTaskId: Ref<string>;
newLocalMessageId: (prefix: string) => string;
@@ -37,7 +37,7 @@ export interface ShippingMappingFormContext {
* @returns 打开、应用和重传库存映射表单的处理函数
*/
export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContext) {
const scrollToLastShippingInventoryMapping = async (): Promise<boolean> => {
const scrollToLastShippingOnhandMapping = async (): Promise<boolean> => {
const container = ctx.chatScrollContainer.value;
if (!container) return false;
let idx = -1;
@@ -56,22 +56,22 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
return true;
};
const openShippingInventoryMappingFormForTask = async (taskId: string): Promise<boolean> => {
const openShippingOnhandMappingFormForTask = 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);
const payload = getShippingOnhandMappingPayload(chatMsg);
if (payload?.taskId?.trim().toUpperCase() === id) return i;
}
return -1;
})();
if (existingIdx >= 0) {
return scrollToLastShippingInventoryMapping();
return scrollToLastShippingOnhandMapping();
}
const schemaPreview = ctx.shippingInventorySchemaPreviewCache.value[id];
const schemaPreview = ctx.shippingOnhandSchemaPreviewCache.value[id];
if (!schemaPreview || typeof schemaPreview !== 'object') {
ctx.msg.warning(ctx.t('chat.shippingNoticeToast.schemaPreviewMissing'));
return false;
@@ -101,18 +101,18 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
reservation_id: String(suggested?.reservation_id || '').trim(),
},
applying: false,
} as ShippingInventoryMappingFormPayload,
} as ShippingOnhandMappingFormPayload,
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
ctx.messages.value.push(mappingMsg);
await ctx.saveLocalMessageToBackend(mappingMsg);
await scrollToLastShippingInventoryMapping();
await scrollToLastShippingOnhandMapping();
return true;
};
const applyShippingInventoryMappingForm = async (msgObj: ChatMessage) => {
const payload = getShippingInventoryMappingPayload(msgObj);
const applyShippingOnhandMappingForm = async (msgObj: ChatMessage) => {
const payload = getShippingOnhandMappingPayload(msgObj);
if (!payload) return;
if (payload.applying) return;
const taskId = String(payload.taskId || '').trim();
@@ -159,18 +159,18 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
}
};
const reuploadShippingInventoryFromMappingForm = (msgObj: ChatMessage) => {
const payload = getShippingInventoryMappingPayload(msgObj);
const reuploadShippingOnhandFromMappingForm = (msgObj: ChatMessage) => {
const payload = getShippingOnhandMappingPayload(msgObj);
if (!payload) return;
const taskId = String(payload.taskId || '').trim();
if (!taskId) return;
ctx.pendingShippingUploadTaskId.value = taskId;
ctx.shippingInventoryPickerRef.value?.click();
ctx.shippingOnhandPickerRef.value?.click();
};
return {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
openShippingOnhandMappingFormForTask,
applyShippingOnhandMappingForm,
reuploadShippingOnhandFromMappingForm,
};
}
@@ -24,7 +24,7 @@ const createContext = (
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
messages: ref([]),
sendShippingMenuMessage: vi.fn(async () => undefined),
openShippingInventoryPicker: vi.fn((_taskId?: string) => true),
openShippingOnhandPicker: vi.fn((_taskId?: string) => true),
openShippingNoticePicker: vi.fn((_taskId?: string) => true),
executeShippingDecision: vi.fn(async () => true),
executeShippingManualUpload: vi.fn(async () => true),
@@ -103,12 +103,12 @@ describe('useChatShippingMenuHandler', () => {
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
await handleShippingMenuAction(
{ id: 'upload_inventory_file', label: '上传库存文件', message: '请上传库存文件' },
{ id: 'upload_onhand_file', label: '上传库存文件', message: '请上传库存文件' },
undefined,
{ taskId: 'sn-picker-123' },
);
expect(ctx.openShippingInventoryPicker).toHaveBeenCalledWith('SN-PICKER-123');
expect(ctx.openShippingOnhandPicker).toHaveBeenCalledWith('SN-PICKER-123');
});
it('passes explicit taskId into notice picker actions', async () => {
@@ -14,7 +14,7 @@ export interface ShippingMenuHandlerContext {
getActiveShippingTaskId: () => string;
messages: Ref<ChatMessage[]>;
sendShippingMenuMessage: (message: string) => Promise<void>;
openShippingInventoryPicker: (taskId?: string) => boolean;
openShippingOnhandPicker: (taskId?: string) => boolean;
openShippingNoticePicker: (taskId?: string) => boolean;
openShippingCustomerDialog: (taskId: string) => Promise<void>;
executeShippingDecision: (
@@ -77,8 +77,8 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
ctx.openShippingNoticePicker(resolveTaskId());
return;
}
if (action.id === 'upload_inventory_file') {
ctx.openShippingInventoryPicker(resolveTaskId());
if (action.id === 'upload_onhand_file') {
ctx.openShippingOnhandPicker(resolveTaskId());
return;
}
if (action.id && [
@@ -30,7 +30,7 @@ const createContext = (
loadHistory: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
startChatTurn: vi.fn(async () => true),
openShippingInventoryPicker: vi.fn(() => true),
openShippingOnhandPicker: vi.fn(() => true),
executeShippingDecision: vi.fn(async () => true),
executeShippingManualUpload: vi.fn(async () => true),
handleShippingMenuAction: vi.fn(async () => undefined),
@@ -39,14 +39,14 @@ const createContext = (
attachments: ref([]),
input: ref(''),
shippingAutoFlowRequested: ref(false),
shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
shippingOnhandPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
pendingShippingUploadTaskId: ref(''),
pendingShippingNoticeTaskId: ref(''),
pendingShippingInventoryFile: ref(null),
pendingShippingOnhandFile: ref(null),
resolvedShippingTaskId: ref(''),
shippingInventorySelectionActive: ref(false),
shippingInventorySelectionTaskId: ref(''),
shippingOnhandSelectionActive: ref(false),
shippingOnhandSelectionTaskId: ref(''),
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
startChatTurn: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
@@ -100,11 +100,11 @@ describe('useChatShippingUploadHandler', () => {
it('opens inventory picker for explicit taskId instead of current active task', () => {
const inventoryClick = vi.fn();
const ctx = createContext({
shippingInventoryPickerRef: ref({ click: inventoryClick } as unknown as HTMLInputElement),
shippingOnhandPickerRef: ref({ click: inventoryClick } as unknown as HTMLInputElement),
});
const { openShippingInventoryPicker } = createShippingUploadHandlers(ctx);
const { openShippingOnhandPicker } = createShippingUploadHandlers(ctx);
const ok = openShippingInventoryPicker('sn-target-100');
const ok = openShippingOnhandPicker('sn-target-100');
expect(ok).toBe(true);
expect(ctx.pendingShippingUploadTaskId.value).toBe('SN-TARGET-100');
@@ -113,11 +113,11 @@ describe('useChatShippingUploadHandler', () => {
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 { handleShippingOnhandSelected } = 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);
await handleShippingOnhandSelected(event);
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
actionType: 'shipping.upload_inventory',
@@ -35,14 +35,14 @@ export interface ShippingUploadHandlerContext {
attachments: Ref<PendingAttachment[]>;
input: Ref<string>;
shippingAutoFlowRequested: Ref<boolean>;
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
shippingOnhandPickerRef: Ref<HTMLInputElement | null>;
shippingNoticePickerRef: Ref<HTMLInputElement | null>;
pendingShippingUploadTaskId: Ref<string>;
pendingShippingNoticeTaskId: Ref<string>;
pendingShippingInventoryFile: Ref<File | null>;
pendingShippingOnhandFile: Ref<File | null>;
resolvedShippingTaskId: Ref<string>;
shippingInventorySelectionActive: Ref<boolean>;
shippingInventorySelectionTaskId: Ref<string>;
shippingOnhandSelectionActive: Ref<boolean>;
shippingOnhandSelectionTaskId: Ref<string>;
getActiveShippingTaskId: () => string;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
@@ -72,8 +72,8 @@ export interface ShippingUploadHandlerContext {
*/
export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) {
const resetInventoryTaskSelection = () => {
ctx.shippingInventorySelectionActive.value = false;
ctx.shippingInventorySelectionTaskId.value = '';
ctx.shippingOnhandSelectionActive.value = false;
ctx.shippingOnhandSelectionTaskId.value = '';
};
const runInventoryUploadChatTurn = async (taskId: string, file: File) => {
@@ -93,7 +93,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
},
},
});
if (!ok) ctx.msg.warning(ctx.t('chat.shippingInventoryUploadFailed'));
if (!ok) ctx.msg.warning(ctx.t('chat.shippingOnhandUploadFailed'));
return ok;
};
@@ -102,34 +102,34 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
await runInventoryUploadChatTurn(taskId, file);
};
const selectShippingInventoryUploadTask = (taskId: string): boolean => {
const selectShippingOnhandUploadTask = (taskId: string): boolean => {
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
if (!normalizedTaskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return false;
}
ctx.resolvedShippingTaskId.value = normalizedTaskId;
ctx.shippingInventorySelectionTaskId.value = normalizedTaskId;
ctx.shippingOnhandSelectionTaskId.value = normalizedTaskId;
ctx.pendingShippingUploadTaskId.value = normalizedTaskId;
ctx.shippingInventorySelectionActive.value = false;
ctx.shippingOnhandSelectionActive.value = false;
const pendingFile = ctx.pendingShippingInventoryFile.value;
const pendingFile = ctx.pendingShippingOnhandFile.value;
if (pendingFile) {
ctx.pendingShippingInventoryFile.value = null;
ctx.pendingShippingOnhandFile.value = null;
ctx.pendingShippingUploadTaskId.value = '';
void uploadInventoryForTask(normalizedTaskId, pendingFile).catch((e: unknown) => {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingInventoryUploadFailed');
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingOnhandUploadFailed');
ctx.msg.warning(errorMessage);
});
return true;
}
ctx.shippingInventoryPickerRef.value?.click();
ctx.shippingOnhandPickerRef.value?.click();
return true;
};
const cancelShippingInventoryTaskSelection = () => {
ctx.pendingShippingInventoryFile.value = null;
const cancelShippingOnhandTaskSelection = () => {
ctx.pendingShippingOnhandFile.value = null;
ctx.pendingShippingUploadTaskId.value = '';
resetInventoryTaskSelection();
};
@@ -258,13 +258,13 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
await runNoticeBatchChatTurn(noticeFiles);
};
const openShippingInventoryPicker = (taskId?: string): boolean => {
const openShippingOnhandPicker = (taskId?: string): boolean => {
const resolvedTaskId = String(taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
if (!resolvedTaskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return false;
}
return selectShippingInventoryUploadTask(resolvedTaskId);
return selectShippingOnhandUploadTask(resolvedTaskId);
};
/**
@@ -284,23 +284,23 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return true;
};
const handleShippingInventorySelected = async (event: Event) => {
const handleShippingOnhandSelected = async (event: Event) => {
const fileInput = event.target as HTMLInputElement;
const file = fileInput.files?.[0];
fileInput.value = '';
const taskId = ctx.pendingShippingUploadTaskId.value;
ctx.pendingShippingUploadTaskId.value = '';
if (!file || !taskId) {
ctx.shippingInventorySelectionTaskId.value = '';
ctx.shippingOnhandSelectionTaskId.value = '';
return;
}
try {
await uploadInventoryForTask(taskId, file);
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingInventoryUploadFailed');
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingOnhandUploadFailed');
ctx.msg.warning(errorMessage);
} finally {
ctx.shippingInventorySelectionTaskId.value = '';
ctx.shippingOnhandSelectionTaskId.value = '';
}
};
@@ -325,11 +325,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
openShippingOnhandPicker,
openShippingNoticePicker,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
handleShippingInventorySelected,
selectShippingOnhandUploadTask,
cancelShippingOnhandTaskSelection,
handleShippingOnhandSelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
isShippingNoticeBatchSubmitting,
@@ -35,7 +35,7 @@ describe('useShippingProcessingWorkItem', () => {
workItemNo: 'OT-20260905-DAC55F90',
sourceType: 'eml',
status: 'waiting_review',
stage: 'inventory_matching',
stage: 'onhand_matching',
progressVersion: 24,
lastActivityAt: '2026-09-05T11:25:45Z',
submissionNo: 'SOS-1',
@@ -43,11 +43,11 @@ describe('useShippingProcessingWorkItem', () => {
userStatus: 'waiting_human',
uiState: {
status: 'waiting_human',
stage: 'inventory_matching',
stage: 'onhand_matching',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [],
blocking_reason: { code: 'inventory_shortage_review_required' },
primary_action: { code: 'retry_inventory_matching' },
primary_action: { code: 'retry_onhand_matching' },
secondary_actions: [],
},
sourceSummary: {
@@ -87,7 +87,7 @@ describe('useShippingProcessingWorkItem', () => {
expect(api!.projection.value?.workItemNo).toBe('OT-20260905-DAC55F90');
expect(api!.projection.value?.userStatus).toBe('waiting_human');
expect(api!.projection.value?.uiState?.lifecycleStage).toBe('fulfillment_prep');
expect(api!.projection.value?.uiState?.primary_action?.code).toBe('retry_inventory_matching');
expect(api!.projection.value?.uiState?.primary_action?.code).toBe('retry_onhand_matching');
expect(api!.error.value).toBeNull();
});
});
@@ -50,11 +50,11 @@ export type ShippingProcessingStage =
| 'candidate_creating'
| 'customer_resolving'
| 'duplicate_checking'
| 'inventory_source_resolving'
| 'onhand_source_resolving'
| 'waiting_review'
| 'order_creating'
| 'inventory_fetching'
| 'inventory_matching'
| 'onhand_fetching'
| 'onhand_matching'
| 'excel_generating'
| 'freight_uploading'
| 'completed';
@@ -86,12 +86,12 @@ export type ShippingProcessingActionIntent =
| 'confirm_customer'
| 'resolve_field_conflicts'
| 'adjudicate_duplicate'
| 'open_inventory_match_review'
| 'open_onhand_match_review'
| 'open_shortage_review'
| 'upload_inventory_file'
| 'reload_inventory_result'
| 'retry_inventory_preparation'
| 'retry_inventory_matching'
| 'upload_onhand_file'
| 'reload_onhand_result'
| 'retry_onhand_preparation'
| 'retry_onhand_matching'
| 'retry_parse'
| 'retry_failed_documents'
| 'retry_failed_attachments'
@@ -106,8 +106,8 @@ export type ShippingProcessingActionIntent =
| 'retry_with_latest_rules'
| 'recheck_freeze_readiness'
| 'retry_task_creation'
| 'retry_inventory_field_mapping'
| 'recheck_inventory_sufficiency'
| 'retry_onhand_field_mapping'
| 'recheck_onhand_sufficiency'
| 'recheck_excel_readiness'
| 'retry_stp_auto_create'
| 'reparse'
@@ -128,11 +128,11 @@ export const SHIPPING_PROCESSING_STAGES: readonly ShippingProcessingStage[] = [
'candidate_creating',
'customer_resolving',
'duplicate_checking',
'inventory_source_resolving',
'onhand_source_resolving',
'waiting_review',
'order_creating',
'inventory_fetching',
'inventory_matching',
'onhand_fetching',
'onhand_matching',
'excel_generating',
'freight_uploading',
'completed',
@@ -252,7 +252,7 @@ export interface ShippingProcessingFacts {
[key: string]: unknown;
}
export interface ShippingInventoryCandidateSetSummary {
export interface ShippingOnhandCandidateSetSummary {
id: number;
version: number;
status: 'draft' | 'frozen' | 'superseded' | 'invalidated';
@@ -262,7 +262,7 @@ export interface ShippingInventoryCandidateSetSummary {
manifestSnapshotSha256?: string | null;
}
export interface ShippingInventoryCandidateSourceDetail {
export interface ShippingOnhandCandidateSourceDetail {
id: number;
candidateSetId: number;
sourceCode: string;
@@ -273,7 +273,7 @@ export interface ShippingInventoryCandidateSourceDetail {
sourceConfigVersion?: string | null;
}
export interface ShippingInventoryCandidateLineDetail {
export interface ShippingOnhandCandidateLineDetail {
candidateLineId: number;
candidateSetId: number;
lineNo: number;
@@ -283,12 +283,12 @@ export interface ShippingInventoryCandidateLineDetail {
allowedSourceCodes: string[];
}
export interface ShippingTaskInventoryCandidatesResponse {
export interface ShippingTaskOnhandCandidatesResponse {
taskNo: string;
currentSet: ShippingInventoryCandidateSetSummary | null;
sources: ShippingInventoryCandidateSourceDetail[];
lines: ShippingInventoryCandidateLineDetail[];
history: ShippingInventoryCandidateSetSummary[];
currentSet: ShippingOnhandCandidateSetSummary | null;
sources: ShippingOnhandCandidateSourceDetail[];
lines: ShippingOnhandCandidateLineDetail[];
history: ShippingOnhandCandidateSetSummary[];
blockingReason?: ShippingProcessingBlockingReason | null;
primaryAction?: ShippingProcessingPrimaryAction | null;
}
@@ -400,15 +400,15 @@ export interface ShippingProcessingProjection {
* 权威事实源:summarize_inventory_rpa_latest_attempts();
* 前端按钮禁用/重试文案/状态徽章全部直接读本对象,禁止继续拼接旧字段合成 running。
*/
inventoryPreparation?: ShippingInventoryPreparationSummary | null;
inventoryPreparation?: ShippingOnhandPreparationSummary | null;
}
/**
* 题4A & 7A:逐源 inventory 准备状态(ShippingProcessingProjection.inventoryPreparation)。
* 按实际冻结源 required_sources 为基准分类并暴露当前成功、等待和失败事实。
*/
export interface ShippingInventoryPreparationSummary {
/** 实际任务级冻结源(task.task_frozen_inventory_source_codes),顺序以冻结记录为准。 */
export interface ShippingOnhandPreparationSummary {
/** 实际任务级冻结源(task.task_frozen_onhand_source_codes),顺序以冻结记录为准。 */
requiredSources: string[];
/** 已就绪:有 prepared 状态 Attempt,且存在有效的 InventoryFile / TaskInventoryLink。 */
preparedSources: string[];
@@ -424,14 +424,14 @@ export interface ShippingInventoryPreparationSummary {
* 按冻结源逐源最近 Attempt 摘要(source_code → 结构化记录)。
* 用于 UI tooltip/详情;按钮禁用不直接读本字典,读上面的 required/prepared/pending/failed 集合。
*/
latestAttempts?: Record<string, ShippingInventoryPerSourceAttempt>;
latestAttempts?: Record<string, ShippingOnhandPerSourceAttempt>;
}
/**
* 逐源最近一次 Inventory RPA Attempt 摘要(inventoryPreparation.latestAttempts[sourceCode])。
* 仅用于 UI 展示;业务判定必须走顶层 *_sources 集合。
*/
export interface ShippingInventoryPerSourceAttempt {
export interface ShippingOnhandPerSourceAttempt {
sourceCode: string;
attemptNo: number;
/** queued | running | consumed | failed | skipped */
@@ -795,7 +795,7 @@ export type InventorySourceMethod =
| 'rule_evaluation_freeze'
| 'legacy_migrated';
export interface ShippingInventorySourceCandidate {
export interface ShippingOnhandSourceCandidate {
source_code: string;
display_name?: string | null;
warehouse_id?: string | null;
@@ -804,12 +804,12 @@ export interface ShippingInventorySourceCandidate {
matched_by?: string | null;
}
export interface ShippingInventorySourceResolution {
export interface ShippingOnhandSourceResolution {
status?: InventorySourceStatus | null;
method?: InventorySourceMethod | null;
reason?: string | null;
release_field_values?: Record<string, string>;
candidates?: ShippingInventorySourceCandidate[];
candidates?: ShippingOnhandSourceCandidate[];
destination_candidates?: string[];
evidence?: Record<string, unknown>[];
conflicts?: string[];
@@ -817,7 +817,7 @@ export interface ShippingInventorySourceResolution {
routing_fingerprint?: string | null;
}
export interface ShippingInventorySnapshot {
export interface ShippingOnhandSnapshot {
inventory_file_no?: string | null;
source_code?: string | null;
warehouse_id?: string | null;
@@ -893,7 +893,7 @@ export interface ShippingTaskSummary {
};
rpa_runtime?: ShippingRpaRuntime | null;
rpa_inventory_source?: Record<string, unknown> | null;
inventory_source_resolution?: ShippingInventorySourceResolution | null;
inventory_source_resolution?: ShippingOnhandSourceResolution | null;
destination_code?: string | null;
destination_city?: string | null;
destination_country?: string | null;
@@ -904,7 +904,7 @@ export interface ShippingTaskSummary {
inventory_source_method?: InventorySourceMethod | null;
inventory_source_config_version?: string | null;
inventory_routing_fingerprint?: string | null;
inventory_snapshot?: ShippingInventorySnapshot | null;
onhand_snapshot?: ShippingOnhandSnapshot | null;
created_at?: string | null;
updated_at?: string | null;
ui_state?: ShippingTaskUiState;
@@ -1033,13 +1033,13 @@ export type ShippingProcessGateCode =
| 'customer_resolution'
| 'duplicate_detection'
| 'field_conflict_resolution'
| 'inventory_source_routing'
| 'onhand_source_routing'
| 'order_freeze_readiness'
| 'task_creation'
| 'inventory_preparation'
| 'inventory_field_mapping'
| 'inventory_matching'
| 'inventory_sufficiency'
| 'onhand_preparation'
| 'onhand_field_mapping'
| 'onhand_matching'
| 'onhand_sufficiency'
| 'excel_readiness'
| 'artifact_generation'
| 'freight_upload_rpa'
@@ -1080,17 +1080,17 @@ export type ShippingProcessGateActionCode =
| 'retry_with_latest_rules'
| 'recheck_freeze_readiness'
| 'retry_task_creation'
| 'reload_inventory_result'
| 'retry_inventory_preparation'
| 'poll_inventory_preparation'
| 'upload_inventory_file'
| 'retry_inventory_field_mapping'
| 'retry_inventory_matching'
| 'retry_inventory_from_preparation'
| 'retry_inventory_from_field_mapping'
| 'retry_inventory_from_matching'
| 'open_inventory_match_review'
| 'recheck_inventory_sufficiency'
| 'reload_onhand_result'
| 'retry_onhand_preparation'
| 'poll_onhand_preparation'
| 'upload_onhand_file'
| 'retry_onhand_field_mapping'
| 'retry_onhand_matching'
| 'retry_onhand_from_preparation'
| 'retry_onhand_from_field_mapping'
| 'retry_onhand_from_matching'
| 'open_onhand_match_review'
| 'recheck_onhand_sufficiency'
| 'open_shortage_review'
| 'recheck_excel_readiness'
| 'regenerate_excel_artifact'
@@ -1354,7 +1354,7 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
order_snapshot_id?: number | null;
order_data_version?: number | null;
field_conflicts?: ShippingFieldConflict[] | null;
inventory_verifications?: ShippingInventoryVerification[];
inventory_verifications?: ShippingOnhandVerification[];
export_artifacts?: ShippingExportArtifact[];
upload_attempts?: ShippingUploadAttempt[];
events: ShippingTaskEvent[];
@@ -1685,7 +1685,7 @@ export interface ShippingFreightNoticeGroupsResponse {
reason?: 'po_missing' | 'no_business_notice' | string | null;
}
export interface ShippingInventoryUploadResponse {
export interface ShippingOnhandUploadResponse {
status: string;
message?: string;
task_id?: string;
@@ -1779,20 +1779,20 @@ export interface ShippingNoticeLayoutSummary {
unsupported: number;
}
export interface ShippingInventoryVerificationLine {
export interface ShippingOnhandVerificationLine {
reservation_id: string;
required_qty: string;
available_qty: string;
status: 'available' | 'shortage' | 'invalid' | string;
}
export interface ShippingInventoryVerification {
export interface ShippingOnhandVerification {
id: number;
status: string;
inventory_snapshot_id?: number | null;
source_config_version?: string | null;
created_at?: string | null;
lines: ShippingInventoryVerificationLine[];
lines: ShippingOnhandVerificationLine[];
}
export interface ShippingExportArtifact {
@@ -2413,7 +2413,7 @@ export interface ShippingOrderReviewInventoryMatchedRule {
* 库存源单源不可用原因码(unavailable_reasons 的值)。
* 与 backend error_explainability_contract.INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED 对齐。
*/
export type ShippingInventorySourceUnavailableReasonCode =
export type ShippingOnhandSourceUnavailableReasonCode =
| 'source_not_found'
| 'source_disabled'
| 'source_runtime_unavailable'
@@ -2427,7 +2427,7 @@ export type ShippingInventorySourceUnavailableReasonCode =
* 特别区分:no_inventory_source_candidates(规则未命中)≠
* inventory_source_unavailable(命中但源不可用)≠ require_manual_review(冲突)。
*/
export type ShippingInventorySourceLineBlockReasonCode =
export type ShippingOnhandSourceLineBlockReasonCode =
| 'no_inventory_source_candidates'
| 'inventory_source_unavailable'
| 'require_manual_review'
@@ -2435,7 +2435,7 @@ export type ShippingInventorySourceLineBlockReasonCode =
| 'manual_inventory_source_invalid'
| 'inventory_source_conflicted'
| 'inventory_source_changed'
| 'inventory_source_identity_mismatch'
| 'onhand_source_identity_mismatch'
| string;
/**
@@ -2457,7 +2457,7 @@ export interface ShippingOrderReviewInventoryRuleSuggestion {
raw_source_codes?: string[];
unavailable_source_codes?: string[];
/** 不可用源编码 → 稳定原因码(非文案) */
unavailable_reasons?: Record<string, ShippingInventorySourceUnavailableReasonCode>;
unavailable_reasons?: Record<string, ShippingOnhandSourceUnavailableReasonCode>;
routing_status?: string;
rule_versions?: ShippingOrderReviewInventoryRuleVersion[];
matched_rule_ids?: number[];
@@ -2479,7 +2479,7 @@ export interface ShippingOrderReviewBuildEligibilityLineProjection {
/** 规则命中但当前不可用的源 */
unavailable_source_codes?: string[];
/** 不可用源编码 → 稳定原因码(非文案;前端用 i18n 渲染) */
unavailable_reasons?: Record<string, ShippingInventorySourceUnavailableReasonCode>;
unavailable_reasons?: Record<string, ShippingOnhandSourceUnavailableReasonCode>;
matched_rule_ids?: number[];
matched_rules?: ShippingOrderReviewInventoryMatchedRule[];
rule_versions?: ShippingOrderReviewInventoryRuleVersion[];
@@ -2490,7 +2490,7 @@ export interface ShippingOrderReviewBuildEligibilityLineProjection {
rule_source_codes?: string[];
routing_status?: string;
can_build?: boolean;
block_reason?: ShippingInventorySourceLineBlockReasonCode | null;
block_reason?: ShippingOnhandSourceLineBlockReasonCode | null;
selection_mode?: string;
manual_reason?: string;
}
@@ -2510,7 +2510,7 @@ export interface ShippingOrderReviewBuildEligibilityIssue {
raw_rule_source_codes?: string[];
message?: string | null;
unavailable_source_codes?: string[];
unavailable_reasons?: Record<string, ShippingInventorySourceUnavailableReasonCode>;
unavailable_reasons?: Record<string, ShippingOnhandSourceUnavailableReasonCode>;
explainability?: ShippingExplainabilityReason | null;
low_confidence_fields?: Array<{
field_code: string;
@@ -3134,13 +3134,13 @@ export interface ShippingOrderReviewLineFulfillmentDecision {
/** 行级履约决定码(与后端 ALLOWED_DECISIONS 对齐)。 */
export type ShippingOrderReviewLineFulfillmentDecisionCode =
| 'wait_inventory'
| 'wait_onhand'
| 'fulfill_complete_line_now'
| 'close_unfulfillable'
| 'reopen'
| 'use_new_inventory_file'
| 'change_inventory_source'
| 'release_inventory_shortage';
| 'release_onhand_shortage';
/** 行级履约与库存缺口投影行(含 OT 匹配事实与 allowed_actions)。 */
export interface ShippingOrderReviewLineFulfillmentLine {
@@ -3195,7 +3195,7 @@ export interface ShippingOrderReviewLineFulfillmentLine {
field_id: string;
display_name: string;
value?: string | null;
value_source?: 'inventory_snapshot' | 'manual_required' | string;
value_source?: 'onhand_snapshot' | 'manual_required' | string;
requires_manual?: boolean;
}>;
/** 字段无法受控解析时的稳定错误码;UI 必须隐藏放行入口。 */
@@ -3300,7 +3300,7 @@ export type ShippingWorkflowItemLifecycleStatus =
| 'layout_parsing'
| 'extracting'
| 'building_order'
| 'inventory_matching'
| 'onhand_matching'
| 'generating_excel'
| 'pending_review'
| 'reparse_failed'
@@ -272,7 +272,7 @@ export interface ShippingActionButton {
source_code?: string;
}
export interface ShippingInventoryMappingFormPayload {
export interface ShippingOnhandMappingFormPayload {
taskId: string;
schema_preview: {
sample_rows?: unknown[][];
@@ -617,7 +617,7 @@ async function mountView(query: Record<string, string> = {}) {
waiting_system_start: '等待系统启动',
waiting_to_start: '等待系统启动',
order_creating: '等待系统启动',
inventory_matching: '库存匹配',
onhand_matching: '库存匹配',
excel_generating: 'Excel 生成',
},
},
@@ -731,7 +731,7 @@ async function mountView(query: Record<string, string> = {}) {
shippingProcessing: {
stage: {
order_creating: '创建正式订单',
inventory_matching: '库存匹配',
onhand_matching: '库存匹配',
},
stageLabel: {
waiting_system_start: '等待系统启动',
@@ -764,8 +764,8 @@ async function mountView(query: Record<string, string> = {}) {
actionCodes: {
confirm_customer: '确认客户',
resolve_field_conflicts: '处理字段冲突',
retry_inventory_preparation: '重新获取库存',
retry_inventory_matching: '重新匹配库存',
retry_onhand_preparation: '重新获取库存',
retry_onhand_matching: '重新匹配库存',
},
},
},
@@ -1545,11 +1545,11 @@ describe('ShippingOrderReviewView layout phase 1', () => {
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-RPA-RECOVERY-PENDING',
status: 'failed', userStatus: 'failed', stage: 'inventory_fetching',
status: 'failed', userStatus: 'failed', stage: 'onhand_fetching',
progressVersion: 7, currentGate: { status: 'blocked_retryable' },
uiState: {
status: 'failed', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_inventory_preparation', i18n_key: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' },
status: 'failed', stage: 'onhand_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_onhand_preparation', i18n_key: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' },
secondary_actions: [],
},
} as any;
@@ -1559,7 +1559,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
ui_state: {
actions: {
primary: {
code: 'retry_inventory_preparation', kind: 'current_gate', enabled: true,
code: 'retry_onhand_preparation', kind: 'current_gate', enabled: true,
dispatch: 'mutation', requires_confirmation: false,
},
secondary: [],
@@ -1579,7 +1579,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).not.toContain('自动处理失败');
});
it('submits retry_inventory_preparation from A even when B.actions lacks the code', async () => {
it('submits retry_onhand_preparation from A even when B.actions lacks the code', async () => {
// 回归:右卡只读 A.primary_action 展示「重新获取库存(RPA)」;若仍按 B.actions
// 授权,会落到「未识别的动作」。A 展示即写路径授权;capabilities 可作 bypass。
activeCase.value = {
@@ -1589,11 +1589,11 @@ describe('ShippingOrderReviewView layout phase 1', () => {
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-RPA-A-ONLY',
status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching',
status: 'failed', userStatus: 'retryable', stage: 'onhand_fetching',
progressVersion: 3, currentGate: { status: 'blocked_retryable' },
uiState: {
status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_inventory_preparation' },
status: 'retryable', stage: 'onhand_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_onhand_preparation' },
secondary_actions: [],
},
} as any;
@@ -1606,17 +1606,17 @@ describe('ShippingOrderReviewView layout phase 1', () => {
process_gate: {
execution_no: 'EXEC-RPA-A-ONLY',
current_blocking_gate: {
gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable',
gate_code: 'onhand_preparation', evaluation_version: 2, status: 'blocked_retryable',
},
allowed_actions: ['retry_inventory_preparation'],
recovery_targets: [{ action_code: 'retry_inventory_preparation' }],
allowed_actions: ['retry_onhand_preparation'],
recovery_targets: [{ action_code: 'retry_onhand_preparation' }],
},
stage_context: {
preparation: {
status: 'blocked', source_locked: false, source_options: [{ source_code: 'DSV' }],
capabilities: [{
code: 'retry_inventory_preparation', scope: 'task',
action_code: 'retry_inventory_preparation', enabled: true,
code: 'retry_onhand_preparation', scope: 'task',
action_code: 'retry_onhand_preparation', enabled: true,
}],
frozen_order_lines: [], lines: [],
},
@@ -1638,7 +1638,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
actionCode: 'retry_inventory_preparation',
actionCode: 'retry_onhand_preparation',
stageCapabilityBypass: true,
}),
);
@@ -1655,12 +1655,12 @@ describe('ShippingOrderReviewView layout phase 1', () => {
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-RPA-CAP-DISABLED',
status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching',
status: 'failed', userStatus: 'retryable', stage: 'onhand_fetching',
progressVersion: 5, currentGate: { status: 'blocked_retryable' },
uiState: {
status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_inventory_matching' },
secondary_actions: [{ code: 'retry_inventory_preparation', enabled: true }],
status: 'retryable', stage: 'onhand_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_onhand_matching' },
secondary_actions: [{ code: 'retry_onhand_preparation', enabled: true }],
},
} as any;
const taskApi = await import('@/features/chat/api/shipping.api');
@@ -1671,9 +1671,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
process_gate: {
execution_no: 'EXEC-RPA-CAP-DISABLED',
current_blocking_gate: {
gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable',
gate_code: 'onhand_preparation', evaluation_version: 2, status: 'blocked_retryable',
},
allowed_actions: ['retry_inventory_matching', 'retry_inventory_preparation'],
allowed_actions: ['retry_onhand_matching', 'retry_onhand_preparation'],
},
stage_context: {
preparation: {
@@ -1682,13 +1682,13 @@ describe('ShippingOrderReviewView layout phase 1', () => {
failed_source_codes: ['DSV'],
capabilities: [
{
code: 'retry_inventory_matching', scope: 'task',
action_code: 'retry_inventory_matching', enabled: false,
code: 'retry_onhand_matching', scope: 'task',
action_code: 'retry_onhand_matching', enabled: false,
disabled_reason: 'no_match_result',
},
{
code: 'retry_inventory_preparation', scope: 'task',
action_code: 'retry_inventory_preparation', enabled: true,
code: 'retry_onhand_preparation', scope: 'task',
action_code: 'retry_onhand_preparation', enabled: true,
disabled_reason: null,
},
],
@@ -1710,7 +1710,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(primary.attributes('data-capability-disabled')).toBe('true');
expect(primary.attributes('title')).toContain('暂无库存匹配结果');
// 侧路按钮:能力 enabled → 保持可点,不受主按钮禁用影响。
const recovery = wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]');
const recovery = wrapper.get('[data-testid="review-current-task-recovery-retry_onhand_preparation"]');
expect(recovery.attributes('disabled')).toBeUndefined();
// 点击禁用按钮不得触发提交,也不得弹任何 info 提示(此前会弹未翻译 key)。
await primary.trigger('click');
@@ -1789,7 +1789,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
confirmed_task_no: 'SN-PROJECTION-PENDING',
process_gate: {
execution_no: 'EXEC-PROJECTION-PENDING', status: 'blocked_retryable', owner_type: 'human', technical_auto_only: false,
current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' },
current_blocking_gate: { gate_code: 'onhand_preparation', status: 'blocked_retryable' },
primary_action: { code: 'retry', label_key: 'chat.shippingOrderReview.currentTask.actionRetry' },
},
automation: { status: 'failed', retryable: true, can_auto_create: false, can_build: true },
@@ -1875,7 +1875,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
confirmed_task_id: 91,
confirmed_task_no: 'SN-SINGLE-SOURCE-1',
// 故意下发与投影分叉的 Case 阶段:单源后必须被无视。
current_stage: { code: 'inventory_matching', label_key: 'inventory_matching', inconsistent: false },
current_stage: { code: 'onhand_matching', label_key: 'onhand_matching', inconsistent: false },
automation: { status: 'running', retryable: false, can_auto_create: false, can_build: true },
};
shippingProcessingProjection.value = null;
@@ -2513,7 +2513,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
};
const wrapper = await mountView({ lifecycle_stage: 'order_review' });
shippingProcessingProjection.value = {
stage: 'inventory_preparation', status: 'processing',
stage: 'onhand_preparation', status: 'processing',
uiState: {
status: 'running', lifecycleStage: 'fulfillment_prep', lifecycleEntries: [],
primary_action: null, secondary_actions: [],
@@ -2700,10 +2700,10 @@ describe('ShippingOrderReviewView layout phase 1', () => {
// 而不是默认回退到订单复核。
shippingProcessingProjection.value = {
status: 'processing',
stage: 'inventory_matching',
stage: 'onhand_matching',
uiState: {
status: 'processing',
stage: 'inventory_matching',
stage: 'onhand_matching',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
@@ -2804,10 +2804,10 @@ describe('ShippingOrderReviewView layout phase 1', () => {
draft_line_id: 'line-frozen',
snapshot_line_id: 1001,
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
line_allowed_actions: ['release_inventory_shortage'],
inventory_allowed_actions: ['retry_onhand_preparation', 'retry_onhand_matching'],
line_allowed_actions: ['release_onhand_shortage'],
release_template_fields: [
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false },
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
],
release_required_fields: [{ field_id: '102', display_name: '库位' }],
@@ -2827,10 +2827,10 @@ describe('ShippingOrderReviewView layout phase 1', () => {
ui_state: {
process_gate: {
execution_no: 'EXEC-FROZEN-LINE',
current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' },
current_blocking_gate: { gate_code: 'onhand_preparation', status: 'blocked_retryable' },
},
actions: {
primary: { code: 'retry_inventory_preparation', enabled: true, dispatch: 'mutation' },
primary: { code: 'retry_onhand_preparation', enabled: true, dispatch: 'mutation' },
secondary: [],
},
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
@@ -2847,10 +2847,10 @@ describe('ShippingOrderReviewView layout phase 1', () => {
required_qty: '6', available_qty: null, part_available_qty: '9', shortage_qty: null, source_code: 'DBS',
inventory_file_no: 'SIF-LINE-DBS', status: 'shortage',
draft_line_id: 'line-frozen',
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
line_allowed_actions: ['release_inventory_shortage'],
inventory_allowed_actions: ['retry_onhand_preparation', 'retry_onhand_matching'],
line_allowed_actions: ['release_onhand_shortage'],
release_template_fields: [
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false },
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
],
release_required_fields: [{ field_id: '102', display_name: '库位' }],
@@ -2886,26 +2886,26 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false);
// 展示态行级动作收纳进更多菜单(⋯):逐项断言授权动作入口存在,不再有常显按钮。
await openLineOverflowMenu(wrapper, 1001);
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-download_inventory_file-1001"]')).toBeTruthy();
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_inventory_preparation-1001"]')).toBeTruthy();
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_inventory_matching-1001"]')).toBeTruthy();
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-release_inventory_shortage-1001"]')).toBeTruthy();
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-download_onhand_file-1001"]')).toBeTruthy();
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_onhand_preparation-1001"]')).toBeTruthy();
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_onhand_matching-1001"]')).toBeTruthy();
expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-release_onhand_shortage-1001"]')).toBeTruthy();
expect(workspace.text()).toContain('库存不足');
await clickLineMenuItem(1001, 'download_inventory_file');
await clickLineMenuItem(1001, 'download_onhand_file');
expect(downloadWorkspaceShippingLineInventoryFileMock).toHaveBeenCalledWith('SN-FROZEN', 'SIF-LINE-DBS');
await openLineOverflowMenu(wrapper, 1001);
await clickLineMenuItem(1001, 'retry_inventory_preparation');
await clickLineMenuItem(1001, 'retry_onhand_preparation');
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
actionCode: 'retry_inventory_preparation',
actionCode: 'retry_onhand_preparation',
payload: { snapshot_line_id: 1001 },
}),
);
// Gate 恢复受理后立即启动五阶段轮询,不依赖浏览器手动刷新。
expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(1);
await openLineOverflowMenu(wrapper, 1001);
await clickLineMenuItem(1001, 'release_inventory_shortage');
await clickLineMenuItem(1001, 'release_onhand_shortage');
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM ID');
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM-001');
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
@@ -2933,9 +2933,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
draft_line_id: 'line-frozen',
snapshot_line_id: 1001,
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
line_allowed_actions: ['release_inventory_shortage'],
line_allowed_actions: ['release_onhand_shortage'],
release_template_fields: [
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false },
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
],
release_required_fields: [{ field_id: '102', display_name: '库位' }],
@@ -2964,7 +2964,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
stage_context: releaseAccepted ? { upload: {} } : {
preparation: {
frozen_order_lines: [{ snapshot_line_id: 1001, line_no: 1, reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6' }],
lines: [{ snapshot_line_id: 1001, line_no: 1, reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-frozen', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }],
lines: [{ snapshot_line_id: 1001, line_no: 1, reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-frozen', line_allowed_actions: ['release_onhand_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }],
},
},
},
@@ -2974,7 +2974,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
await flushPromises();
// 缺字段短缺行:放行入口在更多菜单,必填补录在行内补录条完成(原因不再强制)。
await openLineOverflowMenu(wrapper, 1001);
await clickLineMenuItem(1001, 'release_inventory_shortage');
await clickLineMenuItem(1001, 'release_onhand_shortage');
await wrapper.get('[data-testid="review-fulfillment-release-input-1001-102"]').setValue('A-01');
await wrapper.get('[data-testid="review-fulfillment-release-confirm-1001"]').trigger('click');
await new Promise<void>((resolve) => setTimeout(resolve, 0));
@@ -2997,9 +2997,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
draft_line_id: 'line-async',
snapshot_line_id: 1002,
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
line_allowed_actions: ['release_inventory_shortage'],
line_allowed_actions: ['release_onhand_shortage'],
release_template_fields: [
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false },
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
],
release_required_fields: [{ field_id: '102', display_name: '库位' }],
@@ -3024,7 +3024,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
stage_context: advanceDone ? { upload: {} } : {
preparation: {
frozen_order_lines: [{ snapshot_line_id: 1002, line_no: 1, reservation_id: 'RSV-ASYNC', part_number: 'PN-ASYNC', required_qty: '6' }],
lines: [{ snapshot_line_id: 1002, line_no: 1, reservation_id: 'RSV-ASYNC', part_number: 'PN-ASYNC', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-async', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }],
lines: [{ snapshot_line_id: 1002, line_no: 1, reservation_id: 'RSV-ASYNC', part_number: 'PN-ASYNC', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-async', line_allowed_actions: ['release_onhand_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }],
},
},
},
@@ -3033,7 +3033,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
await openLineOverflowMenu(wrapper, 1002);
await clickLineMenuItem(1002, 'release_inventory_shortage');
await clickLineMenuItem(1002, 'release_onhand_shortage');
await wrapper.get('[data-testid="review-fulfillment-release-input-1002-102"]').setValue('A-01');
await wrapper.get('[data-testid="review-fulfillment-release-confirm-1002"]').trigger('click');
await new Promise<void>((resolve) => setTimeout(resolve, 0));
@@ -3071,9 +3071,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
draft_line_id: 'line-manual',
snapshot_line_id: 1003,
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
line_allowed_actions: ['release_inventory_shortage'],
line_allowed_actions: ['release_onhand_shortage'],
release_template_fields: [
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false },
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
],
release_required_fields: [{ field_id: '102', display_name: '库位' }],
@@ -3092,7 +3092,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
stage_context: releaseAccepted ? { upload: {} } : {
preparation: {
frozen_order_lines: [{ snapshot_line_id: 1003, line_no: 1, reservation_id: 'RSV-MANUAL', part_number: 'PN-MANUAL', required_qty: '6' }],
lines: [{ snapshot_line_id: 1003, line_no: 1, reservation_id: 'RSV-MANUAL', part_number: 'PN-MANUAL', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-manual', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }],
lines: [{ snapshot_line_id: 1003, line_no: 1, reservation_id: 'RSV-MANUAL', part_number: 'PN-MANUAL', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-manual', line_allowed_actions: ['release_onhand_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }],
},
},
},
@@ -3108,7 +3108,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await openLineOverflowMenu(wrapper, 1003);
await clickLineMenuItem(1003, 'release_inventory_shortage');
await clickLineMenuItem(1003, 'release_onhand_shortage');
await wrapper.get('[data-testid="review-fulfillment-release-input-1003-102"]').setValue('A-01');
await wrapper.get('[data-testid="review-fulfillment-release-confirm-1003"]').trigger('click');
await wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').findAll('button')[1].trigger('click');
@@ -3354,7 +3354,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
process_gate: {
gate_status: 'blocked_retryable', blocking_reason_code: 'inventory_file_missing',
primary_action: { code: 'retry_inventory_preparation', label_key: 'retry_inventory_preparation' },
primary_action: { code: 'retry_onhand_preparation', label_key: 'retry_onhand_preparation' },
},
},
} as any);
@@ -3710,7 +3710,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
primary: {
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
dispatch: 'mutation',
target_surface: 'fulfillment_prep', target_anchor: 'inventory_matching',
target_surface: 'fulfillment_prep', target_anchor: 'onhand_matching',
requires_confirmation: false,
},
secondary: [],
@@ -4340,7 +4340,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
shippingNoticeNo: 'SN-OT-WAITING-INVENTORY',
retryable: true,
userStatus: 'retryable',
primaryAction: { code: 'retry_inventory_preparation' },
primaryAction: { code: 'retry_onhand_preparation' },
currentGate: { status: 'blocked_retryable' },
inventoryPreparation: {
activeAttemptCount: 1,
@@ -4349,7 +4349,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
},
uiState: {
status: 'retryable',
primary_action: { code: 'retry_inventory_preparation' },
primary_action: { code: 'retry_onhand_preparation' },
secondary_actions: [],
},
};
@@ -4358,7 +4358,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
ui_state: {
actions: {
primary: {
code: 'retry_inventory_preparation', kind: 'recovery', enabled: true,
code: 'retry_onhand_preparation', kind: 'recovery', enabled: true,
dispatch: 'mutation', requires_confirmation: false,
},
secondary: [],
@@ -4366,7 +4366,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
process_gate: {
execution_no: 'EXEC-INVENTORY-WAITING',
current_blocking_gate: {
gate_code: 'inventory_preparation', evaluation_version: 1,
gate_code: 'onhand_preparation', evaluation_version: 1,
},
},
summary: {}, steps: [],
@@ -4418,8 +4418,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
confirmed_task_no: 'SN-WAIT-1',
// 故意与 Progress 文案分叉:若宽屏仍直读 Case code,会显示「库存匹配」。
current_stage: {
code: 'inventory_matching',
label_key: 'inventory_matching',
code: 'onhand_matching',
label_key: 'onhand_matching',
inconsistent: false,
},
automation: {
@@ -850,7 +850,7 @@ const formalTaskActions = computed(() => {
/** 行级库存选源动作:只在表格逐行处理,禁止作为任务级按钮出现在右侧"当前任务"卡(避免与表格打勾重复)。 */
const LINE_SCOPE_INVENTORY_ACTIONS = new Set([
'override_line_inventory_source',
'override_line_onhand_source',
]);
/**
@@ -1888,7 +1888,7 @@ async function executeFormalTaskAction(
await nextTick();
scrollWorkbenchAnchor('review-fulfillment-prep-workspace');
},
inventory_upload: () => scrollWorkbenchAnchor('review-formal-task-todo-panel'),
onhand_upload: () => scrollWorkbenchAnchor('review-formal-task-todo-panel'),
order_fields: () => scrollWorkbenchAnchor('review-order-lines-table'),
reservation: () => scrollWorkbenchAnchor('review-order-lines-table'),
duplicate_review: () => scrollWorkbenchAnchor('review-duplicate-panel'),
@@ -2009,7 +2009,7 @@ async function handleCurrentTaskAction(
await nextTick();
scrollWorkbenchAnchor('review-formal-task-result-region');
break;
case 'open_inventory_match_review':
case 'open_onhand_match_review':
if (hasFormalOt.value) {
// 正式 OT 后匹配/缺口语境的真实宿主是通知准备工作区;订单明细表不承载库存结果。
scrollWorkbenchAnchor('review-fulfillment-prep-workspace');
@@ -2043,7 +2043,7 @@ async function handleCurrentTaskAction(
}
break;
}
case 'retry_inventory_matching': {
case 'retry_onhand_matching': {
const summary = displayCase.value?.process_gate;
if (!summary) return;
const result = await submitProcessGatePrimaryAction(summary, { actionCode: code });
@@ -2740,13 +2740,13 @@ async function submitLineOdmChoice(line: { snapshot_line_id?: number | null }) {
function formalPreparationLineAllows(
line: { snapshot_line_id?: number | null },
action: 'retry_inventory_preparation' | 'retry_inventory_matching' | 'close_unfulfillable' | 'release_inventory_shortage',
action: 'retry_onhand_preparation' | 'retry_onhand_matching' | 'close_unfulfillable' | 'release_onhand_shortage',
): boolean {
const fulfillment = formalPreparationLineFulfillment(line);
if (action === 'close_unfulfillable' || action === 'release_inventory_shortage') {
if (action === 'close_unfulfillable' || action === 'release_onhand_shortage') {
return Boolean(
fulfillment?.line_allowed_actions?.includes(action)
&& (action !== 'release_inventory_shortage' || !fulfillment?.release_field_resolution_error),
&& (action !== 'release_onhand_shortage' || !fulfillment?.release_field_resolution_error),
);
}
return Boolean(fulfillment?.inventory_allowed_actions?.includes(action));
@@ -2758,7 +2758,7 @@ function formalPreparationLineAllows(
*/
function formalPreparationLineStatusLabel(line: { snapshot_line_id?: number | null; status?: string | null; shortage_qty?: string | number | null }): string {
const fulfillment = formalPreparationLineFulfillment(line);
if (fulfillment?.decision?.decision_code === 'release_inventory_shortage') {
if (fulfillment?.decision?.decision_code === 'release_onhand_shortage') {
return t('chat.shippingOrderReview.lifecycle.prepare.releaseShortage');
}
const status = String(line.status || '').trim().toLowerCase();
@@ -2807,7 +2807,7 @@ async function confirmReleaseInventoryShortage() {
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(line.draft_line_id || ''),
decision_code: 'release_inventory_shortage',
decision_code: 'release_onhand_shortage',
reason,
release_field_values: releaseInventoryFieldValues.value,
expected_draft_version: activeCase.value?.draft?.draft_version,
@@ -2896,7 +2896,7 @@ function releaseBarReadyFor(line: { snapshot_line_id?: number | null }): boolean
const fulfillment = formalPreparationLineFulfillment(line);
const required = releaseBarLineRequiredFields(line);
return Boolean(
fulfillment?.line_allowed_actions?.includes('release_inventory_shortage')
fulfillment?.line_allowed_actions?.includes('release_onhand_shortage')
&& required.every((field) => releaseBarValue(line, field).trim())
&& !releaseBarBusy.value[releaseBarKey(line)],
);
@@ -2917,7 +2917,7 @@ async function confirmReleaseBar(line: { snapshot_line_id?: number | null }) {
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(fulfillment.draft_line_id || ''),
decision_code: 'release_inventory_shortage',
decision_code: 'release_onhand_shortage',
reason: '',
release_field_values: { ...(releaseBarValues.value[key] || {}) },
expected_draft_version: activeCase.value?.draft?.draft_version,
@@ -3011,7 +3011,7 @@ async function downloadFormalPreparationLineInventoryFile(line: {
/** 行级恢复提交当前 Gate 的精确动作,使用冻结快照行身份。 */
async function retryFormalPreparationLine(
snapshotLineId: number | string,
actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching',
actionCode: 'retry_onhand_preparation' | 'retry_onhand_matching',
) {
if (!snapshotLineId) return;
await submitFormalGateAction(actionCode, { snapshot_line_id: Number(snapshotLineId) });
@@ -3132,20 +3132,20 @@ function overflowItems(line: {
shortage_qty?: string | number | null;
}): Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise<void> }> {
const items: Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise<void> }> = [];
if (formalPreparationLineAllows(line, 'retry_inventory_matching')) {
if (formalPreparationLineAllows(line, 'retry_onhand_matching')) {
items.push({
key: 'retry_inventory_matching',
key: 'retry_onhand_matching',
icon: RefreshCw,
labelKey: inventoryActionLabelKey('retry_inventory_matching')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_matching'),
labelKey: inventoryActionLabelKey('retry_onhand_matching')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_onhand_matching'),
});
}
// 放行缺口:缺字段型短缺行 → 行内展开补录条(替代弹窗);仅缺原因的行 → 旧弹窗(原因已可选)。
if (formalPreparationLineAllows(line, 'release_inventory_shortage')) {
if (formalPreparationLineAllows(line, 'release_onhand_shortage')) {
items.push({
key: 'release_inventory_shortage',
key: 'release_onhand_shortage',
icon: Check,
labelKey: inventoryActionLabelKey('release_inventory_shortage')!,
labelKey: inventoryActionLabelKey('release_onhand_shortage')!,
run: () => {
if (releaseBarHasFields(line)) expandReleaseBar(line);
else openReleaseInventoryShortage(line);
@@ -3160,19 +3160,19 @@ function overflowItems(line: {
run: () => openCloseLineDialog(line),
});
}
if (formalPreparationLineAllows(line, 'retry_inventory_preparation')) {
if (formalPreparationLineAllows(line, 'retry_onhand_preparation')) {
items.push({
key: 'retry_inventory_preparation',
key: 'retry_onhand_preparation',
icon: Bot,
labelKey: inventoryActionLabelKey('retry_inventory_preparation')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_preparation'),
labelKey: inventoryActionLabelKey('retry_onhand_preparation')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_onhand_preparation'),
});
}
if (formalPreparationLineInventoryFileNo(line)) {
items.push({
key: 'download_inventory_file',
key: 'download_onhand_file',
icon: Download,
labelKey: inventoryActionLabelKey('download_inventory_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory',
labelKey: inventoryActionLabelKey('download_onhand_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory',
run: () => downloadFormalPreparationLineInventoryFile(line),
});
}
@@ -3246,7 +3246,7 @@ async function saveInlineEdit(line: {
}
// 库存源覆写沿用既有 Gate 动作(override_line_inventory_source),后端校验后仅重匹配该行。
if (sourceChanged) {
await submitFormalGateAction('override_line_inventory_source', {
await submitFormalGateAction('override_line_onhand_source', {
line_no: draft.line_no,
source_code: nextSourceCode,
});
@@ -3778,7 +3778,7 @@ const preparationWaveSelectableLines = computed(() => formalPreparationLines.val
if (!fulfillment) return false;
if (['task_created', 'fulfilled', 'closed_unfulfillable'].includes(String(fulfillment.line_status || ''))) return false;
return Boolean(fulfillment.can_fulfill_complete_line)
|| fulfillment.decision?.decision_code === 'release_inventory_shortage';
|| fulfillment.decision?.decision_code === 'release_onhand_shortage';
}));
const allPreparationWaveSelected = computed(() => (
preparationWaveSelectableLines.value.length > 0
@@ -1,8 +1,8 @@
/**
* features/shipping-notice/shippingI18nParity.spec.ts
* 用途:验证货代发货通知业务域在四种语言中的文案键保持一致。
* 依赖:admin/chat/workspace 四语言 JSON;只检查货代业务子树,不受其他历史业务域影响。
* 逻辑:递归收集叶子键并比较集合;覆盖 Schema/库存/聊天通知/会话摘要/工作台待办。
* 依赖:admin/chat/workspace/errors 四语言 JSON;errors 比较全文件叶子键,其余只检查货代业务子树。
* 逻辑:递归收集叶子键并比较集合;覆盖 Schema/库存/聊天通知/会话摘要/工作台待办/errors.json。
*/
import { describe, expect, it } from 'vitest';
@@ -15,6 +15,10 @@ import chatEn from '@/locales/en/chat.json';
import chatTh from '@/locales/th/chat.json';
import chatZhCn from '@/locales/zh-CN/chat.json';
import chatZhTw from '@/locales/zh-TW/chat.json';
import errorsEn from '@/locales/en/errors.json';
import errorsTh from '@/locales/th/errors.json';
import errorsZhCn from '@/locales/zh-CN/errors.json';
import errorsZhTw from '@/locales/zh-TW/errors.json';
import workspaceEn from '@/locales/en/workspace.json';
import workspaceTh from '@/locales/th/workspace.json';
import workspaceZhCn from '@/locales/zh-CN/workspace.json';
@@ -46,10 +50,10 @@ describe('shipping notice i18n parity', () => {
it('keeps admin inventory configuration keys aligned', () => {
expectSameKeys([
adminZhCn.shippingInventory as LocaleTree,
adminZhTw.shippingInventory as LocaleTree,
adminEn.shippingInventory as LocaleTree,
adminTh.shippingInventory as LocaleTree,
adminZhCn.freightRpa as LocaleTree,
adminZhTw.freightRpa as LocaleTree,
adminEn.freightRpa as LocaleTree,
adminTh.freightRpa as LocaleTree,
]);
});
@@ -71,6 +75,15 @@ describe('shipping notice i18n parity', () => {
]);
});
it('keeps errors.json keys aligned', () => {
expectSameKeys([
errorsZhCn as LocaleTree,
errorsZhTw as LocaleTree,
errorsEn as LocaleTree,
errorsTh as LocaleTree,
]);
});
it('keeps workspace shipping notice keys aligned', () => {
expectSameKeys([
workspaceZhCn.shippingNotice as LocaleTree,
@@ -92,7 +92,7 @@ describe('ProcessGateRecoveryCard', () => {
technical_auto_only: true,
owner_type: 'system',
responsible_party: 'worker',
next_action_code: 'retry_inventory_preparation',
next_action_code: 'retry_onhand_preparation',
}),
canHandle: false,
},
@@ -148,15 +148,15 @@ describe('ProcessGateRecoveryCard', () => {
summary: baseSummary({
current_blocking_gate: {
...baseSummary().current_blocking_gate!,
gate_code: 'inventory_matching',
next_action_code: 'open_inventory_match_review',
gate_code: 'onhand_matching',
next_action_code: 'open_onhand_match_review',
},
next_action_code: 'open_inventory_match_review',
next_action_code: 'open_onhand_match_review',
recovery_targets: [{
action_code: 'retry_inventory_from_preparation',
target_gate: 'inventory_preparation',
resume_after_gate: 'inventory_matching',
invalidates: ['inventory_snapshot'],
action_code: 'retry_onhand_from_preparation',
target_gate: 'onhand_preparation',
resume_after_gate: 'onhand_matching',
invalidates: ['onhand_snapshot'],
}],
}),
canHandle: true,
@@ -185,11 +185,11 @@ describe('ProcessGateRecoveryCard', () => {
summary: baseSummary({
current_blocking_gate: {
...baseSummary().current_blocking_gate!,
gate_code: 'inventory_preparation',
next_action_code: 'retry_inventory_preparation',
gate_code: 'onhand_preparation',
next_action_code: 'retry_onhand_preparation',
},
next_action_code: 'retry_inventory_preparation',
allowed_actions: ['retry_inventory_preparation'],
next_action_code: 'retry_onhand_preparation',
allowed_actions: ['retry_onhand_preparation'],
task_no: 'SN-TEST-001',
navigation: { target: 'task_workspace', task_no: 'SN-TEST-001' },
}),
@@ -209,10 +209,10 @@ describe('ProcessGateRecoveryCard', () => {
summary: baseSummary({
current_blocking_gate: {
...baseSummary().current_blocking_gate!,
gate_code: 'inventory_matching',
next_action_code: 'retry_inventory_from_preparation',
gate_code: 'onhand_matching',
next_action_code: 'retry_onhand_from_preparation',
},
next_action_code: 'retry_inventory_from_preparation',
next_action_code: 'retry_onhand_from_preparation',
}),
canHandle: true,
},
@@ -42,15 +42,15 @@ function summary() {
execution_no: 'EXEC-1',
status: 'blocked',
current_blocking_gate: {
gate_code: 'inventory_matching',
gate_code: 'onhand_matching',
evaluation_version: 3,
status: 'blocked',
},
primary_action: {
code: 'retry_inventory_matching',
code: 'retry_onhand_matching',
dispatch: 'mutation',
},
allowed_actions: ['retry_inventory_matching'],
allowed_actions: ['retry_onhand_matching'],
} as never;
}
@@ -60,7 +60,7 @@ function capabilitySummary() {
execution_no: 'EXEC-1',
status: 'blocked',
current_blocking_gate: {
gate_code: 'inventory_field_mapping',
gate_code: 'onhand_field_mapping',
evaluation_version: 5,
status: 'blocked',
},
@@ -92,7 +92,7 @@ describe('useShippingProcessGateRecovery', () => {
postActionMock.mockResolvedValue({
dispatch: 'async_job',
execution_no: 'EXEC-1',
gate_code: 'inventory_matching',
gate_code: 'onhand_matching',
attempt: { id: 9, status: 'queued' },
});
});
@@ -101,7 +101,7 @@ describe('useShippingProcessGateRecovery', () => {
const { exposed, app } = mountComposable();
const result = await exposed.submitPrimaryAction(summary(), {
actionCode: 'retry_inventory_matching',
actionCode: 'retry_onhand_matching',
});
expect(result.outcome).toBe('submitted');
@@ -117,7 +117,7 @@ describe('useShippingProcessGateRecovery', () => {
const { exposed, app } = mountComposable();
const result = await exposed.submitPrimaryAction(capabilitySummary(), {
actionCode: 'override_line_inventory_source',
actionCode: 'override_line_onhand_source',
stageCapabilityBypass: true,
});
@@ -126,8 +126,8 @@ describe('useShippingProcessGateRecovery', () => {
expect(getExecutionMock).not.toHaveBeenCalled();
expect(postActionMock).toHaveBeenCalledWith(
'EXEC-1',
'inventory_field_mapping',
expect.objectContaining({ action_code: 'override_line_inventory_source' }),
'onhand_field_mapping',
expect.objectContaining({ action_code: 'override_line_onhand_source' }),
);
app.unmount();
@@ -138,18 +138,18 @@ describe('useShippingProcessGateRecovery', () => {
const result = await exposed.submitPrimaryAction({
execution_no: 'EXEC-1',
status: 'processing',
current_gate: { gate_code: 'inventory_preparation', evaluation_version: 7, status: 'running' },
current_gate: { gate_code: 'onhand_preparation', evaluation_version: 7, status: 'running' },
allowed_actions: [],
recovery_targets: [],
} as never, {
actionCode: 'retry_inventory_preparation',
actionCode: 'retry_onhand_preparation',
stageCapabilityBypass: true,
});
expect(result.outcome).toBe('submitted');
expect(postActionMock).toHaveBeenCalledWith(
'EXEC-1',
'inventory_preparation',
expect.objectContaining({ action_code: 'retry_inventory_preparation' }),
'onhand_preparation',
expect.objectContaining({ action_code: 'retry_onhand_preparation' }),
);
app.unmount();
});
@@ -8,8 +8,8 @@
*/
import type {
ShippingExplainabilityReason,
ShippingInventorySourceLineBlockReasonCode,
ShippingInventorySourceUnavailableReasonCode,
ShippingOnhandSourceLineBlockReasonCode,
ShippingOnhandSourceUnavailableReasonCode,
ShippingProcessGateActionCode,
ShippingProcessGateActionPresentation,
ShippingProcessGateCode,
@@ -21,8 +21,8 @@ import type {
export type {
ShippingExplainabilityReason,
ShippingInventorySourceLineBlockReasonCode,
ShippingInventorySourceUnavailableReasonCode,
ShippingOnhandSourceLineBlockReasonCode,
ShippingOnhandSourceUnavailableReasonCode,
ShippingProcessGateActionCode,
ShippingProcessGateActionPresentation,
ShippingProcessGateCode,
@@ -24,7 +24,7 @@ function projection(
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'blocked',
stage: 'inventory_source_resolving',
stage: 'onhand_source_resolving',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
@@ -103,7 +103,7 @@ describe('resolveProcessingActionPresentation', () => {
it('does not turn diagnostic gate nextActionCode into a user action', () => {
const result = resolveProcessingActionPresentation(projection({
currentGate: {
gateCode: 'inventory_source_routing',
gateCode: 'onhand_source_routing',
status: 'blocked',
nextActionCode: 'open_inventory_source_review',
blockingReasonCode: 'no_inventory_source_candidates',
@@ -118,21 +118,21 @@ describe('resolveProcessingActionPresentation', () => {
const result = resolveProcessingActionPresentation(projection({
status: 'processing',
currentGate: {
gateCode: 'inventory_source_routing', status: 'blocked', nextActionCode: 'retry',
gateCode: 'onhand_source_routing', status: 'blocked', nextActionCode: 'retry',
blockingReasonCode: null, attemptNo: 1,
},
primaryAction: { code: 'retry_parse', i18nKey: 'action.retry_parse', parameters: {} },
availableActions: ['retry_parse', 'view_result'],
uiState: {
status: 'waiting_human', stage: 'fulfillment_prep', blocking_reason: null,
primary_action: { code: 'retry_inventory_preparation', i18nKey: 'action.retry_inventory_preparation', parameters: {} },
primary_action: { code: 'retry_onhand_preparation', i18nKey: 'action.retry_onhand_preparation', parameters: {} },
secondary_actions: [
{ code: 'view_details', enabled: true },
{ code: 'retry_parse', enabled: false },
],
},
}));
expect(result.primary?.actionCode).toBe('retry_inventory_preparation');
expect(result.primary?.actionCode).toBe('retry_onhand_preparation');
expect(result.secondary?.actionCode).toBe('view_details');
expect(result.overflow).toEqual([]);
});
@@ -230,10 +230,10 @@ describe('resolveProcessingActionPresentation', () => {
const result = resolveProcessingActionPresentation(projection({
status: 'waiting_human',
uiState: {
status: 'waiting_human', stage: 'inventory_fetching', blocking_reason: null,
status: 'waiting_human', stage: 'onhand_fetching', blocking_reason: null,
primary_action: {
code: 'retry_inventory_preparation',
i18nKey: 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
code: 'retry_onhand_preparation',
i18nKey: 'workspace.shippingNotice.processGate.actionCodes.retry_onhand_preparation',
parameters: {},
},
// Gate 工作台可保留受控上传入口;批次卡只消费 primary_action。
@@ -242,7 +242,7 @@ describe('resolveProcessingActionPresentation', () => {
}), { surface: 'right' });
expect(result.primary).toMatchObject({
actionCode: 'retry_inventory_preparation',
actionCode: 'retry_onhand_preparation',
labelKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
});
expect(result.secondary).toBeNull();
@@ -251,14 +251,14 @@ describe('resolveProcessingActionPresentation', () => {
it('uses the shared inventory presentation for a rematch action', () => {
const result = resolveProcessingActionPresentation(projection({
uiState: {
status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null,
primary_action: { code: 'retry_inventory_matching', i18nKey: null, parameters: {} },
status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null,
primary_action: { code: 'retry_onhand_matching', i18nKey: null, parameters: {} },
secondary_actions: [],
},
}), { surface: 'right' });
expect(result.primary).toMatchObject({
actionCode: 'retry_inventory_matching',
actionCode: 'retry_onhand_matching',
labelKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
});
});
@@ -332,7 +332,7 @@ describe('resolveProcessingActionPresentation', () => {
it('preserves a backend-directed fulfillment preparation target for review navigation', () => {
const result = resolveProcessingActionPresentation(projection({
uiState: {
status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null,
status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null,
primary_action: {
code: 'view_result',
targetLifecycleStage: 'fulfillment_prep',
@@ -351,7 +351,7 @@ describe('resolveProcessingActionPresentation', () => {
it('preserves a backend-directed fulfillment target on a secondary action', () => {
const result = resolveProcessingActionPresentation(projection({
uiState: {
status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null,
status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null,
primary_action: null,
secondary_actions: [{
code: 'view_result', enabled: true,
@@ -373,7 +373,7 @@ describe('resolveProcessingActionPresentation', () => {
const result = resolveConversationTaskActionPresentation({
task_no: 'SN-1', group: 'needs_action', status_label: 'waiting_human',
uiState: {
status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null,
status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null,
primary_action: null,
secondary_actions: [{
code: 'view_result', enabled: true,
@@ -32,11 +32,11 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
confirm_customer: 'confirm_customer',
resolve_field_conflicts: 'resolve_field_conflicts',
adjudicate_duplicate: 'adjudicate_duplicate',
open_inventory_match_review: 'open_inventory_match_review',
open_onhand_match_review: 'open_onhand_match_review',
open_shortage_review: 'open_shortage_review',
reload_inventory_result: 'reload_inventory_result',
retry_inventory_preparation: 'retry_inventory_preparation',
retry_inventory_matching: 'retry_inventory_matching',
reload_onhand_result: 'reload_onhand_result',
retry_onhand_preparation: 'retry_onhand_preparation',
retry_onhand_matching: 'retry_onhand_matching',
reparse_batch: 'reparse_batch',
retry_parse: 'retry_parse',
retry_failed_documents: 'retry_failed_documents',
@@ -52,10 +52,10 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
retry_with_latest_rules: 'retry_with_latest_rules',
recheck_freeze_readiness: 'recheck_freeze_readiness',
retry_task_creation: 'retry_task_creation',
retry_inventory_field_mapping: 'retry_inventory_field_mapping',
recheck_inventory_sufficiency: 'recheck_inventory_sufficiency',
retry_onhand_field_mapping: 'retry_onhand_field_mapping',
recheck_onhand_sufficiency: 'recheck_onhand_sufficiency',
recheck_excel_readiness: 'recheck_excel_readiness',
poll_inventory_preparation: 'refresh',
poll_onhand_preparation: 'refresh',
poll_freight_upload_rpa: 'refresh',
edit_order_fields: 'open_order_review',
edit_reservation: 'open_order_review',
@@ -86,13 +86,13 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
/** 需要在聊天/右侧展示精确恢复动作文案的正式 action_code。 */
const RECOVERY_ACTION_CODES = new Set([
'reload_inventory_result',
'retry_inventory_preparation', 'retry_inventory_matching', 'retry_parse',
'reload_onhand_result',
'retry_onhand_preparation', 'retry_onhand_matching', 'retry_parse',
'retry_failed_documents', 'retry_failed_attachments', 'retry_freight_upload_rpa',
'retry_order_extraction', 'retry_layout_parsing', 'rematerialize_document',
'reroute_document_profile', 'revalidate_reservation', 'retry_customer_resolution',
'retry_duplicate_detection', 'retry_with_latest_rules', 'recheck_freeze_readiness',
'retry_task_creation', 'retry_inventory_field_mapping', 'recheck_inventory_sufficiency',
'retry_task_creation', 'retry_onhand_field_mapping', 'recheck_onhand_sufficiency',
'recheck_excel_readiness', 'retry_stp_auto_create', 'reparse',
]);
/** 永不升为主 CTA 的动作码(仍可作次要/溢出)。 */
@@ -113,13 +113,13 @@ const FILE_ROW_NAVIGATION_CODES = new Set([
* 或 retry_inventory_matching 等稳定动作码。
*/
const INTERNAL_INVENTORY_ACTION_CODES = new Set([
'retry_inventory_from_preparation',
'retry_inventory_from_matching',
'retry_inventory_field_mapping',
'retry_inventory_from_field_mapping',
'poll_inventory_preparation',
'refresh_inventory_candidate_projection',
'recheck_inventory_sufficiency',
'retry_onhand_from_preparation',
'retry_onhand_from_matching',
'retry_onhand_field_mapping',
'retry_onhand_from_field_mapping',
'poll_onhand_preparation',
'refresh_onhand_candidate_projection',
'recheck_onhand_sufficiency',
]);
/**
@@ -131,13 +131,13 @@ const INTERNAL_INVENTORY_ACTION_CODES = new Set([
export function inventoryActionLabelKey(code: string | null | undefined): string | null {
const normalized = String(code || '').trim().toLowerCase();
const keyByCode: Record<string, string> = {
reload_inventory_result: 'workspace.shippingNotice.processGate.inventoryActions.reloadInventoryResult',
retry_inventory_preparation: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
retry_inventory_matching: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
open_inventory_match_review: 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
reload_onhand_result: 'workspace.shippingNotice.processGate.inventoryActions.reloadInventoryResult',
retry_onhand_preparation: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
retry_onhand_matching: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
open_onhand_match_review: 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
open_shortage_review: 'workspace.shippingNotice.processGate.inventoryActions.openShortageReview',
download_inventory_file: 'workspace.shippingNotice.processGate.inventoryActions.downloadInventoryFile',
release_inventory_shortage: 'workspace.shippingNotice.processGate.inventoryActions.releaseInventoryShortage',
download_onhand_file: 'workspace.shippingNotice.processGate.inventoryActions.downloadInventoryFile',
release_onhand_shortage: 'workspace.shippingNotice.processGate.inventoryActions.releaseInventoryShortage',
};
return keyByCode[normalized] || null;
}
@@ -135,18 +135,18 @@ describe('ReviewProgressStrip', () => {
const wrapper = mountStrip(buildProjection({
status: 'automating',
userStatus: 'waiting_human',
stage: 'inventory_fetching',
stage: 'onhand_fetching',
currentGate: {
gateCode: 'inventory_preparation',
gateCode: 'onhand_preparation',
status: 'blocked_manual',
nextActionCode: 'upload_inventory_file',
nextActionCode: 'upload_onhand_file',
blockingReasonCode: 'inventory_file_empty',
attemptNo: 3,
},
}), true);
const title = wrapper.get('[data-testid="review-progress-title"]').text();
expect(title).toContain('待人工处理');
expect(title).toContain('inventory_fetching');
expect(title).toContain('onhand_fetching');
expect(title).not.toContain('系统处理中');
expect(wrapper.find('[data-testid="review-progress-refresh"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-workflow-progress-polling"]').exists()).toBe(false);
@@ -19,7 +19,7 @@ function base(overrides: Partial<ShippingProcessingProjection> = {}): ShippingPr
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'blocked',
stage: 'inventory_matching',
stage: 'onhand_matching',
progressVersion: 3,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
@@ -41,12 +41,12 @@ function base(overrides: Partial<ShippingProcessingProjection> = {}): ShippingPr
describe('mergeWorkbenchProcessingProjection', () => {
it('discards stale incoming with lower progressVersion', () => {
const local = base({ progressVersion: 5, stage: 'excel_generating' });
const incoming = base({ progressVersion: 4, stage: 'inventory_matching' });
const incoming = base({ progressVersion: 4, stage: 'onhand_matching' });
expect(mergeWorkbenchProcessingProjection(local, incoming)).toBe(local);
});
it('replaces whole projection when incoming version is newer', () => {
const local = base({ progressVersion: 5, stage: 'inventory_matching' });
const local = base({ progressVersion: 5, stage: 'onhand_matching' });
const incoming = base({ progressVersion: 6, stage: 'excel_generating', availableActions: ['download_excel'] });
expect(mergeWorkbenchProcessingProjection(local, incoming)).toEqual(incoming);
});
@@ -27,7 +27,7 @@ function baseProjection(
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'blocked',
stage: 'inventory_source_resolving',
stage: 'onhand_source_resolving',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
@@ -47,8 +47,8 @@ function baseProjection(
}
describe('progressWindow', () => {
it('anchors inventory_source_resolving at index 7', () => {
expect(stageAbsoluteIndex('inventory_source_resolving')).toBe(7);
it('anchors onhand_source_resolving at index 7', () => {
expect(stageAbsoluteIndex('onhand_source_resolving')).toBe(7);
});
it('workbench shows all 15 stages', () => {
@@ -85,11 +85,11 @@ describe('progressWindow', () => {
it('prefers backend stageNodes status over index heuristic', () => {
const nodes = buildProgressWindow(baseProjection({
stage: 'inventory_source_resolving',
stage: 'onhand_source_resolving',
status: 'processing',
stageNodes: [
{ stage: 'upload_received', absoluteIndex: 0, status: 'passed' },
{ stage: 'inventory_source_resolving', absoluteIndex: 7, status: 'failed' },
{ stage: 'onhand_source_resolving', absoluteIndex: 7, status: 'failed' },
],
}), 'workbench');
expect(nodes[7]?.status).toBe('failed');
@@ -25,11 +25,11 @@ describe('stageMapping', () => {
candidate_creating: 'intake_parse',
customer_resolving: 'order_review',
duplicate_checking: 'order_review',
inventory_source_resolving: 'order_review',
onhand_source_resolving: 'order_review',
waiting_review: 'order_review',
order_creating: 'fulfillment_prep',
inventory_fetching: 'fulfillment_prep',
inventory_matching: 'fulfillment_prep',
onhand_fetching: 'fulfillment_prep',
onhand_matching: 'fulfillment_prep',
excel_generating: 'fulfillment_prep',
freight_uploading: 'freight_upload',
completed: 'upload_complete',
@@ -41,8 +41,8 @@ describe('stageMapping', () => {
});
it('过渡态归入对应业务标签(库存准备/充足性→通知准备;人工上传交接→货代上传)', () => {
expect(mapProcessingStageToLifecycle('inventory_preparation')).toBe('fulfillment_prep');
expect(mapProcessingStageToLifecycle('inventory_sufficiency')).toBe('fulfillment_prep');
expect(mapProcessingStageToLifecycle('onhand_preparation')).toBe('fulfillment_prep');
expect(mapProcessingStageToLifecycle('onhand_sufficiency')).toBe('fulfillment_prep');
expect(mapProcessingStageToLifecycle('manual_upload_handoff')).toBe('freight_upload');
});
@@ -44,14 +44,14 @@ export const SHIPPING_STAGE_TO_LIFECYCLE: Record<string, LifecycleStageCode> = {
candidate_creating: 'intake_parse',
customer_resolving: 'order_review',
duplicate_checking: 'order_review',
inventory_source_resolving: 'order_review',
onhand_source_resolving: 'order_review',
waiting_review: 'order_review',
order_creating: 'fulfillment_prep',
inventory_fetching: 'fulfillment_prep',
onhand_fetching: 'fulfillment_prep',
// 过渡态:库存准备/充足性归入通知准备。
inventory_preparation: 'fulfillment_prep',
inventory_matching: 'fulfillment_prep',
inventory_sufficiency: 'fulfillment_prep',
onhand_preparation: 'fulfillment_prep',
onhand_matching: 'fulfillment_prep',
onhand_sufficiency: 'fulfillment_prep',
excel_generating: 'fulfillment_prep',
freight_uploading: 'freight_upload',
// 过渡态:人工上传交接归入货代上传。
@@ -27,7 +27,7 @@ function projection(
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'blocked',
stage: 'inventory_matching',
stage: 'onhand_matching',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
@@ -53,7 +53,7 @@ describe('workbenchActionRegistry', () => {
it('registers Gate fulfillment actions and does not retain legacy aliases', () => {
for (const code of [
'retry_inventory_matching',
'retry_onhand_matching',
'mark_manual_uploaded',
'retry_freight_upload_rpa',
'regenerate_excel_artifact',
@@ -88,7 +88,7 @@ describe('workbenchActionRegistry', () => {
});
it('hides write actions when actionsExecutable=false but keeps view_result', () => {
expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.retry_inventory_matching, {
expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.retry_onhand_matching, {
actionsExecutable: false,
surface: 'review',
})).toBe(false);
@@ -113,64 +113,64 @@ describe('workbenchActionRegistry', () => {
expect(payload?.action_code).toBe('totally_unknown_action');
});
it('exposes Gate retry_inventory_matching as primary for review Footer', () => {
it('exposes Gate retry_onhand_matching as primary for review Footer', () => {
const result = resolveProcessingActionPresentation(projection({
uiState: {
status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null,
primary_action: { code: 'retry_inventory_matching', label_key: 'x' }, secondary_actions: [],
status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null,
primary_action: { code: 'retry_onhand_matching', label_key: 'x' }, secondary_actions: [],
},
currentGate: {
gateCode: 'inventory_match',
status: 'blocked',
nextActionCode: 'retry_inventory_matching',
nextActionCode: 'retry_onhand_matching',
blockingReasonCode: 'inventory_shortage',
attemptNo: 1,
},
availableActions: ['refresh'],
}), { surface: 'review', actionsExecutable: true });
expect(result.primary?.intent).toBe('retry_inventory_matching');
expect(result.primary?.actionCode).toBe('retry_inventory_matching');
expect(result.primary?.intent).toBe('retry_onhand_matching');
expect(result.primary?.actionCode).toBe('retry_onhand_matching');
expect(result.secondary).toBeNull();
});
it('routes backend retry_inventory_matching through the formal Gate todo action', () => {
it('routes backend retry_onhand_matching through the formal Gate todo action', () => {
const result = resolveProcessingActionPresentation(projection({
uiState: {
status: 'retryable', stage: 'inventory_matching', blocking_reason: null,
primary_action: { code: 'retry_inventory_matching', label_key: 'x' }, secondary_actions: [],
status: 'retryable', stage: 'onhand_matching', blocking_reason: null,
primary_action: { code: 'retry_onhand_matching', label_key: 'x' }, secondary_actions: [],
},
currentGate: {
gateCode: 'inventory_matching',
gateCode: 'onhand_matching',
status: 'blocked_retryable',
nextActionCode: 'retry_inventory_matching',
nextActionCode: 'retry_onhand_matching',
blockingReasonCode: 'inventory_match_failed',
attemptNo: 1,
},
}), { surface: 'review', actionsExecutable: true });
expect(result.primary?.actionCode).toBe('retry_inventory_matching');
expect(result.primary?.actionCode).toBe('retry_onhand_matching');
const resolved = resolveWorkbenchActionItem(result.primary!, { postCreate: true });
expect(resolved?.reviewBehavior).toBe('todo_panel');
expect(resolved?.todoActionCode).toBe('retry_inventory_matching');
expect(resolved?.todoActionCode).toBe('retry_onhand_matching');
});
it('routes merged inventory rematch through the formal Gate todo action', () => {
const result = resolveProcessingActionPresentation(projection({
uiState: {
status: 'retryable', stage: 'inventory_preparation', blocking_reason: null,
primary_action: { code: 'retry_inventory_matching', label_key: 'x' }, secondary_actions: [],
status: 'retryable', stage: 'onhand_preparation', blocking_reason: null,
primary_action: { code: 'retry_onhand_matching', label_key: 'x' }, secondary_actions: [],
},
currentGate: {
gateCode: 'inventory_preparation',
gateCode: 'onhand_preparation',
status: 'blocked_retryable',
nextActionCode: 'retry_inventory_matching',
nextActionCode: 'retry_onhand_matching',
},
}), { surface: 'review' });
const resolved = resolveWorkbenchActionItem(result.primary!, { postCreate: true });
expect(result.primary?.intent).toBe('retry_inventory_matching');
expect(result.primary?.intent).toBe('retry_onhand_matching');
expect(resolved?.reviewBehavior).toBe('todo_panel');
expect(resolved?.todoActionCode).toBe('retry_inventory_matching');
expect(resolved?.todoActionCode).toBe('retry_onhand_matching');
});
it('shows RPA upload retry instead of manual upload entries when Gate 19 is blocked', () => {
@@ -135,37 +135,37 @@ export const WORKBENCH_ACTION_REGISTRY: Record<string, WorkbenchActionRegistryEn
isWrite: true,
stageFamily: 'pre_create',
},
open_inventory_match_review: {
intent: 'open_inventory_match_review',
open_onhand_match_review: {
intent: 'open_onhand_match_review',
reviewBehavior: 'todo_panel',
todoActionCode: 'open_inventory_match_review',
todoActionCode: 'open_onhand_match_review',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
retry_inventory_matching: {
intent: 'retry_inventory_matching',
retry_onhand_matching: {
intent: 'retry_onhand_matching',
reviewBehavior: 'todo_panel',
todoActionCode: 'retry_inventory_matching',
todoActionCode: 'retry_onhand_matching',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
retry_inventory_preparation: {
intent: 'retry_inventory_preparation',
retry_onhand_preparation: {
intent: 'retry_onhand_preparation',
reviewBehavior: 'todo_panel',
todoActionCode: 'retry_inventory_preparation',
todoActionCode: 'retry_onhand_preparation',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
reload_inventory_result: {
intent: 'reload_inventory_result',
reload_onhand_result: {
intent: 'reload_onhand_result',
reviewBehavior: 'todo_panel',
todoActionCode: 'reload_inventory_result',
todoActionCode: 'reload_onhand_result',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
@@ -0,0 +1,24 @@
/**
* features/workspace/api/inbound-report.api.spec.ts
* 用途:锁定收料报表列表与下载地址的工作台契约。
* 依赖:inbound-report.api、vitest。
* 逻辑:普通接收人只能经工作台受控下载,不拼接对象存储地址。
*/
import { describe, expect, it } from 'vitest';
import {
listFailedInboundRpaUnits, inboundReportDownloadUrl, resendInboundReportFile, retryInboundRpaUnit,
} from './inbound-report.api';
describe('inboundReportDownloadUrl', () => {
it('uses the workspace authorization endpoint instead of an object storage URL', () => {
// 关键断言:浏览器只能使用后端鉴权下载代理,不能得到 MinIO bucket/key。
expect(inboundReportDownloadUrl(42)).toBe('/api/workspace/inbound-report-files/42/download');
});
it('keeps manual compensation routes in the admin namespace', () => {
expect(String(listFailedInboundRpaUnits)).toContain('inbound-rpa-units?status=failed');
expect(String(retryInboundRpaUnit)).toContain('/api/admin/inbound-rpa-units/');
expect(String(resendInboundReportFile)).toContain('/api/admin/inbound-report-files/');
});
});
@@ -1,5 +1,5 @@
/**
* features/workspace/api/receipt-report.api.ts
* features/workspace/api/inbound-report.api.ts
* 用途:工作台收料归档列表与受控下载 API。
* 依赖:requestJson、getAuthHeaders。
* 逻辑:列表由服务端按当前接收人/管理员授权裁剪;下载始终经过工作台鉴权代理。
@@ -8,7 +8,7 @@
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
export type ReceiptReportFile = {
export type InboundReportFile = {
id: number;
original_filename: string;
content_type?: string | null;
@@ -22,7 +22,7 @@ export type ReceiptReportFile = {
download_url: string;
};
export type ReceiptRpaUnit = {
export type InboundRpaUnit = {
id: number;
source_code: string;
warehouse_id?: string | null;
@@ -40,8 +40,8 @@ export type ReceiptRpaUnit = {
* 核心逻辑:不接收 user_id 或对象存储参数,服务端以当前会话和排程接收人关系授权。
* @returns 脱敏归档元数据和受控下载地址。
*/
export const listWorkspaceReceiptReportFiles = (limit = 100) => requestJson<{ items: ReceiptReportFile[] }>(
`/api/workspace/receipt-report-files?limit=${encodeURIComponent(String(limit))}`,
export const listWorkspaceInboundReportFiles = (limit = 100) => requestJson<{ items: InboundReportFile[] }>(
`/api/workspace/inbound-report-files?limit=${encodeURIComponent(String(limit))}`,
{ headers: getAuthHeaders() },
);
@@ -51,21 +51,21 @@ export const listWorkspaceReceiptReportFiles = (limit = 100) => requestJson<{ it
* @param fileId - 收料归档文件主键。
* @returns 由后端再次校验接收人权限的下载路径。
*/
export const receiptReportDownloadUrl = (fileId: number) => `/api/workspace/receipt-report-files/${encodeURIComponent(String(fileId))}/download`;
export const inboundReportDownloadUrl = (fileId: number) => `/api/workspace/inbound-report-files/${encodeURIComponent(String(fileId))}/download`;
/** 管理员读取失败收料单元;普通用户不调用此管理端接口。 */
export const listFailedReceiptRpaUnits = () => requestJson<{ items: ReceiptRpaUnit[] }>(
'/api/admin/receipt-rpa-units?status=failed&limit=100', { headers: getAuthHeaders() },
export const listFailedInboundRpaUnits = () => requestJson<{ items: InboundRpaUnit[] }>(
'/api/admin/inbound-rpa-units?status=failed&limit=100', { headers: getAuthHeaders() },
);
/** 管理员以必填原因新建失败单元的独立人工重试事实。 */
export const retryReceiptRpaUnit = (unitId: number, reason: string) => requestJson<unknown>(
`/api/admin/receipt-rpa-units/${encodeURIComponent(String(unitId))}/retry`,
export const retryInboundRpaUnit = (unitId: number, reason: string) => requestJson<unknown>(
`/api/admin/inbound-rpa-units/${encodeURIComponent(String(unitId))}/retry`,
{ method: 'POST', headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' }, body: JSON.stringify({ reason }) },
);
/** 管理员仅重发已归档文件的企微消息,不会重新导出。 */
export const resendReceiptReportFile = (fileId: number) => requestJson<unknown>(
`/api/admin/receipt-report-files/${encodeURIComponent(String(fileId))}/resend`,
export const resendInboundReportFile = (fileId: number) => requestJson<unknown>(
`/api/admin/inbound-report-files/${encodeURIComponent(String(fileId))}/resend`,
{ method: 'POST', headers: getAuthHeaders() },
);
@@ -1,24 +0,0 @@
/**
* features/workspace/api/receipt-report.api.spec.ts
* 用途:锁定收料报表列表与下载地址的工作台契约。
* 依赖:receipt-report.api、vitest。
* 逻辑:普通接收人只能经工作台受控下载,不拼接对象存储地址。
*/
import { describe, expect, it } from 'vitest';
import {
listFailedReceiptRpaUnits, receiptReportDownloadUrl, resendReceiptReportFile, retryReceiptRpaUnit,
} from './receipt-report.api';
describe('receiptReportDownloadUrl', () => {
it('uses the workspace authorization endpoint instead of an object storage URL', () => {
// 关键断言:浏览器只能使用后端鉴权下载代理,不能得到 MinIO bucket/key。
expect(receiptReportDownloadUrl(42)).toBe('/api/workspace/receipt-report-files/42/download');
});
it('keeps manual compensation routes in the admin namespace', () => {
expect(String(listFailedReceiptRpaUnits)).toContain('receipt-rpa-units?status=failed');
expect(String(retryReceiptRpaUnit)).toContain('/api/admin/receipt-rpa-units/');
expect(String(resendReceiptReportFile)).toContain('/api/admin/receipt-report-files/');
});
});
@@ -41,7 +41,7 @@ const i18n = createI18n({
admin: '管理控制台',
applications: '应用管理',
scheduleRuns: '排程记录',
receiptReports: '收料文件',
inboundReports: '收料文件',
shippingNotice: '货代发货',
shippingCustomers: '客户主数据',
shippingMyTasks: '我的待办',
@@ -68,7 +68,7 @@ async function mountSidebar(user: { role: string; is_platform_admin?: boolean })
{ path: WORKSPACE_PATHS.applications, name: 'workspace-applications', component: { template: '<div />' } },
{ path: WORKSPACE_PATHS.profile, name: 'workspace-profile', component: { template: '<div />' } },
{ path: WORKSPACE_PATHS.scheduleRuns, name: 'workspace-schedule-runs', component: { template: '<div />' } },
{ path: WORKSPACE_PATHS.receiptReports, name: 'workspace-receipt-reports', component: { template: '<div />' } },
{ path: WORKSPACE_PATHS.inboundReports, name: 'workspace-inbound-reports', component: { template: '<div />' } },
{ path: WORKSPACE_PATHS.feedback, name: 'workspace-feedback', component: { template: '<div />' } },
{ path: WORKSPACE_PATHS.updates, name: 'workspace-updates', component: { template: '<div />' } },
{ path: WORKSPACE_PATHS.shippingNoticeCustomers, name: 'workspace-shipping-customers', component: { template: '<div />' } },
@@ -33,7 +33,7 @@ const primaryLinkItems = [
{ path: WORKSPACE_PATHS.profile, labelKey: 'workspace.nav.profile', icon: User, match: ['workspace-profile'] },
{ path: WORKSPACE_PATHS.applications, labelKey: 'workspace.nav.applications', icon: LayoutGrid, match: ['workspace-applications'] },
{ path: WORKSPACE_PATHS.scheduleRuns, labelKey: 'workspace.nav.scheduleRuns', icon: Clock, match: ['workspace-schedule-runs'] },
{ path: WORKSPACE_PATHS.receiptReports, labelKey: 'workspace.nav.receiptReports', icon: FileDown, match: ['workspace-receipt-reports'] },
{ path: WORKSPACE_PATHS.inboundReports, labelKey: 'workspace.nav.inboundReports', icon: FileDown, match: ['workspace-inbound-reports'] },
] as const;
const secondaryLinkItems = [
@@ -21,7 +21,7 @@ const ROUTE_NAME_TO_SIDEBAR: Record<string, WorkspaceSidebarItem> = {
'workspace-knowledge-base': 'knowledge_base',
'workspace-knowledge-base-group': 'knowledge_base',
'workspace-schedule-runs': 'schedule_runs',
'workspace-receipt-reports': 'receipt_reports',
'workspace-inbound-reports': 'receipt_reports',
'workspace-shipping-customers': 'shipping_notice',
'workspace-shipping-tasks': 'shipping_notice',
'workspace-shipping-my-tasks': 'shipping_notice',
@@ -11,7 +11,7 @@ export const WORKSPACE_PATHS = {
updates: '/workspace/updates',
knowledgeBase: '/workspace/knowledge-base',
scheduleRuns: '/workspace/schedule-runs',
receiptReports: '/workspace/receipt-reports',
inboundReports: '/workspace/inbound-reports',
shippingNotice: '/workspace/shipping-notice/my-tasks',
shippingNoticeCustomers: '/workspace/shipping-notice/customers',
shippingNoticeTasks: '/workspace/shipping-notice/tasks',
@@ -35,7 +35,7 @@ export const LEGACY_VIEW_TO_PATH: Record<string, string> = {
updates: WORKSPACE_PATHS.updates,
knowledge_base: WORKSPACE_PATHS.knowledgeBase,
schedule_runs: WORKSPACE_PATHS.scheduleRuns,
receipt_reports: WORKSPACE_PATHS.receiptReports,
receipt_reports: WORKSPACE_PATHS.inboundReports,
shipping_notice: WORKSPACE_PATHS.shippingNotice,
accounting_voucher_check: WORKSPACE_PATHS.accountingVoucherCheck,
contract_payment: WORKSPACE_PATHS.contractPayment,
@@ -1,26 +1,26 @@
/**
* features/workspace/pages/ReceiptReportFilesPage.spec.ts
* features/workspace/pages/InboundReportFilesPage.spec.ts
* 用途:验证收料归档页的接收人与管理员补偿权限边界。
* 依赖:Vue Test Utils、Vue I18n、receipt-report.api、Workspace 上下文。
* 依赖:Vue Test Utils、Vue I18n、inbound-report.api、Workspace 上下文。
* 逻辑:普通接收人只能下载获授权文件;管理员才会查询失败单元并看到重发/重试操作。
*/
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it, vi } from 'vitest';
import ReceiptReportFilesPage from './ReceiptReportFilesPage.vue';
import InboundReportFilesPage from './InboundReportFilesPage.vue';
import { WORKSPACE_KEY } from '../composables/workspace.context';
const listWorkspaceReceiptReportFiles = vi.fn();
const listFailedReceiptRpaUnits = vi.fn();
const resendReceiptReportFile = vi.fn();
const listWorkspaceInboundReportFiles = vi.fn();
const listFailedInboundRpaUnits = vi.fn();
const resendInboundReportFile = vi.fn();
vi.mock('../api/receipt-report.api', () => ({
listWorkspaceReceiptReportFiles: (...args: unknown[]) => listWorkspaceReceiptReportFiles(...args),
listFailedReceiptRpaUnits: (...args: unknown[]) => listFailedReceiptRpaUnits(...args),
receiptReportDownloadUrl: (id: number) => `/download/${id}`,
resendReceiptReportFile: (...args: unknown[]) => resendReceiptReportFile(...args),
retryReceiptRpaUnit: vi.fn(),
vi.mock('../api/inbound-report.api', () => ({
listWorkspaceInboundReportFiles: (...args: unknown[]) => listWorkspaceInboundReportFiles(...args),
listFailedInboundRpaUnits: (...args: unknown[]) => listFailedInboundRpaUnits(...args),
inboundReportDownloadUrl: (id: number) => `/download/${id}`,
resendInboundReportFile: (...args: unknown[]) => resendInboundReportFile(...args),
retryInboundRpaUnit: vi.fn(),
}));
const i18n = createI18n({
@@ -29,7 +29,7 @@ const i18n = createI18n({
messages: {
en: {
workspace: {
receiptReports: {
inboundReports: {
title: 'Receipt Files', hint: 'hint', refresh: 'Refresh', loading: 'Loading', empty: 'Empty',
file: 'File', site: 'Site', warehouse: 'Warehouse', createdAt: 'Created', expiresAt: 'Expires',
action: 'Action', download: 'Download', resend: 'Resend to WeCom', failedUnits: 'Failed receipt units',
@@ -41,7 +41,7 @@ const i18n = createI18n({
});
function mountPage(role: string) {
return mount(ReceiptReportFilesPage, {
return mount(InboundReportFilesPage, {
global: {
plugins: [i18n],
provide: { [WORKSPACE_KEY as symbol]: { currentUser: { role } } },
@@ -49,12 +49,12 @@ function mountPage(role: string) {
});
}
describe('ReceiptReportFilesPage permissions', () => {
describe('InboundReportFilesPage permissions', () => {
it('does not expose administrator compensation actions to a recipient', async () => {
listWorkspaceReceiptReportFiles.mockResolvedValue({ items: [{
listWorkspaceInboundReportFiles.mockResolvedValue({ items: [{
id: 1, original_filename: 'receipt.xlsx', file_size: 12, sha256: 'a'.repeat(64),
}] });
listFailedReceiptRpaUnits.mockResolvedValue({ items: [{ id: 9, source_code: 'DBS-A', status: 'failed' }] });
listFailedInboundRpaUnits.mockResolvedValue({ items: [{ id: 9, source_code: 'DBS-A', status: 'failed' }] });
const wrapper = mountPage('user');
await flushPromises();
@@ -63,12 +63,12 @@ describe('ReceiptReportFilesPage permissions', () => {
expect(wrapper.text()).toContain('Download');
expect(wrapper.text()).not.toContain('Resend to WeCom');
expect(wrapper.text()).not.toContain('Failed receipt units');
expect(listFailedReceiptRpaUnits).not.toHaveBeenCalled();
expect(listFailedInboundRpaUnits).not.toHaveBeenCalled();
});
it('shows failed-unit compensation only to an administrator', async () => {
listWorkspaceReceiptReportFiles.mockResolvedValue({ items: [] });
listFailedReceiptRpaUnits.mockResolvedValue({ items: [{
listWorkspaceInboundReportFiles.mockResolvedValue({ items: [] });
listFailedInboundRpaUnits.mockResolvedValue({ items: [{
id: 9, source_code: 'DBS-A', warehouse_id: 'WH-01', status: 'failed', error_code: 'RPA.TIMEOUT',
}] });
@@ -79,15 +79,15 @@ describe('ReceiptReportFilesPage permissions', () => {
expect(wrapper.text()).toContain('Failed receipt units');
expect(wrapper.text()).toContain('DBS-A / WH-01');
expect(wrapper.text()).toContain('Retry with reason');
expect(listFailedReceiptRpaUnits).toHaveBeenCalledOnce();
expect(listFailedInboundRpaUnits).toHaveBeenCalledOnce();
});
it('uses the notification resend action without creating another export', async () => {
listWorkspaceReceiptReportFiles.mockResolvedValue({ items: [{
listWorkspaceInboundReportFiles.mockResolvedValue({ items: [{
id: 7, original_filename: 'receipt.xlsx', file_size: 12, sha256: 'b'.repeat(64),
}] });
listFailedReceiptRpaUnits.mockResolvedValue({ items: [] });
resendReceiptReportFile.mockResolvedValue({});
listFailedInboundRpaUnits.mockResolvedValue({ items: [] });
resendInboundReportFile.mockResolvedValue({});
const wrapper = mountPage('admin');
await flushPromises();
@@ -95,7 +95,7 @@ describe('ReceiptReportFilesPage permissions', () => {
await flushPromises();
// 重发只调用归档文件的通知接口,不存在浏览器侧重新导出入口。
expect(resendReceiptReportFile).toHaveBeenCalledWith(7);
expect(resendInboundReportFile).toHaveBeenCalledWith(7);
expect(wrapper.text()).not.toContain('Export');
});
});
@@ -1,22 +1,22 @@
<script setup lang="ts">
/**
* features/workspace/pages/ReceiptReportFilesPage.vue
* features/workspace/pages/InboundReportFilesPage.vue
* 用途:向排程收件人展示可下载的收料原样归档文件。
* 依赖:receipt-report.api、Vue I18n、Lucide。
* 依赖:inbound-report.api、Vue I18n、Lucide。
* 逻辑:文件列表始终由服务端按收件人授权裁剪;浏览器只请求受控下载地址。
*/
import { computed, inject, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Download, RefreshCw } from 'lucide-vue-next';
import {
listFailedReceiptRpaUnits, listWorkspaceReceiptReportFiles, receiptReportDownloadUrl,
resendReceiptReportFile, retryReceiptRpaUnit, type ReceiptReportFile, type ReceiptRpaUnit,
} from '../api/receipt-report.api';
listFailedInboundRpaUnits, listWorkspaceInboundReportFiles, inboundReportDownloadUrl,
resendInboundReportFile, retryInboundRpaUnit, type InboundReportFile, type InboundRpaUnit,
} from '../api/inbound-report.api';
import { WORKSPACE_KEY } from '../composables/workspace.context';
import { isPlatformAdminUser } from '@/shared/utils/auth';
const files = ref<ReceiptReportFile[]>([]);
const failedUnits = ref<ReceiptRpaUnit[]>([]);
const files = ref<InboundReportFile[]>([]);
const failedUnits = ref<InboundRpaUnit[]>([]);
const loading = ref(false);
const { t } = useI18n();
const ws = inject(WORKSPACE_KEY);
@@ -26,8 +26,8 @@ const isAdmin = computed(() => isPlatformAdminUser(ws?.currentUser));
async function loadFiles(): Promise<void> {
loading.value = true;
try {
files.value = (await listWorkspaceReceiptReportFiles()).items;
failedUnits.value = isAdmin.value ? (await listFailedReceiptRpaUnits()).items : [];
files.value = (await listWorkspaceInboundReportFiles()).items;
failedUnits.value = isAdmin.value ? (await listFailedInboundRpaUnits()).items : [];
} catch {
files.value = [];
} finally {
@@ -43,21 +43,21 @@ function formatDate(value?: string | null): string {
}
/** 统一从后端受控下载入口获取文件,下载时服务端会再次做权限审计。 */
function downloadFile(file: ReceiptReportFile): void {
window.location.assign(receiptReportDownloadUrl(file.id));
function downloadFile(file: InboundReportFile): void {
window.location.assign(inboundReportDownloadUrl(file.id));
}
/** 管理员重发已归档文件,不触发任何新的 RPA 导出。 */
async function resendFile(file: ReceiptReportFile): Promise<void> {
await resendReceiptReportFile(file.id);
async function resendFile(file: InboundReportFile): Promise<void> {
await resendInboundReportFile(file.id);
}
/** 管理员填写审计原因后才允许创建新的失败单元重试。 */
async function retryUnit(unit: ReceiptRpaUnit): Promise<void> {
async function retryUnit(unit: InboundRpaUnit): Promise<void> {
const target = `${unit.source_code}${unit.warehouse_id ? ` / ${unit.warehouse_id}` : ''}`;
const reason = window.prompt(t('workspace.receiptReports.retryReasonPrompt', { target }));
const reason = window.prompt(t('workspace.inboundReports.retryReasonPrompt', { target }));
if (!reason?.trim()) return;
await retryReceiptRpaUnit(unit.id, reason.trim());
await retryInboundRpaUnit(unit.id, reason.trim());
await loadFiles();
}
@@ -67,12 +67,12 @@ onMounted(() => { void loadFiles(); });
<template>
<section class="space-y-5 animate-fade-in-up">
<header class="flex items-center justify-between gap-3">
<div><h2 class="text-2xl font-bold text-primary">{{ $t('workspace.receiptReports.title') }}</h2><p class="mt-1 text-sm text-muted">{{ $t('workspace.receiptReports.hint') }}</p></div>
<button type="button" class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft" :disabled="loading" @click="loadFiles"><RefreshCw class="h-3.5 w-3.5" />{{ $t('workspace.receiptReports.refresh') }}</button>
<div><h2 class="text-2xl font-bold text-primary">{{ $t('workspace.inboundReports.title') }}</h2><p class="mt-1 text-sm text-muted">{{ $t('workspace.inboundReports.hint') }}</p></div>
<button type="button" class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft" :disabled="loading" @click="loadFiles"><RefreshCw class="h-3.5 w-3.5" />{{ $t('workspace.inboundReports.refresh') }}</button>
</header>
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">{{ $t('workspace.receiptReports.loading') }}</div>
<div v-else-if="!files.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">{{ $t('workspace.receiptReports.empty') }}</div>
<div v-else class="overflow-hidden rounded-2xl border border-default bg-surface"><div class="overflow-auto"><table class="w-full min-w-[860px] text-sm"><thead class="border-b border-subtle bg-surface-soft text-left text-secondary"><tr><th class="px-4 py-3">{{ $t('workspace.receiptReports.file') }}</th><th class="px-4 py-3">{{ $t('workspace.receiptReports.site') }}</th><th class="px-4 py-3">{{ $t('workspace.receiptReports.warehouse') }}</th><th class="px-4 py-3">{{ $t('workspace.receiptReports.createdAt') }}</th><th class="px-4 py-3">{{ $t('workspace.receiptReports.expiresAt') }}</th><th class="px-4 py-3">{{ $t('workspace.receiptReports.action') }}</th></tr></thead><tbody><tr v-for="file in files" :key="file.id" class="border-b border-subtle last:border-0"><td class="px-4 py-3 font-medium text-primary">{{ file.original_filename }}</td><td class="px-4 py-3 text-muted">{{ file.source_code || '-' }}</td><td class="px-4 py-3 text-muted">{{ file.warehouse_id || '-' }}</td><td class="px-4 py-3 text-muted">{{ formatDate(file.created_at) }}</td><td class="px-4 py-3 text-muted">{{ formatDate(file.archive_expires_at) }}</td><td class="px-4 py-3"><button type="button" class="inline-flex items-center gap-1 rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary hover:bg-surface-soft" @click="downloadFile(file)"><Download class="h-3 w-3" />{{ $t('workspace.receiptReports.download') }}</button><button v-if="isAdmin" type="button" class="ml-2 inline-flex rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary hover:bg-surface-soft" @click="resendFile(file)">{{ $t('workspace.receiptReports.resend') }}</button></td></tr></tbody></table></div></div>
<section v-if="isAdmin && failedUnits.length" class="overflow-hidden rounded-2xl border border-amber-200 bg-amber-50/40"><header class="border-b border-amber-200 px-4 py-3 text-sm font-semibold text-primary">{{ $t('workspace.receiptReports.failedUnits') }}</header><div class="overflow-auto"><table class="w-full min-w-[720px] text-sm"><tbody><tr v-for="unit in failedUnits" :key="unit.id" class="border-b border-amber-100 last:border-0"><td class="px-4 py-3 font-medium">{{ unit.source_code }}<span v-if="unit.warehouse_id"> / {{ unit.warehouse_id }}</span></td><td class="px-4 py-3 text-muted">{{ unit.error_code || unit.error_message || '-' }}</td><td class="px-4 py-3"><button type="button" class="rounded-lg border border-amber-300 px-2 py-1 text-xs font-medium text-amber-800 hover:bg-amber-100" @click="retryUnit(unit)">{{ $t('workspace.receiptReports.retry') }}</button></td></tr></tbody></table></div></section>
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">{{ $t('workspace.inboundReports.loading') }}</div>
<div v-else-if="!files.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">{{ $t('workspace.inboundReports.empty') }}</div>
<div v-else class="overflow-hidden rounded-2xl border border-default bg-surface"><div class="overflow-auto"><table class="w-full min-w-[860px] text-sm"><thead class="border-b border-subtle bg-surface-soft text-left text-secondary"><tr><th class="px-4 py-3">{{ $t('workspace.inboundReports.file') }}</th><th class="px-4 py-3">{{ $t('workspace.inboundReports.site') }}</th><th class="px-4 py-3">{{ $t('workspace.inboundReports.warehouse') }}</th><th class="px-4 py-3">{{ $t('workspace.inboundReports.createdAt') }}</th><th class="px-4 py-3">{{ $t('workspace.inboundReports.expiresAt') }}</th><th class="px-4 py-3">{{ $t('workspace.inboundReports.action') }}</th></tr></thead><tbody><tr v-for="file in files" :key="file.id" class="border-b border-subtle last:border-0"><td class="px-4 py-3 font-medium text-primary">{{ file.original_filename }}</td><td class="px-4 py-3 text-muted">{{ file.source_code || '-' }}</td><td class="px-4 py-3 text-muted">{{ file.warehouse_id || '-' }}</td><td class="px-4 py-3 text-muted">{{ formatDate(file.created_at) }}</td><td class="px-4 py-3 text-muted">{{ formatDate(file.archive_expires_at) }}</td><td class="px-4 py-3"><button type="button" class="inline-flex items-center gap-1 rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary hover:bg-surface-soft" @click="downloadFile(file)"><Download class="h-3 w-3" />{{ $t('workspace.inboundReports.download') }}</button><button v-if="isAdmin" type="button" class="ml-2 inline-flex rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary hover:bg-surface-soft" @click="resendFile(file)">{{ $t('workspace.inboundReports.resend') }}</button></td></tr></tbody></table></div></div>
<section v-if="isAdmin && failedUnits.length" class="overflow-hidden rounded-2xl border border-amber-200 bg-amber-50/40"><header class="border-b border-amber-200 px-4 py-3 text-sm font-semibold text-primary">{{ $t('workspace.inboundReports.failedUnits') }}</header><div class="overflow-auto"><table class="w-full min-w-[720px] text-sm"><tbody><tr v-for="unit in failedUnits" :key="unit.id" class="border-b border-amber-100 last:border-0"><td class="px-4 py-3 font-medium">{{ unit.source_code }}<span v-if="unit.warehouse_id"> / {{ unit.warehouse_id }}</span></td><td class="px-4 py-3 text-muted">{{ unit.error_code || unit.error_message || '-' }}</td><td class="px-4 py-3"><button type="button" class="rounded-lg border border-amber-300 px-2 py-1 text-xs font-medium text-amber-800 hover:bg-amber-100" @click="retryUnit(unit)">{{ $t('workspace.inboundReports.retry') }}</button></td></tr></tbody></table></div></section>
</section>
</template>
@@ -77,7 +77,7 @@ function detail(): ShippingTaskDetail {
summary: { title: 't', message: 'm' },
actions: {
primary: {
code: 'retry_inventory_matching', kind: 'recovery', enabled: true,
code: 'retry_onhand_matching', kind: 'recovery', enabled: true,
label: '重新匹配', dispatch: 'mutation',
requires_confirmation: false,
},
@@ -87,7 +87,7 @@ function detail(): ShippingTaskDetail {
process_gate: {
execution_no: 'SPE-1',
current_blocking_gate: {
gate_code: 'inventory_matching',
gate_code: 'onhand_matching',
evaluation_version: 3,
},
},
@@ -137,9 +137,9 @@ describe('TaskTodoPanel actionsExecutable', () => {
execution_no: 'SPE-1',
technical_auto_only: true,
current_blocking_gate: {
gate_code: 'inventory_preparation',
gate_code: 'onhand_preparation',
evaluation_version: 3,
next_action_code: 'poll_inventory_preparation',
next_action_code: 'poll_onhand_preparation',
},
},
} as ShippingTaskDetail['ui_state'];