feat(shipping-notice): 收敛复核状态隔离、STP 重试幂等与 XFA 合成预览标注

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-07 02:58:28 +08:00
1 parent 84a881b554
commit 74270adc22
149 files changed
+20111 -3871

No files matched your search

@@ -75,12 +75,13 @@ describe('resolveProcessingActionPresentation', () => {
expect(result.primary?.actionCode).toBe('retry_parse');
});
it('filters open_order_review on review surface', () => {
it('filters open_order_review and refresh on review surface', () => {
const result = resolveProcessingActionPresentation(projection({
availableActions: ['open_order_review', 'refresh'],
}), { surface: 'review' });
expect(result.primary?.intent).toBe('refresh');
availableActions: ['open_order_review', 'refresh', 'view_result'],
}), { surface: 'review', actionsExecutable: true });
expect(result.primary?.intent).toBe('view_result');
expect(result.overflow.some((i) => i.intent === 'open_order_review')).toBe(false);
expect([result.primary, result.secondary, ...result.overflow].some((i) => i?.intent === 'refresh')).toBe(false);
});
it('maps open_order_review label to processing entry on chat surface', () => {
@@ -1,23 +1,37 @@
/**
* features/shipping-progress/actionPresentation.ts
* 用途:从统一投影解析四页面共用的 ActionPresentation(主/次/溢出)。
* 依赖:ShippingProcessingProjection、SHIPPING_PROCESSING_ACTION_INTENTS、types。
* 用途:从统一投影 / 会话 OT 任务解析四页面共用的 ActionPresentation(主/次/溢出)。
* 依赖:ShippingProcessingProjection、ConversationProcessingUserTask、workbenchActionRegistry、types。
* 逻辑:优先级 Gate.nextActionCode → availableActions → 终态查看 → none;
* 自动处理中(processing/automating)主按钮为空;review 面隐藏 open_order_review。
* cancel_* 与 view_details 永不作主 CTA;无业务入口时 focus_task 兜底并映射「查看进度」;
* 自动处理中(processing/automating)主按钮为空;review 面经注册表 fail-closed 过滤。
*/
import type {
ConversationProcessingUserTask,
ShippingProcessingActionIntent,
ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import type { ActionPresentation, ActionPresentationItem, ActionPresentationSurface } from './types';
import type { WorkbenchPanelAvailability } from './workbenchActionRegistry';
import {
lookupWorkbenchAction,
shouldRenderWorkbenchAction,
warnUnregisteredWorkbenchAction,
} from './workbenchActionRegistry';
/** 可映射为统一意图的原始动作码(gate / available_actions)。 */
const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
open_order_review: 'open_order_review',
open_review: 'open_order_review',
open_order_processing: 'open_order_review',
enter_manual_review: 'open_order_review',
edit_formal_task: 'edit_formal_task',
freeze_order: 'edit_formal_task',
open_profile_review: 'open_profile_review',
confirm_customer: 'confirm_customer',
resolve_field_conflicts: 'resolve_field_conflicts',
adjudicate_duplicate: 'adjudicate_duplicate',
open_inventory_source_review: 'open_inventory_source_review',
confirm_inventory_source: 'open_inventory_source_review',
retry_resolve_inventory_source: 'open_inventory_source_review',
@@ -29,6 +43,9 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
retry: 'retry',
retry_parse: 'retry',
retry_failed_documents: 'retry',
retry_failed_attachments: 'retry',
retry_upload: 'retry',
retry_freight_upload_rpa: 'retry',
refresh: 'refresh',
regenerate_excel: 'regenerate_excel',
generate_excel: 'regenerate_excel',
@@ -40,13 +57,21 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
open_fulfillment: 'view_result',
view_result: 'view_result',
view_details: 'view_result',
focus_task: 'view_result',
view_record: 'view_record',
/** 取消类动作映射为 view_record,以便进入 presentation(再由 NEVER_PRIMARY 降为次要)。 */
cancel_task: 'view_record',
cancel_run: 'view_record',
};
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
/** 永不升为主 CTA 的动作码(仍可作次要/溢出)。 */
const NEVER_PRIMARY_CODES = new Set(['cancel_task', 'cancel_run', 'view_details']);
/**
* 将原始动作码映射为统一意图;未知码返回 null。
*
* @param code - Gate / available_actions 原始码
*/
export function mapActionCodeToIntent(code: string | null | undefined): ShippingProcessingActionIntent | null {
const normalized = String(code || '').trim().toLowerCase();
@@ -56,6 +81,7 @@ export function mapActionCodeToIntent(code: string | null | undefined): Shipping
/**
* 构建单个动作项。
* 核心逻辑:默认 labelKey=action.{intent};chat/right 面改写订单处理 / 重试解析 / 查看进度。
*/
function toItem(
code: string,
@@ -63,11 +89,18 @@ function toItem(
surface?: ActionPresentationSurface,
): ActionPresentationItem {
let labelKey = `chat.shippingProcessing.action.${intent}`;
if (
intent === 'open_order_review'
&& (surface === 'chat' || surface === 'right')
) {
const normalized = String(code || '').trim().toLowerCase();
const chatOrRight = surface === 'chat' || surface === 'right';
if (intent === 'open_order_review' && chatOrRight) {
labelKey = 'chat.shippingProcessing.action.open_order_processing';
} else if (intent === 'retry' && chatOrRight) {
labelKey = 'chat.shippingProcessing.action.retry_parse';
} else if (normalized === 'focus_task' && chatOrRight) {
labelKey = 'chat.shippingProcessing.action.view_progress';
} else if (normalized === 'cancel_task' || normalized === 'cancel_run') {
labelKey = 'chat.shippingProcessing.cancelEntireTaskSingle';
} else if (normalized === 'view_details') {
labelKey = 'chat.shippingProcessing.viewTaskDetails';
}
return {
intent,
@@ -76,6 +109,39 @@ function toItem(
};
}
/**
* 将动作列表拆成主/次/溢出;cancel 与 view_details 永不作 primary。
*/
function partitionActionItems(items: ActionPresentationItem[]): ActionPresentation {
if (!items.length) {
return { primary: null, secondary: null, overflow: [] };
}
const primaryPool = items.filter(
(item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()),
);
const demoted = items.filter(
(item) => NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()),
);
const primary = primaryPool[0] || null;
const rest = [
...primaryPool.slice(1),
...demoted,
];
return {
primary,
secondary: rest[0] || null,
overflow: rest.slice(1),
};
}
export interface ResolveProcessingActionPresentationOptions {
surface?: ActionPresentationSurface;
/** 订单处理工作台写权限;仅 surface=review 时生效。 */
actionsExecutable?: boolean;
/** 面板可用性(review 面 requiresPanel 守卫)。 */
panels?: WorkbenchPanelAvailability | null;
}
/**
* 解析统一动作投影。
*
@@ -84,16 +150,22 @@ function toItem(
* 2. currentGate.nextActionCode 优先;
* 3. availableActions 依次填主/次/溢出;
* 4. completed/failed/cancelled → view_result / view_record 兜底;
* 5. surface=review 时过滤 open_order_review(已在复核页)。
* 5. surface=review 时经注册表 fail-closed(未知隐藏 + 告警;隐藏 refresh/自跳转);
* 6. cancel / view_details 强制降为次要或溢出。
*
* @param projection - 统一处理投影
* @param options - surface / actionsExecutable / panels
*/
export function resolveProcessingActionPresentation(
projection: ShippingProcessingProjection | null | undefined,
options?: { surface?: ActionPresentationSurface },
options?: ResolveProcessingActionPresentationOptions,
): ActionPresentation {
const empty: ActionPresentation = { primary: null, secondary: null, overflow: [] };
if (!projection) return empty;
const surface = options?.surface;
const actionsExecutable = options?.actionsExecutable !== false;
const panels = options?.panels ?? null;
const status = String(projection.status || '').trim().toLowerCase();
if (AUTOMATING_STATUSES.has(status) && !projection.currentGate?.nextActionCode) {
return empty;
@@ -107,10 +179,36 @@ export function resolveProcessingActionPresentation(
if (!code) return;
const key = code.toLowerCase();
if (seen.has(key)) return;
const intent = mapActionCodeToIntent(code);
if (!intent || intent === 'none') return;
if (surface === 'review' && intent === 'open_order_review') return;
seen.add(key);
const intent = mapActionCodeToIntent(code);
if (!intent || intent === 'none') {
// [fail-closed] 未知动作不渲染原始码,仅告警。
warnUnregisteredWorkbenchAction({
actionCode: code,
surface: surface || 'workbench',
workItemType: projection.workItemType,
});
return;
}
if (surface === 'review') {
const entry = lookupWorkbenchAction(code) || lookupWorkbenchAction(intent);
if (!entry) {
warnUnregisteredWorkbenchAction({
actionCode: code,
surface: 'review',
workItemType: projection.workItemType,
});
return;
}
if (!shouldRenderWorkbenchAction(entry, {
actionsExecutable,
surface: 'review',
panels,
actionCode: code,
})) {
return;
}
}
items.push(toItem(code, intent, surface));
};
@@ -127,9 +225,50 @@ export function resolveProcessingActionPresentation(
return empty;
}
return {
primary: items[0] || null,
secondary: items[1] || null,
overflow: items.slice(2),
return partitionActionItems(items);
}
/**
* 从会话 OT 任务投影解析 ActionPresentation(无 workItem 时的统一适配器)。
* 核心逻辑:primary_action 优先;available_actions 补充;无正式入口时 focus_task→查看进度;
* cancel/view_details 永不作主 CTA。
* @param task - 会话用户可见任务
* @param options.surface - 展示面(默认 right)
*/
export function resolveConversationTaskActionPresentation(
task: ConversationProcessingUserTask | null | undefined,
options?: { surface?: ActionPresentationSurface },
): ActionPresentation {
const empty: ActionPresentation = { primary: null, secondary: null, overflow: [] };
if (!task) return empty;
const surface = options?.surface || 'right';
const items: ActionPresentationItem[] = [];
const seen = new Set<string>();
const pushCode = (raw: string | null | undefined) => {
const code = String(raw || '').trim();
if (!code) return;
const key = code.toLowerCase();
if (seen.has(key)) return;
const intent = mapActionCodeToIntent(code);
if (!intent || intent === 'none') return;
seen.add(key);
items.push(toItem(code, intent, surface));
};
pushCode(task.primary_action);
for (const action of task.available_actions || []) {
pushCode(action);
}
// 无正式业务入口时,默认提供查看进度(focus_task)。
const hasPrimaryCandidate = items.some(
(item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()),
);
if (!hasPrimaryCandidate) {
pushCode('focus_task');
}
return partitionActionItems(items);
}
@@ -0,0 +1,156 @@
/**
* features/shipping-progress/components/ReviewProgressStrip.spec.ts
* 用途:验收压缩进度条——宽屏 15 阶、无五域、阻断需时显示「当前需要」、自动推进刷新。
* 依赖:Vitest、@vue/test-utils、vue-i18n、ReviewProgressStrip。
* 逻辑:合法 stageNodes → 15 节点;非法 → 不可用提示;automating → 标题换文案且无当前需要。
*/
import { mount } from '@vue/test-utils';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createI18n } from 'vue-i18n';
import {
SHIPPING_PROCESSING_STAGES,
type ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import ReviewProgressStrip from './ReviewProgressStrip.vue';
function buildProjection(
overrides: Partial<ShippingProcessingProjection> = {},
): ShippingProcessingProjection {
const stageNodes = SHIPPING_PROCESSING_STAGES.map((stage, absoluteIndex) => ({
stage,
absoluteIndex,
status: (absoluteIndex < 8 ? 'passed' : absoluteIndex === 8 ? 'blocked' : 'pending') as const,
}));
return {
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: null,
conversationId: 'c1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 2,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: {
gateCode: 'order_review',
status: 'blocked',
nextActionCode: 'confirm_customer',
blockingReasonCode: 'customer_unresolved',
attemptNo: 1,
},
availableActions: ['confirm_customer'],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
stageNodes,
...overrides,
};
}
function mountStrip(projection: ShippingProcessingProjection, polling = false) {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
workflowProgress: { polling: '正在刷新进度…' },
},
shippingProcessing: {
progress: {
completedOfTotal: '已完成 {done} / {total}',
currentNeedLabel: '当前需要:',
progressTitleWithStage: '订单处理进度 · {stage}',
systemProcessingWithStage: '系统处理中 · {stage}',
viewProcessDetails: '查看流程详情',
viewFullProcess: '查看完整流程',
stageNodesUnavailable: '进度详情暂不可用',
},
stage: Object.fromEntries(SHIPPING_PROCESSING_STAGES.map((s) => [s, s])),
action: { refresh: '刷新', confirm_customer: '确认客户' },
gateReasons: { customer_unresolved: '确认客户', generic: '需要处理' },
},
},
workspace: {
shippingNotice: {
processGate: {
actions: { confirm_customer: '确认客户', retry_freight_upload_rpa: '重试货代上传' },
},
},
},
},
},
});
return mount(ReviewProgressStrip, {
props: { projection, polling },
global: { plugins: [i18n] },
});
}
describe('ReviewProgressStrip', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('renders title + 15 stage nodes without domain chips', () => {
const wrapper = mountStrip(buildProjection());
expect(wrapper.get('[data-testid="review-progress-title"]').text()).toContain('订单处理进度');
expect(wrapper.find('[data-testid="review-progress-stage-nodes"]').exists()).toBe(true);
expect(wrapper.findAll('[data-testid="review-progress-stage-nodes"] [data-stage]')).toHaveLength(15);
expect(wrapper.find('[data-testid="review-progress-domains"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-progress-current-need"]').text()).toContain('确认客户');
expect(wrapper.find('[data-testid="review-progress-completed-summary"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-progress-open-details"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-progress-refresh"]').exists()).toBe(false);
});
it('shows system-processing title and refresh while automating without current need', () => {
const wrapper = mountStrip(buildProjection({
status: 'automating',
stage: 'freight_uploading',
currentGate: null,
availableActions: [],
}));
expect(wrapper.get('[data-testid="review-progress-title"]').text()).toContain('系统处理中');
expect(wrapper.find('[data-testid="review-progress-current-need"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-progress-refresh"]').exists()).toBe(true);
});
it('hides stage nodes and warns when stageNodes invalid', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
const wrapper = mountStrip(buildProjection({ stageNodes: [] }));
expect(wrapper.find('[data-testid="review-progress-stage-nodes"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-progress-stage-nodes-unavailable"]').exists()).toBe(true);
expect(warn).toHaveBeenCalled();
});
it('falls back to nextActionCode label when blockingReasonCode missing', () => {
const wrapper = mountStrip(buildProjection({
currentGate: {
gateCode: 'freight_upload',
status: 'blocked',
nextActionCode: 'retry_freight_upload_rpa',
blockingReasonCode: null,
attemptNo: 1,
},
}));
expect(wrapper.find('[data-testid="review-progress-current-need"]').text()).toContain('重试货代上传');
});
it('emits open-process-details from details CTA', async () => {
const wrapper = mountStrip(buildProjection());
await wrapper.get('[data-testid="review-progress-open-details"]').trigger('click');
expect(wrapper.emitted('open-process-details')).toHaveLength(1);
});
});
@@ -1,24 +1,30 @@
<!--
features/shipping-progress/components/ReviewProgressStrip.vue
用途:订单处理工作台只读紧凑进度——五域摘要 + 当前节点 n/15 + 当前需要 + 打开流程详情。
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、gateReasonLabel。
逻辑:由 ReviewWorkflowProgressPanel 挂载;正文不展开 15 阶、不挂 ActionBar;写操作只在底部 Footer。
用途:订单处理工作台只读进度——宽屏仅 15 阶主进度;窄屏摘要版。
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、stageNodesAuthority、gateReasonLabel.resolveCurrentNeedLabel。
逻辑:由 ReviewWorkflowProgressPanel 挂载;禁止点击节点;宽屏隐藏五域与 n/15 文案;
窄屏不展示 15 阶横条;有阻断 Gate 且非自动推进时显示「当前需要」(优先级 C);
「查看流程详情/完整流程」同一 emit;写操作只在 Footer。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
import type {
ShippingProcessingProjection,
ShippingProcessingStageNodeStatus,
} from '@/features/chat/types/shipping.api.types';
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
import { buildProgressRangeHint } from '../progressWindow';
import {
buildProgressRangeHint,
buildReviewProgressDomainSummary,
stageAbsoluteIndex,
} from '../progressWindow';
import { resolveGateReasonLabel } from '../gateReasonLabel';
import type { ProgressDomainState } from '../types';
readAuthoritativeStageNodes,
warnStageNodesUnavailable,
} from '../stageNodesAuthority';
import { resolveCurrentNeedLabel } from '../gateReasonLabel';
const props = defineProps<{
projection: ShippingProcessingProjection;
/** 宿主轮询中提示(显示在标题行)。 */
polling?: boolean;
}>();
const emit = defineEmits<{
@@ -30,7 +36,9 @@ const { t, te } = useI18n();
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
const domains = computed(() => buildReviewProgressDomainSummary(props.projection));
/** 权威 15 阶;非法时 null(fail-closed)。 */
const stageNodes = computed(() => readAuthoritativeStageNodes(props.projection));
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
const isAutomating = computed(() => (
@@ -38,38 +46,76 @@ const isAutomating = computed(() => (
&& !props.projection.currentGate?.nextActionCode
));
/**
* ● 当前阶段 · 第 n/15。
*/
const currentLine = computed(() => {
const stageKey = rangeHint.value?.currentLabelKey || shippingProcessingStageKey(props.projection.stage);
const stageLabel = te(stageKey) ? t(stageKey) : props.projection.stage;
const index = stageAbsoluteIndex(props.projection.stage) + 1;
return `● ${stageLabel} · ${t('chat.shippingProcessing.progress.positionOfTotal', { current: index, total: 15 })}`;
const stageLabel = computed(() => {
const stage = props.projection.stage;
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : String(stage || '');
});
/**
* 当前需要:Gate 原因;自动推进中用系统文案。
* 单行标题:自动推进用「系统处理中 · 阶段」;否则「订单处理进度 · 阶段」。
*/
const currentNeed = computed(() => {
const titleLine = computed(() => {
const stage = stageLabel.value || '—';
if (isAutomating.value) {
return t('chat.shippingProcessing.progress.systemProcessingNeed');
return t('chat.shippingProcessing.progress.systemProcessingWithStage', { stage });
}
return resolveGateReasonLabel(
props.projection.currentGate?.blockingReasonCode,
{ t, te },
return t('chat.shippingProcessing.progress.progressTitleWithStage', { stage });
});
/**
* 有阻断 Gate 且非自动推进时展示「当前需要」。
*/
const showCurrentNeed = computed(() => {
if (isAutomating.value) return false;
const gate = props.projection.currentGate;
if (!gate) return false;
return Boolean(
String(gate.blockingReasonCode || '').trim()
|| String(gate.nextActionCode || '').trim(),
);
});
/**
* 五域圆点样式。
* 「当前需要」:blockingReasonCode 优先,缺失时回退 nextActionCode(与 Footer 语义对齐)。
*/
function domainDotClass(state: ProgressDomainState): string {
if (state === 'passed') return 'bg-emerald-500';
if (state === 'current') return 'bg-brand-500';
if (state === 'blocked') return 'bg-amber-500';
if (state === 'failed') return 'bg-rose-500';
return 'bg-slate-300';
const currentNeed = computed(() => {
if (!showCurrentNeed.value) return '';
return resolveCurrentNeedLabel(props.projection.currentGate, { t, te });
});
watch(
stageNodes,
(nodes) => {
if (!nodes) {
warnStageNodesUnavailable({
workItemNo: props.projection.workItemNo,
reason: 'missing_or_invalid_stage_nodes',
});
}
},
{ immediate: true },
);
/**
* 15 阶节点色块(只读高亮,禁止交互)。
*/
function nodeToneClass(status: ShippingProcessingStageNodeStatus, isCurrent: boolean): string {
if (status === 'passed') return 'bg-emerald-500/90 text-white';
if (status === 'blocked') return 'bg-amber-500 text-white';
if (status === 'failed') return 'bg-rose-500 text-white';
if (status === 'running' || isCurrent) return 'bg-brand-500 text-white ring-2 ring-brand-300';
if (status === 'skipped') return 'bg-slate-200 text-slate-400 line-through dark:bg-slate-700';
return 'bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-300';
}
/**
* 节点展示短标签。
*/
function nodeShortLabel(stage: string): string {
const key = shippingProcessingStageKey(stage);
const label = te(key) ? t(key) : stage;
return String(label).slice(0, 4);
}
</script>
@@ -78,43 +124,80 @@ function domainDotClass(state: ProgressDomainState): string {
class="space-y-2"
data-testid="review-progress-strip"
>
<div
v-if="domains.length"
class="flex flex-wrap items-center gap-1.5"
data-testid="review-progress-domains"
>
<div class="flex items-start justify-between gap-2">
<div
v-for="domain in domains"
:key="domain.key"
class="inline-flex items-center gap-1 rounded-md border border-default bg-surface px-2 py-0.5 text-[11px]"
:data-domain="domain.key"
:data-state="domain.state"
class="min-w-0 text-sm font-semibold text-primary"
data-testid="review-progress-title"
>
{{ titleLine }}
<span
class="inline-block h-1.5 w-1.5 rounded-full"
:class="domainDotClass(domain.state)"
/>
<span :class="domain.state === 'current' || domain.state === 'blocked' ? 'font-semibold text-primary' : 'text-secondary'">
{{ t(domain.labelKey) }}
v-if="polling"
class="ml-2 text-[11px] font-normal text-muted"
data-testid="review-workflow-progress-polling"
>
{{ t('chat.shippingOrderReview.workflowProgress.polling') }}
</span>
</div>
<button
v-if="isAutomating"
type="button"
class="shrink-0 rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-secondary hover:bg-surface-muted"
data-testid="review-progress-refresh"
@click="emit('refresh')"
>
{{ t('chat.shippingProcessing.action.refresh') }}
</button>
</div>
<!-- 宽屏:唯一主进度 = 15 阶只读条。 -->
<div
class="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-secondary"
data-testid="review-progress-range"
v-if="stageNodes"
class="hidden lg:block"
data-testid="review-progress-stage-nodes"
>
<span data-testid="review-progress-current-line">{{ currentLine }}</span>
<span v-if="rangeHint">
{{ t('chat.shippingProcessing.progress.completedOfTotal', {
done: rangeHint.done,
total: rangeHint.total,
}) }}
</span>
<div
class="flex gap-1 overflow-x-auto pb-1"
role="list"
aria-label="shipping-processing-stages"
>
<div
v-for="node in stageNodes"
:key="node.stage"
role="listitem"
class="min-w-[3.25rem] shrink-0 select-none rounded-md px-1.5 py-1 text-center text-[10px] leading-tight pointer-events-none"
:class="nodeToneClass(node.status, node.stage === projection.stage)"
:data-stage="node.stage"
:data-status="node.status"
:data-current="node.stage === projection.stage ? '1' : '0'"
:title="te(shippingProcessingStageKey(node.stage)) ? t(shippingProcessingStageKey(node.stage)) : node.stage"
>
<div class="font-semibold">{{ node.absoluteIndex + 1 }}</div>
<div class="truncate">{{ nodeShortLabel(node.stage) }}</div>
</div>
</div>
</div>
<p
v-else
class="hidden text-[11px] text-amber-800 lg:block dark:text-amber-200"
data-testid="review-progress-stage-nodes-unavailable"
>
{{ t('chat.shippingProcessing.progress.stageNodesUnavailable') }}
</p>
<!-- 窄屏摘要:仅已完成 n/15(宽屏由节点色表达,不重复文案)。 -->
<p
v-if="rangeHint"
class="text-[11px] text-secondary lg:hidden"
data-testid="review-progress-completed-summary"
>
{{ t('chat.shippingProcessing.progress.completedOfTotal', {
done: rangeHint.done,
total: rangeHint.total,
}) }}
</p>
<p
v-if="currentNeed"
v-if="showCurrentNeed && currentNeed"
class="text-[11px] text-amber-800 dark:text-amber-200"
data-testid="review-progress-current-need"
>
@@ -129,16 +212,8 @@ function domainDotClass(state: ProgressDomainState): string {
data-testid="review-progress-open-details"
@click="emit('open-process-details')"
>
{{ t('chat.shippingProcessing.progress.viewProcessDetails') }}
</button>
<button
v-if="isAutomating"
type="button"
class="rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-secondary hover:bg-surface-muted"
data-testid="review-progress-refresh"
@click="emit('refresh')"
>
{{ t('chat.shippingProcessing.action.refresh') }}
<span class="hidden lg:inline">{{ t('chat.shippingProcessing.progress.viewProcessDetails') }}</span>
<span class="lg:hidden">{{ t('chat.shippingProcessing.progress.viewFullProcess') }}</span>
</button>
</div>
</div>
@@ -6,7 +6,10 @@
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
import {
SHIPPING_PROCESSING_STAGES,
type ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import ChatProgressSummary from './ChatProgressSummary.vue';
import SidebarProgressInline from './SidebarProgressInline.vue';
import ReviewProgressStrip from './ReviewProgressStrip.vue';
@@ -45,6 +48,11 @@ function sampleProjection(): ShippingProcessingProjection {
poNumber: null,
},
childOrderTasks: [],
stageNodes: SHIPPING_PROCESSING_STAGES.map((stage, absoluteIndex) => ({
stage,
absoluteIndex,
status: (absoluteIndex < 8 ? 'passed' : absoluteIndex === 8 ? 'blocked' : 'pending') as const,
})),
};
}
@@ -72,7 +80,11 @@ const i18n = createI18n({
domainFulfillmentShip: '发货履约',
currentNeedLabel: '当前需要:',
systemProcessingNeed: '系统处理中',
progressTitleWithStage: '订单处理进度 · {stage}',
systemProcessingWithStage: '系统处理中 · {stage}',
viewProcessDetails: '查看流程详情',
viewFullProcess: '查看完整流程',
stageNodesUnavailable: '进度详情暂不可用',
closeProcessDetails: '关闭',
processDetailsTitle: '流程详情',
nodeTime: '时间',
@@ -131,20 +143,19 @@ describe('shipping progress presenters', () => {
expect(wrapper.find('[data-testid="sidebar-progress-inline"]').exists()).toBe(true);
});
it('mounts ReviewProgressStrip as compact five-domain readonly strip', () => {
it('mounts ReviewProgressStrip as compressed 15-stage readonly strip', () => {
const wrapper = mount(ReviewProgressStrip, {
props: { projection },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-progress-strip"]').exists()).toBe(true);
expect(wrapper.findAll('[data-testid="review-progress-domains"] [data-domain]').length).toBe(5);
expect(wrapper.find('[data-testid="review-progress-domains"]').exists()).toBe(false);
expect(wrapper.findAll('[data-testid="review-progress-stage-nodes"] [data-stage]').length).toBe(15);
// 正文不得再挂 ActionBar / 页内完整 15 阶展开
expect(wrapper.find('[data-testid="unified-action-bar"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-progress-expand-full"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-progress-nodes-strip"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-progress-open-details"]').exists()).toBe(true);
});
it('mounts ReviewProcessDetailDrawer with readonly 15 nodes', () => {
const wrapper = mount(ReviewProcessDetailDrawer, {
props: {
@@ -7,18 +7,19 @@
import { computed, unref, type ComputedRef, type MaybeRef, type Ref } from 'vue';
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
import { resolveProcessingActionPresentation } from '../actionPresentation';
import type { ActionPresentation, ActionPresentationSurface } from '../types';
import {
resolveProcessingActionPresentation,
type ResolveProcessingActionPresentationOptions,
} from '../actionPresentation';
import type { ActionPresentation } from '../types';
export interface UseProcessingActionPresentationOptions {
surface?: ActionPresentationSurface;
}
export type UseProcessingActionPresentationOptions = ResolveProcessingActionPresentationOptions;
/**
* 从投影 ref 得到响应式 ActionPresentation。
*
* @param projection - 统一投影 ref
* @param options - 可选 surface(chat/right/review/workbench)
* @param options - surface / actionsExecutable / panels(MaybeRef 以响应式重算)
*/
export function useProcessingActionPresentation(
projection: Ref<ShippingProcessingProjection | null | undefined>
@@ -0,0 +1,56 @@
/**
* features/shipping-progress/gateReasonLabel.spec.ts
* 用途:验收「当前需要」文案优先级 C(blockingReason → nextAction)。
* 依赖:Vitest、gateReasonLabel。
* 逻辑:有 reason 用 gateReasons;仅有 action 用 processGate.actions;均无则空串。
*/
import { describe, expect, it } from 'vitest';
import { resolveCurrentNeedLabel, resolveGateReasonLabel } from './gateReasonLabel';
function makeI18n(messages: Record<string, string>) {
return {
te: (key: string) => Object.prototype.hasOwnProperty.call(messages, key),
t: (key: string) => messages[key] || key,
};
}
describe('gateReasonLabel', () => {
it('resolveGateReasonLabel prefers shippingProcessing.gateReasons', () => {
const i18n = makeI18n({
'chat.shippingProcessing.gateReasons.customer_unresolved': '确认客户',
'chat.shippingProcessing.gateReasons.generic': '需要处理',
});
expect(resolveGateReasonLabel('customer_unresolved', i18n)).toBe('确认客户');
});
it('resolveCurrentNeedLabel uses blockingReasonCode first', () => {
const i18n = makeI18n({
'chat.shippingProcessing.gateReasons.customer_unresolved': '确认客户',
'workspace.shippingNotice.processGate.actions.confirm_customer': '确认客户(动作)',
'chat.shippingProcessing.gateReasons.generic': '需要处理',
});
expect(resolveCurrentNeedLabel({
blockingReasonCode: 'customer_unresolved',
nextActionCode: 'confirm_customer',
}, i18n)).toBe('确认客户');
});
it('resolveCurrentNeedLabel falls back to nextActionCode when reason missing', () => {
const i18n = makeI18n({
'workspace.shippingNotice.processGate.actions.retry_freight_upload_rpa': '重试货代上传',
'chat.shippingProcessing.gateReasons.generic': '需要处理',
});
expect(resolveCurrentNeedLabel({
blockingReasonCode: null,
nextActionCode: 'retry_freight_upload_rpa',
}, i18n)).toBe('重试货代上传');
});
it('resolveCurrentNeedLabel returns empty when gate empty', () => {
const i18n = makeI18n({
'chat.shippingProcessing.gateReasons.generic': '需要处理',
});
expect(resolveCurrentNeedLabel(null, i18n)).toBe('');
expect(resolveCurrentNeedLabel({ blockingReasonCode: '', nextActionCode: '' }, i18n)).toBe('');
});
});
@@ -1,9 +1,9 @@
/**
* features/shipping-progress/gateReasonLabel.ts
* 用途:将 Gate blockingReasonCode 解析为用户可读文案,禁止界面直接暴露内部码。
* 依赖:vue-i18n TranslateResult 兼容的 t/te 函数。
* 逻辑:优先 chat.shippingProcessing.gateReasons.* → workspace.shippingNotice.workflowReasons.*
* → 通用兜底;永不回退为原始 code。
* 用途:将 Gate blockingReasonCode / nextActionCode 解析为用户可读「当前需要」文案。
* 依赖:vue-i18n 兼容的 t/te。
* 逻辑:优先 blockingReasonCode → gateReasons;缺失时 nextActionCode → processGate.actions;
* 永不直接暴露内部码;供 ReviewProgressStrip「当前需要」使用。
*/
export type GateReasonI18n = {
@@ -37,3 +37,40 @@ export function resolveGateReasonLabel(
? i18n.t('chat.shippingProcessing.gateReasons.generic')
: i18n.t('chat.shippingProcessing.status.blocked');
}
/**
* 解析订单处理工作台「当前需要」文案(与 Footer 语义对齐,禁止第二行重复「下一步」)。
*
* 核心逻辑(优先级 C):
* 1. 有 blockingReasonCode → gateReasons / workflowReasons;
* 2. 否则有 nextActionCode → processGate.actions / shippingProcessing.action;
* 3. 均无则空串(由调用方决定是否展示)。
*
* @param gate - 当前 Gate 摘要
* @param i18n - t / te
* @returns 用户可读文案
*/
export function resolveCurrentNeedLabel(
gate: {
blockingReasonCode?: string | null;
nextActionCode?: string | null;
} | null | undefined,
i18n: GateReasonI18n,
): string {
const reasonCode = String(gate?.blockingReasonCode || '').trim();
if (reasonCode) {
return resolveGateReasonLabel(reasonCode, i18n);
}
const actionCode = String(gate?.nextActionCode || '').trim();
if (!actionCode) return '';
const actionKeys = [
`workspace.shippingNotice.processGate.actions.${actionCode}`,
`chat.shippingProcessing.action.${actionCode}`,
];
for (const key of actionKeys) {
if (i18n.te(key)) return i18n.t(key);
}
return i18n.te('chat.shippingProcessing.gateReasons.generic')
? i18n.t('chat.shippingProcessing.gateReasons.generic')
: i18n.t('chat.shippingProcessing.status.blocked');
}
@@ -0,0 +1,76 @@
/**
* features/shipping-progress/mergeProcessingProjection.spec.ts
* 用途:验收工作台 progress_version 单调合并规则。
* 依赖:Vitest、mergeProcessingProjection。
* 逻辑:旧包丢弃、同版本合并、新包整包替换。
*/
import { describe, expect, it } from 'vitest';
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
import { mergeWorkbenchProcessingProjection } from './mergeProcessingProjection';
function base(overrides: Partial<ShippingProcessingProjection> = {}): ShippingProcessingProjection {
return {
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'eml',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: 'SN-1',
conversationId: 'c1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'blocked',
stage: 'inventory_matching',
progressVersion: 3,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: ['match_inventory'],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
...overrides,
};
}
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' });
expect(mergeWorkbenchProcessingProjection(local, incoming)).toBe(local);
});
it('replaces whole projection when incoming version is newer', () => {
const local = base({ progressVersion: 5, stage: 'inventory_matching' });
const incoming = base({ progressVersion: 6, stage: 'excel_generating', availableActions: ['download_excel'] });
expect(mergeWorkbenchProcessingProjection(local, incoming)).toEqual(incoming);
});
it('merges fields when versions are equal', () => {
const local = base({
progressVersion: 5,
availableActions: ['match_inventory'],
currentGate: {
gateCode: 'old',
status: 'blocked',
nextActionCode: 'match_inventory',
blockingReasonCode: 'x',
attemptNo: 1,
},
});
const incoming = base({
progressVersion: 5,
availableActions: ['regenerate_excel'],
currentGate: null,
});
const merged = mergeWorkbenchProcessingProjection(local, incoming);
expect(merged?.availableActions).toEqual(['regenerate_excel']);
expect(merged?.currentGate).toBeNull();
expect(merged?.progressVersion).toBe(5);
});
});
@@ -0,0 +1,43 @@
/**
* features/shipping-progress/mergeProcessingProjection.ts
* 用途:订单处理工作台 Projection 按 progress_version 合并(禁止旧包覆盖新包)。
* 依赖:ShippingProcessingProjection。
* 逻辑:仅工作台启用;任务中心不调用。incoming < local 丢弃;== 字段合并保留本地 UI;> 整包替换。
*/
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
/**
* 按 progressVersion 单调规则合并投影。
*
* 核心逻辑:
* - incoming < local → 返回 local(丢弃整包)
* - incoming == local → 浅合并字段,保留 local 上已有临时 UI 相关字段优先
* - incoming > local 或 local 为空 → 返回 incoming
*
* @param local - 当前工作台投影
* @param incoming - 新拉取并已 normalize 的投影
* @returns 应写入状态的投影
*/
export function mergeWorkbenchProcessingProjection(
local: ShippingProcessingProjection | null | undefined,
incoming: ShippingProcessingProjection | null | undefined,
): ShippingProcessingProjection | null {
if (!incoming) return local ?? null;
if (!local) return incoming;
const localVersion = Number(local.progressVersion || 0);
const incomingVersion = Number(incoming.progressVersion || 0);
if (incomingVersion < localVersion) {
return local;
}
if (incomingVersion > localVersion) {
return incoming;
}
// [STEP] 同版本:incoming 覆盖业务字段;本地临时 UI 由调用方另行保留。
return {
...local,
...incoming,
};
}
@@ -191,19 +191,46 @@ export function buildProgressRangeHint(
}
/**
* 构建订单处理工作台五域摘要(默认紧凑条用,非完整 15 阶)。
* 构建订单处理工作台五域摘要(压缩业务域一行)。
*
* 核心逻辑:当前索引落在域内 → current/blocked/failed;整域已过 → passed;否则 pending。
* 核心逻辑:若传入 authoritativeNodes(来自 projection.stageNodes),仅据此聚合,禁止第二套启发式;
* 未传时回退当前 stage 索引(兼容详情抽屉等非工作台主条场景)。
*
* @param projection - 统一投影
* @param authoritativeNodes - 可选权威 15 阶节点(工作台主条必须传入)
*/
export function buildReviewProgressDomainSummary(
projection: ShippingProcessingProjection | null | undefined,
authoritativeNodes?: Array<{ absoluteIndex: number; status: ShippingProcessingStageNodeStatus }> | null,
): ProgressDomainSummaryItem[] {
if (!projection) return [];
const currentIndex = stageAbsoluteIndex(projection.stage);
const statusNorm = String(projection.status || '').trim().toLowerCase();
return REVIEW_PROGRESS_DOMAIN_RANGES.map((domain) => {
let state: ProgressDomainState = 'pending';
if (currentIndex > domain.end) {
if (authoritativeNodes?.length) {
// [STEP] 仅由权威节点聚合:域内含 blocked/failed → 对应态;含 running/当前阶 → current;全 passed/skipped → passed。
const slice = authoritativeNodes.filter(
(node) => node.absoluteIndex >= domain.start && node.absoluteIndex <= domain.end,
);
if (slice.some((node) => node.status === 'failed')) {
state = 'failed';
} else if (slice.some((node) => node.status === 'blocked')) {
state = 'blocked';
} else if (
slice.some((node) => node.status === 'running')
|| (currentIndex >= domain.start && currentIndex <= domain.end)
) {
state = 'current';
} else if (
slice.length > 0
&& slice.every((node) => node.status === 'passed' || node.status === 'skipped')
) {
state = 'passed';
} else if (currentIndex > domain.end) {
state = 'passed';
}
} else if (currentIndex > domain.end) {
state = 'passed';
} else if (currentIndex >= domain.start && currentIndex <= domain.end) {
if (statusNorm === 'failed' || statusNorm === 'cancelled') state = 'failed';
@@ -0,0 +1,70 @@
/**
* features/shipping-progress/stageNodesAuthority.spec.ts
* 用途:验收 stage_nodes 权威读取与 fail-closed。
* 依赖:Vitest、stageNodesAuthority、SHIPPING_PROCESSING_STAGES。
* 逻辑:合法 15 节点返回;长度/状态非法返回 null。
*/
import { describe, expect, it } from 'vitest';
import {
SHIPPING_PROCESSING_STAGES,
type ShippingProcessingProjection,
type ShippingProcessingStageNode,
} from '@/features/chat/types/shipping.api.types';
import { readAuthoritativeStageNodes } from './stageNodesAuthority';
function projectionWithNodes(
nodes: ShippingProcessingStageNode[] | undefined,
): ShippingProcessingProjection {
return {
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: null,
conversationId: 'c1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
stageNodes: nodes,
};
}
describe('readAuthoritativeStageNodes', () => {
it('accepts exactly 15 valid nodes', () => {
const nodes = SHIPPING_PROCESSING_STAGES.map((stage, absoluteIndex) => ({
stage,
absoluteIndex,
status: absoluteIndex < 8 ? 'passed' as const : absoluteIndex === 8 ? 'blocked' as const : 'pending' as const,
}));
expect(readAuthoritativeStageNodes(projectionWithNodes(nodes))?.length).toBe(15);
});
it('returns null when stage_nodes missing or wrong length', () => {
expect(readAuthoritativeStageNodes(projectionWithNodes(undefined))).toBeNull();
expect(readAuthoritativeStageNodes(projectionWithNodes([]))).toBeNull();
});
it('returns null when status is illegal', () => {
const nodes = SHIPPING_PROCESSING_STAGES.map((stage, absoluteIndex) => ({
stage,
absoluteIndex,
status: (absoluteIndex === 0 ? 'weird' : 'pending') as ShippingProcessingStageNode['status'],
}));
expect(readAuthoritativeStageNodes(projectionWithNodes(nodes))).toBeNull();
});
});
@@ -0,0 +1,71 @@
/**
* features/shipping-progress/stageNodesAuthority.ts
* 用途:订单处理工作台 15 阶节点权威读取与校验(只信 projection.stageNodes)。
* 依赖:shipping.api.types ShippingProcessingProjection / StageNode、SHIPPING_PROCESSING_STAGES。
* 逻辑:ReviewProgressStrip 宽屏条与五域摘要共用;非法/缺失时 fail-closed,禁止启发式造假节点。
*/
import {
SHIPPING_PROCESSING_STAGES,
type ShippingProcessingProjection,
type ShippingProcessingStage,
type ShippingProcessingStageNode,
type ShippingProcessingStageNodeStatus,
} from '@/features/chat/types/shipping.api.types';
const VALID_NODE_STATUSES = new Set<ShippingProcessingStageNodeStatus>([
'skipped',
'pending',
'running',
'passed',
'blocked',
'failed',
]);
/**
* 校验并返回权威 stage_nodes;非法时返回 null。
*
* 核心逻辑:须恰好 15 个节点,且 stage / absoluteIndex / status 合法。
*
* @param projection - 统一处理投影
* @returns 规范化节点列表;不可用时 null
*/
export function readAuthoritativeStageNodes(
projection: ShippingProcessingProjection | null | undefined,
): ShippingProcessingStageNode[] | null {
const raw = projection?.stageNodes;
if (!Array.isArray(raw) || raw.length !== SHIPPING_PROCESSING_STAGES.length) {
return null;
}
const nodes: ShippingProcessingStageNode[] = [];
for (let i = 0; i < raw.length; i += 1) {
const item = raw[i];
if (!item || typeof item !== 'object') return null;
const stage = String(item.stage || '').trim() as ShippingProcessingStage;
const absoluteIndex = Number(item.absoluteIndex);
const status = String(item.status || '').trim() as ShippingProcessingStageNodeStatus;
if (!SHIPPING_PROCESSING_STAGES.includes(stage)) return null;
if (!Number.isInteger(absoluteIndex) || absoluteIndex !== i) return null;
if (SHIPPING_PROCESSING_STAGES[i] !== stage) return null;
if (!VALID_NODE_STATUSES.has(status)) return null;
nodes.push({ stage, absoluteIndex, status });
}
return nodes;
}
/**
* stage_nodes 不可用时的 fail-closed 告警(仅结构化字段)。
*
* @param params.workItemNo - 工作项编号
* @param params.reason - 简短原因码
*/
export function warnStageNodesUnavailable(params: {
workItemNo?: string | null;
reason: string;
}): void {
// eslint-disable-next-line no-console
console.warn('[shipping-workbench] stage_nodes unavailable', {
workItemNo: String(params.workItemNo || '').trim() || null,
reason: params.reason,
});
}
@@ -0,0 +1,155 @@
/**
* features/shipping-progress/workbenchActionRegistry.spec.ts
* 用途:验收订单处理工作台动作注册表与 fail-closed 规则。
* 依赖:Vitest、workbenchActionRegistry、actionPresentation。
* 逻辑:合法码可渲染;未知码告警且不进入 presentation;review 隐藏自跳转与 refresh。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
import { resolveProcessingActionPresentation } from './actionPresentation';
import {
WORKBENCH_ACTION_REGISTRY,
lookupWorkbenchAction,
resolveWorkbenchActionItem,
shouldRenderWorkbenchAction,
} from './workbenchActionRegistry';
function projection(
overrides: Partial<ShippingProcessingProjection> = {},
): ShippingProcessingProjection {
return {
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'eml',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: 'SN-1',
conversationId: 'c1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'blocked',
stage: 'inventory_matching',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
...overrides,
};
}
describe('workbenchActionRegistry', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('registers fulfillment and focus actions used by Footer', () => {
for (const code of [
'confirm_inventory_source',
'match_inventory',
'generate_excel',
'mark_manual_uploaded',
'retry_upload',
'view_result',
'view_record',
'confirm_customer',
'open_profile_review',
'open_inventory_source_review',
]) {
expect(lookupWorkbenchAction(code)).toBeTruthy();
}
expect(WORKBENCH_ACTION_REGISTRY.open_inventory_source_review.reviewBehavior).toBe('open_inventory_candidates');
expect(WORKBENCH_ACTION_REGISTRY.confirm_inventory_source.reviewBehavior).toBe('todo_panel');
expect(WORKBENCH_ACTION_REGISTRY.confirm_customer.reviewBehavior).toBe('open_customer_dialog');
});
it('hides open_order_review / edit_formal_task / refresh on review surface', () => {
expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.open_order_review, {
actionsExecutable: true,
surface: 'review',
})).toBe(false);
expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.edit_formal_task, {
actionsExecutable: true,
surface: 'review',
})).toBe(false);
expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.refresh, {
actionsExecutable: true,
surface: 'review',
})).toBe(false);
});
it('hides write actions when actionsExecutable=false but keeps view_result', () => {
expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.match_inventory, {
actionsExecutable: false,
surface: 'review',
})).toBe(false);
expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.view_result, {
actionsExecutable: false,
surface: 'review',
})).toBe(true);
});
it('warns and omits unregistered action codes from review presentation', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
const result = resolveProcessingActionPresentation(projection({
availableActions: ['totally_unknown_action', 'view_result'],
}), { surface: 'review', actionsExecutable: true });
expect(result.primary?.intent).toBe('view_result');
expect(warn).toHaveBeenCalled();
const payload = warn.mock.calls[0]?.[1] as { action_code?: string };
expect(payload?.action_code).toBe('totally_unknown_action');
});
it('exposes match_inventory as primary for review Footer', () => {
const result = resolveProcessingActionPresentation(projection({
currentGate: {
gateCode: 'inventory_match',
status: 'blocked',
nextActionCode: 'match_inventory',
blockingReasonCode: 'inventory_shortage',
attemptNo: 1,
},
availableActions: ['refresh'],
}), { surface: 'review', actionsExecutable: true });
expect(result.primary?.intent).toBe('open_inventory_match_review');
expect(result.primary?.actionCode).toBe('match_inventory');
expect(result.secondary).toBeNull();
});
it('hides confirm_customer when customer panel unavailable', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.confirm_customer, {
actionsExecutable: true,
surface: 'review',
panels: { customerUnresolved: false },
actionCode: 'confirm_customer',
})).toBe(false);
expect(warn).toHaveBeenCalled();
});
it('routes aliased open_inventory_source_review to todo_panel after create', () => {
// 后端 normalize 后 Footer 只见 open_inventory_source_review;建单后须 Todo。
const pre = resolveWorkbenchActionItem({
intent: 'open_inventory_source_review',
actionCode: 'open_inventory_source_review',
labelKey: 'x',
}, { postCreate: false });
expect(pre?.reviewBehavior).toBe('open_inventory_candidates');
const post = resolveWorkbenchActionItem({
intent: 'open_inventory_source_review',
actionCode: 'open_inventory_source_review',
labelKey: 'x',
}, { postCreate: true });
expect(post?.reviewBehavior).toBe('todo_panel');
expect(post?.todoActionCode).toBe('confirm_inventory_source');
});
});
@@ -0,0 +1,491 @@
/**
* features/shipping-progress/workbenchActionRegistry.ts
* 用途:订单处理工作台统一动作注册表(Projection action → 宿主执行器)。
* 依赖:shipping.api.types ActionIntent、ActionPresentationItem / Surface。
* 逻辑:Footer/Resolver 只经本表派发;未知码 fail-closed(不渲染 + console.warn);
* 写交互使用显式执行器(禁止宽泛 navigate_panel);面板依赖由 requiresPanel 守卫。
*/
import type { ShippingProcessingActionIntent } from '@/features/chat/types/shipping.api.types';
import type { ActionPresentationItem, ActionPresentationSurface } from './types';
/** 工作台执行器类别(禁止宽泛 navigate_panel)。 */
export type WorkbenchActionExecutorKind =
| 'todo_panel'
| 'open_customer_dialog'
| 'focus_field_conflicts'
| 'focus_duplicate_panel'
| 'focus_profile_panel'
| 'open_inventory_candidates'
| 'focus_inventory_issues'
| 'download'
| 'retry'
| 'view_result'
| 'view_record'
| 'refresh_strip_only'
| 'hidden_on_review';
/** 面板可用性键(与 WorkbenchPanelAvailability 对齐)。 */
export type WorkbenchPanelKey =
| 'customerUnresolved'
| 'hasFieldConflicts'
| 'hasDuplicateAdjudication'
| 'hasProfileMatch'
| 'hasInventoryCandidates'
| 'hasInventoryIssues';
/** 当前 Case 面板是否挂载/有内容,供 requiresPanel 过滤。 */
export interface WorkbenchPanelAvailability {
customerUnresolved?: boolean;
hasFieldConflicts?: boolean;
hasDuplicateAdjudication?: boolean;
hasProfileMatch?: boolean;
hasInventoryCandidates?: boolean;
hasInventoryIssues?: boolean;
}
/** 注册表条目。 */
export interface WorkbenchActionRegistryEntry {
/** 契约意图(与后端 SHIPPING_PROCESSING_ACTION_INTENTS 对齐)。 */
intent: ShippingProcessingActionIntent;
/** 工作台 surface 行为。 */
reviewBehavior: WorkbenchActionExecutorKind;
/** TaskTodoPanel 调用时使用的动作码(可与原始码不同)。 */
todoActionCode?: string;
/** 页面内滚动/高亮锚点 data-testid。 */
scrollTestId?: string;
/** 是否需要正式 Notice 任务详情(履约写)。 */
requiresFormalTask?: boolean;
/** 依赖的面板可用性键;缺失时 fail-closed 隐藏。 */
requiresPanel?: WorkbenchPanelKey;
/** 是否为写操作(actionsExecutable=false 时隐藏)。 */
isWrite: boolean;
/** 预期 stage family(契约测试用)。 */
stageFamily: 'pre_create' | 'post_create' | 'any' | 'terminal';
}
/**
* 合法 action_code → 注册条目(含别名)。
* 新增后端动作必须先登记本表,否则前端 fail-closed。
*/
export const WORKBENCH_ACTION_REGISTRY: Record<string, WorkbenchActionRegistryEntry> = {
open_order_review: {
intent: 'open_order_review',
reviewBehavior: 'hidden_on_review',
isWrite: false,
stageFamily: 'pre_create',
},
open_review: {
intent: 'open_order_review',
reviewBehavior: 'hidden_on_review',
isWrite: false,
stageFamily: 'pre_create',
},
open_order_processing: {
intent: 'open_order_review',
reviewBehavior: 'hidden_on_review',
isWrite: false,
stageFamily: 'pre_create',
},
enter_manual_review: {
intent: 'open_order_review',
reviewBehavior: 'hidden_on_review',
isWrite: false,
stageFamily: 'pre_create',
},
edit_formal_task: {
intent: 'edit_formal_task',
reviewBehavior: 'hidden_on_review',
isWrite: false,
stageFamily: 'any',
},
freeze_order: {
intent: 'edit_formal_task',
reviewBehavior: 'hidden_on_review',
isWrite: true,
stageFamily: 'post_create',
},
open_profile_review: {
intent: 'open_profile_review',
reviewBehavior: 'focus_profile_panel',
scrollTestId: 'review-profile-match-panel',
requiresPanel: 'hasProfileMatch',
isWrite: false,
stageFamily: 'pre_create',
},
confirm_customer: {
intent: 'confirm_customer',
reviewBehavior: 'open_customer_dialog',
scrollTestId: 'review-customer-resolution-panel',
requiresPanel: 'customerUnresolved',
isWrite: true,
stageFamily: 'pre_create',
},
resolve_field_conflicts: {
intent: 'resolve_field_conflicts',
reviewBehavior: 'focus_field_conflicts',
scrollTestId: 'review-field-conflict-panel',
requiresPanel: 'hasFieldConflicts',
isWrite: true,
stageFamily: 'pre_create',
},
adjudicate_duplicate: {
intent: 'adjudicate_duplicate',
reviewBehavior: 'focus_duplicate_panel',
scrollTestId: 'review-duplicate-panel',
requiresPanel: 'hasDuplicateAdjudication',
isWrite: true,
stageFamily: 'pre_create',
},
// 建单前:打开库存候选面板(禁止 TaskTodoPanel);不依赖面板键(Gate 已授权)。
open_inventory_source_review: {
intent: 'open_inventory_source_review',
reviewBehavior: 'open_inventory_candidates',
scrollTestId: 'review-inventory-candidates-panel',
isWrite: true,
stageFamily: 'pre_create',
},
// 建单后:委托 TaskTodoPanel 确认库存源。
confirm_inventory_source: {
intent: 'open_inventory_source_review',
reviewBehavior: 'todo_panel',
todoActionCode: 'confirm_inventory_source',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
retry_resolve_inventory_source: {
intent: 'open_inventory_source_review',
reviewBehavior: 'todo_panel',
todoActionCode: 'confirm_inventory_source',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
open_inventory_match_review: {
intent: 'open_inventory_match_review',
reviewBehavior: 'todo_panel',
todoActionCode: 'match_inventory',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
match_inventory: {
intent: 'open_inventory_match_review',
reviewBehavior: 'todo_panel',
todoActionCode: 'match_inventory',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
rematch: {
intent: 'open_inventory_match_review',
reviewBehavior: 'todo_panel',
todoActionCode: 'rematch',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
open_shortage_review: {
intent: 'open_shortage_review',
reviewBehavior: 'focus_inventory_issues',
scrollTestId: 'review-inventory-issue-list',
requiresPanel: 'hasInventoryIssues',
isWrite: true,
stageFamily: 'post_create',
},
upload_inventory_file: {
intent: 'upload_inventory_file',
reviewBehavior: 'todo_panel',
todoActionCode: 'upload_inventory_file',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
regenerate_excel: {
intent: 'regenerate_excel',
reviewBehavior: 'todo_panel',
todoActionCode: 'generate_excel',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
generate_excel: {
intent: 'regenerate_excel',
reviewBehavior: 'todo_panel',
todoActionCode: 'generate_excel',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
download_excel: {
intent: 'download_excel',
reviewBehavior: 'download',
isWrite: false,
stageFamily: 'post_create',
},
open_manual_upload: {
intent: 'open_manual_upload',
reviewBehavior: 'todo_panel',
todoActionCode: 'mark_manual_uploaded',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
wait_manual_upload: {
intent: 'open_manual_upload',
reviewBehavior: 'todo_panel',
todoActionCode: 'mark_manual_uploaded',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
mark_manual_uploaded: {
intent: 'open_manual_upload',
reviewBehavior: 'todo_panel',
todoActionCode: 'mark_manual_uploaded',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
regenerate_manual_upload_todo: {
intent: 'open_manual_upload',
reviewBehavior: 'todo_panel',
todoActionCode: 'mark_manual_uploaded',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
retry_upload: {
intent: 'retry',
reviewBehavior: 'todo_panel',
todoActionCode: 'retry_upload',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
retry_freight_upload_rpa: {
intent: 'retry',
reviewBehavior: 'todo_panel',
todoActionCode: 'retry_upload',
requiresFormalTask: true,
isWrite: true,
stageFamily: 'post_create',
scrollTestId: 'review-formal-task-todo-panel',
},
retry: {
intent: 'retry',
reviewBehavior: 'retry',
isWrite: true,
stageFamily: 'any',
},
retry_parse: {
intent: 'retry',
reviewBehavior: 'retry',
isWrite: true,
stageFamily: 'pre_create',
},
retry_failed_documents: {
intent: 'retry',
reviewBehavior: 'retry',
isWrite: true,
stageFamily: 'pre_create',
},
retry_failed_attachments: {
intent: 'retry',
reviewBehavior: 'retry',
isWrite: true,
stageFamily: 'pre_create',
},
refresh: {
intent: 'refresh',
reviewBehavior: 'refresh_strip_only',
isWrite: false,
stageFamily: 'any',
},
view_result: {
intent: 'view_result',
reviewBehavior: 'view_result',
isWrite: false,
stageFamily: 'terminal',
scrollTestId: 'review-formal-task-result-region',
},
open_fulfillment: {
intent: 'view_result',
reviewBehavior: 'view_result',
isWrite: false,
stageFamily: 'terminal',
scrollTestId: 'review-formal-task-result-region',
},
view_details: {
intent: 'view_result',
reviewBehavior: 'view_result',
isWrite: false,
stageFamily: 'terminal',
scrollTestId: 'review-formal-task-result-region',
},
focus_task: {
intent: 'view_result',
reviewBehavior: 'view_result',
isWrite: false,
stageFamily: 'any',
scrollTestId: 'review-formal-task-result-region',
},
view_record: {
intent: 'view_record',
reviewBehavior: 'view_record',
isWrite: false,
stageFamily: 'any',
},
cancel_task: {
intent: 'view_record',
reviewBehavior: 'view_record',
isWrite: false,
stageFamily: 'any',
},
cancel_run: {
intent: 'view_record',
reviewBehavior: 'view_record',
isWrite: false,
stageFamily: 'any',
},
};
/**
* 查找注册表条目(大小写不敏感)。
*
* @param actionCode - Gate / available_actions 原始码
* @returns 注册条目;未登记返回 null
*/
export function lookupWorkbenchAction(actionCode: string | null | undefined): WorkbenchActionRegistryEntry | null {
const key = String(actionCode || '').trim().toLowerCase();
if (!key) return null;
return WORKBENCH_ACTION_REGISTRY[key] || null;
}
/**
* 未知动作 fail-closed 告警(仅 action_code / surface / workItemType)。
*
* @param params.actionCode - 未登记动作码
* @param params.surface - 展示面
* @param params.workItemType - 可选工作项类型
*/
export function warnUnregisteredWorkbenchAction(params: {
actionCode: string;
surface: ActionPresentationSurface;
workItemType?: string | null;
}): void {
// eslint-disable-next-line no-console
console.warn('[shipping-workbench] unregistered action hidden', {
action_code: String(params.actionCode || '').trim(),
surface: params.surface,
workItemType: String(params.workItemType || '').trim() || null,
});
}
/**
* 面板依赖不满足时告警(fail-closed 隐藏)。
*
* @param params.actionCode - 动作码
* @param params.panelKey - 缺失的面板键
* @param params.surface - 展示面
*/
export function warnUnavailableWorkbenchPanel(params: {
actionCode: string;
panelKey: WorkbenchPanelKey;
surface: ActionPresentationSurface;
}): void {
// eslint-disable-next-line no-console
console.warn('[shipping-workbench] required panel unavailable', {
action_code: String(params.actionCode || '').trim(),
panel_key: params.panelKey,
surface: params.surface,
});
}
/**
* 判断工作台 surface 是否应渲染该动作。
*
* 核心逻辑:review 隐藏自跳转与 refresh;写操作受 actionsExecutable 约束;
* requiresPanel 在 panels 提供时做可用性守卫。
*
* @param entry - 注册条目
* @param options.actionsExecutable - 是否允许业务写
* @param options.surface - 展示面
* @param options.panels - 可选面板可用性
* @param options.actionCode - 可选原始码(告警用)
*/
export function shouldRenderWorkbenchAction(
entry: WorkbenchActionRegistryEntry,
options: {
actionsExecutable: boolean;
surface: ActionPresentationSurface;
panels?: WorkbenchPanelAvailability | null;
actionCode?: string;
},
): boolean {
if (options.surface === 'review') {
if (entry.reviewBehavior === 'hidden_on_review') return false;
if (entry.reviewBehavior === 'refresh_strip_only') return false;
}
if (entry.isWrite && !options.actionsExecutable) return false;
if (entry.requiresPanel && options.panels) {
const available = Boolean(options.panels[entry.requiresPanel]);
if (!available) {
warnUnavailableWorkbenchPanel({
actionCode: options.actionCode || entry.intent,
panelKey: entry.requiresPanel,
surface: options.surface,
});
return false;
}
}
return true;
}
/**
* 从 ActionPresentationItem 解析注册条目;未登记返回 null。
*
* 核心逻辑:优先按原始 actionCode 查找;建单后若后端把 confirm_inventory_source
* 别名为 open_inventory_source_review,则改用 todo_panel 条目(禁止再开候选面板)。
*
* @param item - 统一动作项
* @param options.postCreate - 正式 Notice 已建单时为 true
*/
export function resolveWorkbenchActionItem(
item: ActionPresentationItem,
options?: { postCreate?: boolean },
): WorkbenchActionRegistryEntry | null {
const byCode = lookupWorkbenchAction(item.actionCode);
const byIntent = lookupWorkbenchAction(item.intent);
const entry = byCode || byIntent;
if (!entry) return null;
// [STEP] 建单后库存源确认:契约意图仍是 open_inventory_source_review,执行器须走 Todo。
const code = String(item.actionCode || '').trim().toLowerCase();
const inventorySourceCodes = new Set([
'open_inventory_source_review',
'confirm_inventory_source',
'retry_resolve_inventory_source',
]);
if (
options?.postCreate
&& (entry.intent === 'open_inventory_source_review' || inventorySourceCodes.has(code))
) {
return lookupWorkbenchAction('confirm_inventory_source') || entry;
}
return entry;
}