feat(shipping-notice): 升级货代发货流程为五阶段,完善业务校验

将货代发货流程从四阶段扩展为五阶段,拆分上传相关逻辑至独立的货代上传阶段;
统一多语言文案修正客户状态语义,将"客户尚未识别"调整为符合业务的"客户尚未确认";
新增严格的上传成功验证谓词,需同时满足任务状态、全部预约单上传成功、存在有效成功上传尝试三个条件方可标记为完成;
新增坐标取值模型配置,支持Legacy冻结绝对坐标和锚点框架受限平移两种模式;
更新全链路相关文档、前端组件、后端服务与测试用例,确保业务逻辑对齐新业务规则。
This commit is contained in:
hugo committed 2026-08-21 09:20:47 +08:00
1 parent 1b6483a4ea
commit 935bf26fa6
86 files changed
+2743 -311

No files matched your search

@@ -238,7 +238,7 @@ export const getWorkspaceShippingProcessing = async (
.then((raw): WorkspaceShippingProcessingResponse => ({
conversation_id: String(raw?.conversation_id || normalized),
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
// 会话级 status_groups / 四阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
// 会话级 status_groups / 五阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
// 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。
conversation_processing: raw?.conversation_processing
? normalizeConversationProcessingProjection(raw.conversation_processing)
@@ -1,6 +1,6 @@
/**
* features/chat/components/ShippingWorkflowStepper.vue
* 用途:货代发货四阶段 Stepper 展示组件。
* 用途:货代发货五阶段 Stepper 展示组件。
* 依赖:shipping/shippingStepper、vue-i18n。
* 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。
*/
@@ -33,7 +33,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
<template>
<div class="space-y-2">
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4' : 'md:grid-cols-4'">
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-5' : 'md:grid-cols-5'">
<div
v-for="(step, index) in steps"
:key="step.id"
@@ -167,7 +167,9 @@ const hasDiagnosticDetails = computed(() => Boolean(
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
<section
class="rounded-lg border px-3 py-2 text-xs"
:class="eligibility.can_build
:class="eligibility.can_build === null
? 'border-slate-200 bg-slate-50 text-slate-800 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100'
: eligibility.can_build
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100'
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
data-testid="review-eligibility-details-overall"
@@ -175,8 +177,10 @@ const hasDiagnosticDetails = computed(() => Boolean(
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build === null ? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-100' : eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build === null
? t('chat.shippingOrderReview.buildEligibility.notValidated')
: eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span>
</span>
@@ -153,6 +153,7 @@ const lowConfidenceFields = computed(() => props.eligibility?.issues?.flatMap((i
) || []);
const unexplainedBlocked = computed(() => Boolean(
props.eligibility
&& props.eligibility.status !== 'not_validated'
&& props.eligibility.can_build === false
&& !props.eligibility.issues?.length
&& !props.eligibility.failed_gates?.length
@@ -212,13 +213,17 @@ const gateChecklist = computed(() => {
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="eligibility.can_build
:class="eligibility.can_build === null
? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'
: eligibility.can_build
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
data-testid="review-build-eligibility-badge"
>
{{
eligibility.can_build
eligibility.status === 'not_validated'
? t('chat.shippingOrderReview.buildEligibility.notValidated')
: eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo')
}}
@@ -0,0 +1,63 @@
/**
* features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts
* 用途:锁定唯一标准客户候选的工作台提示,避免将可自动确认状态误报为未识别。
* 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel。
* 逻辑:unique_candidate 显示自动确认说明和明确按钮;其他未确认状态维持人工选择入口。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewCustomerResolutionPanel from './ReviewCustomerResolutionPanel.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingCustomer: { loadFailed: '加载失败', confirmFailed: '确认失败' },
shippingOrderReview: {
customerResolution: {
title: '客户确认', subtitle: '请选择标准客户', uniqueCandidateHint: '已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。',
confirmUniqueCandidate: '确认唯一候选', selectCustomer: '选择标准客户', retrying: '识别中…', retryCustomer: '重新识别客户',
retryDone: '已重新识别客户', retryFailed: '重新识别客户失败', confirmed: '客户已确认', confirmReason: '人工确认',
standardCustomer: '标准客户', customerCode: '客户编码', matchedInputs: '匹配输入', candidates: '候选客户', pdfReparseHint: '请重新识别 PDF',
inputLabels: { customerCode: '客户编码', customerName: '客户名称', address: '地址', email: '邮箱', domain: '域名', other: '其他' },
status: { unique_candidate: '唯一候选', unmatched: '未匹配', confirmed: '已确认' },
},
resume: { autoCreated: '已自动建单', waitingManualConfirm: '等待人工确认' },
},
},
},
},
});
function mountPanel(status: string) {
return mount(ReviewCustomerResolutionPanel, {
props: {
caseNo: 'CASE-CUSTOMER-1',
editable: true,
resolution: { resolved: false, status, raw_name: 'ACME' },
},
global: {
plugins: [i18n],
stubs: { ShippingCustomerConfirmDialog: true },
},
});
}
describe('ReviewCustomerResolutionPanel', () => {
it('唯一候选展示自动确认说明和明确确认入口', () => {
const wrapper = mountPanel('unique_candidate');
expect(wrapper.text()).toContain('保存校验时系统会自动确认');
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('确认唯一候选');
});
it('非唯一未确认状态维持人工选择客户入口', () => {
const wrapper = mountPanel('unmatched');
expect(wrapper.text()).not.toContain('保存校验时系统会自动确认');
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('选择标准客户');
});
});
@@ -41,6 +41,10 @@ const options = ref<ShippingCustomerOption[]>([]);
const loadingOptions = ref(false);
const resolved = computed(() => Boolean(props.resolution?.resolved));
const hasUniqueCandidate = computed(() => (
!resolved.value
&& String(props.resolution?.status || '').trim() === 'unique_candidate'
));
const statusLabel = computed(() => {
const status = String(props.resolution?.status || '').trim();
if (!status) {
@@ -198,7 +202,11 @@ async function onRetry() {
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.customerResolution.subtitle') }}</p>
<p class="mt-0.5 text-xs text-muted">
{{ hasUniqueCandidate
? t('chat.shippingOrderReview.customerResolution.uniqueCandidateHint')
: t('chat.shippingOrderReview.customerResolution.subtitle') }}
</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
@@ -244,7 +252,9 @@ async function onRetry() {
:disabled="busy"
@click="openSelectDialog"
>
{{ t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
{{ hasUniqueCandidate
? t('chat.shippingOrderReview.customerResolution.confirmUniqueCandidate')
: t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
</button>
<button
type="button"
@@ -30,7 +30,7 @@ export type ReviewDocumentNavItem = {
lifecycle_stage?: ReviewLifecycleStageCode | null;
};
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
@@ -112,7 +112,7 @@ function caseStatusLabel(status: string): string {
/** 后端阶段码只做 i18n 投影;缺失时保留空白,禁止按 Case 状态补造阶段。 */
function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
const code = String(item.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(code)) return null;
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(code)) return null;
const key = `chat.shippingOrderReview.lifecycle.stages.${code}`;
return te(key) ? t(key) : null;
}
@@ -17,6 +17,7 @@ const i18n = createI18n({
messages: {
'zh-CN': {
chat: {
shippingNoticeRetryParse: '重试解析',
shippingOrderReview: {
lifecycle: {
navigation: '订单生命周期阶段',
@@ -33,6 +34,7 @@ const i18n = createI18n({
const stages: ReviewLifecycleStageItem[] = [
{ code: 'order_review', label: '订单复核', state: 'completed' },
{ code: 'fulfillment_prep', label: '通知准备', state: 'current' },
{ code: 'freight_upload', label: '货代上传', state: 'blocked', reason: '请先完成通知准备' },
{ code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' },
];
@@ -45,6 +47,30 @@ function mountNavigation() {
}
describe('ReviewLifecycleStageNavigation', () => {
it('only exposes retry_parse on the current intake stage when the server authorizes it', async () => {
const wrapper = mount(ReviewLifecycleStageNavigation, {
props: {
stages: [
{ code: 'intake_parse', label: '接收解析', state: 'current' },
...stages,
],
activeCode: 'intake_parse',
availableActions: ['retry_parse'],
retrying: false,
},
global: { plugins: [i18n] },
});
// 关键断言:重试入口必须位于已发送文件的当前阶段卡,且完全由后端动作授权。
const retry = wrapper.get('[data-testid="review-lifecycle-stage-retry-parse"]');
expect(retry.text()).toContain('重试解析');
await retry.trigger('click');
expect(wrapper.emitted('retry-parse')).toEqual([[]]);
await wrapper.setProps({ availableActions: [] });
expect(wrapper.find('[data-testid="review-lifecycle-stage-retry-parse"]').exists()).toBe(false);
});
it('renders intake_parse as the first lifecycle stage', () => {
const wrapper = mount(ReviewLifecycleStageNavigation, {
props: {
@@ -63,9 +89,10 @@ describe('ReviewLifecycleStageNavigation', () => {
'review-lifecycle-stage-intake_parse',
'review-lifecycle-stage-order_review',
'review-lifecycle-stage-fulfillment_prep',
'review-lifecycle-stage-freight_upload',
'review-lifecycle-stage-upload_complete',
]);
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-4');
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-5');
});
it('allows opening a completed stage for inspection', async () => {
@@ -1,13 +1,13 @@
<!--
features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue
用途:订单生命周期工作台的四阶段导航,只呈现父级已裁决的阶段状态。
用途:订单生命周期工作台的五阶段导航,只呈现父级已裁决的阶段状态。
依赖:父级 ShippingOrderReviewView 提供阶段、状态和阻断原因;lucide-vue-next 图标。
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。
-->
<script setup lang="ts">
import { Check, LockKeyhole } from 'lucide-vue-next';
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
export interface ReviewLifecycleStageItem {
@@ -21,13 +21,25 @@ const props = defineProps<{
stages: ReviewLifecycleStageItem[];
/** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */
activeCode: ReviewLifecycleStageCode | null;
/** 仅消费当前对象后端下发的恢复动作,禁止按阶段或状态由前端猜测。 */
availableActions?: string[];
/** retry_parse 请求中的互斥状态,避免用户重复提交。 */
retrying?: boolean;
}>();
const emit = defineEmits<{
select: [code: ReviewLifecycleStageCode];
'open-detail': [code: ReviewLifecycleStageCode];
'retry-parse': [];
}>();
/** 接收解析的恢复只在后端明确授权且该阶段为当前阶段时展示。 */
function canRetryParse(stage: ReviewLifecycleStageItem): boolean {
return stage.code === 'intake_parse'
&& stage.state === 'current'
&& (props.availableActions || []).includes('retry_parse');
}
/**
* 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。
*/
@@ -43,7 +55,7 @@ function selectStage(stage: ReviewLifecycleStageItem) {
:aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')"
data-testid="review-lifecycle-stage-navigation"
>
<div class="grid gap-2 sm:grid-cols-4">
<div class="grid gap-2 sm:grid-cols-5">
<div
v-for="stage in props.stages"
:key="stage.code"
@@ -81,6 +93,16 @@ function selectStage(stage: ReviewLifecycleStageItem) {
? $t('chat.shippingOrderReview.lifecycle.completed')
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
</button>
<button
v-if="canRetryParse(stage)"
type="button"
class="mt-2 rounded border border-brand-300 px-2 py-1 text-xs font-medium text-brand-700 hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-brand-700 dark:text-brand-200 dark:hover:bg-brand-950/40"
data-testid="review-lifecycle-stage-retry-parse"
:disabled="props.retrying === true"
@click="emit('retry-parse')"
>
{{ $t('chat.shippingNoticeRetryParse') }}
</button>
</div>
</div>
</nav>
@@ -18,6 +18,10 @@ const i18n = createI18n({
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
routeType: '路由类型', executionMode: '执行模式',
coordinateModel: {
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
translateY: '纵向平移', reasonCodes: '原因码',
},
status: { matched: '已匹配', ambiguous: '多个候选' },
} } },
},
@@ -44,6 +48,34 @@ function mountPanel(needsReview = false) {
});
}
function mountAnchorFramePanel(visibility: 'admin' | 'admin_only' = 'admin') {
return mount(ReviewProfileMatchPanel, {
props: {
profileMatch: {
available: true,
visibility,
status: 'unique_match',
needs_review: false,
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
candidates: [{
profile_code: 'ODP-A',
version: 1,
display_name: '客户订单模板',
score: 0.99,
coordinate_transform: {
status: 'applied',
translate_x: 0.001,
translate_y: 0.03,
reason_codes: [],
},
}],
fallback_reason_codes: [],
},
},
global: { plugins: [i18n] },
});
}
describe('ReviewProfileMatchPanel', () => {
it('默认收起无需关注的候选列表', () => {
const wrapper = mountPanel(false);
@@ -69,4 +101,23 @@ describe('ReviewProfileMatchPanel', () => {
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).toContain('客户订单模板');
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).not.toContain('ODP-A');
});
it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => {
const wrapper = mountAnchorFramePanel();
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
const details = wrapper.get('[data-testid="review-profile-match-details"]');
expect(details.text()).toContain('锚点坐标框架');
expect(details.text()).toContain('纵向平移');
expect(details.text()).toContain('0.03');
expect(details.text()).not.toContain('ORDER NO.');
expect(details.text()).not.toContain('x0');
});
it('非管理员不可见锚点框架技术详情', async () => {
const wrapper = mountAnchorFramePanel('admin_only');
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-profile-match-coordinate-transform"]').exists()).toBe(false);
});
});
@@ -30,6 +30,19 @@ const candidateCount = computed(() => (props.profileMatch?.candidates || []).len
const defaultCandidatesExpanded = computed(() => false);
const candidatesOpenOverride = ref<boolean | null>(null);
const candidatesExpanded = computed(() => candidatesOpenOverride.value ?? defaultCandidatesExpanded.value);
const selectedCoordinateTransform = computed(() => {
if (!isAdminView.value) return null;
const selectedCode = String(props.profileMatch?.selected_profile?.profile_code || '');
const selectedVersion = props.profileMatch?.selected_profile?.version;
const candidate = (props.profileMatch?.candidates || []).find((item) => (
item.profile_code === selectedCode
&& (selectedVersion == null || item.version === selectedVersion)
));
return candidate?.coordinate_transform || null;
});
const coordinateTransformReasonCodes = computed(() => (
selectedCoordinateTransform.value?.reason_codes || []
));
watch(
() => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`,
@@ -118,6 +131,17 @@ const selectedLabel = computed(() => {
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
</div>
<div v-if="selectedCoordinateTransform" data-testid="review-profile-match-coordinate-transform" class="mt-2 rounded-lg border border-sky-200 bg-sky-50 px-2.5 py-2 text-[11px] text-sky-950 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-100">
<div class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.anchorFrame') }}</div>
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1">
<span>{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.status') }}: {{ selectedCoordinateTransform.status }}</span>
<span v-if="selectedCoordinateTransform.translate_x != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateX') }}: {{ selectedCoordinateTransform.translate_x }}</span>
<span v-if="selectedCoordinateTransform.translate_y != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateY') }}: {{ selectedCoordinateTransform.translate_y }}</span>
</div>
<div v-if="coordinateTransformReasonCodes.length" class="mt-1">
{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.reasonCodes') }}: {{ coordinateTransformReasonCodes.join(', ') }}
</div>
</div>
</dl>
<ul
class="mt-2 max-h-48 space-y-1.5 overflow-y-auto pr-1"
@@ -801,6 +801,7 @@ describe('ShippingConversationProcessingCard', () => {
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
blocking_reason: null,
@@ -820,6 +821,7 @@ describe('ShippingConversationProcessingCard', () => {
expect(row.text()).toContain('通知准备');
expect(row.text()).toContain('订单复核 · 可进入');
expect(row.text()).toContain('通知准备 · 当前可处理');
expect(row.text()).toContain('货代上传 · 前置未完成');
expect(row.text()).toContain('通知完成 · 前置未完成');
});
@@ -50,8 +50,8 @@ const props = defineProps<{
hasMoreHistory?: boolean;
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
workbenchMode?: boolean;
/** 批次四阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
/** 批次五阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
/** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */
fileSearchQuery?: string;
/** 后端已授权下载的正式 Excel 对应 OT。 */
@@ -94,12 +94,13 @@ type WorkbenchFileRow = {
po_number?: string | null;
projection?: ShippingProcessingProjection;
};
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number];
const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
order_review: 'orderReview',
fulfillment_prep: 'fulfillmentPrep',
freight_upload: 'freightUpload',
upload_complete: 'uploadComplete',
};
@@ -454,7 +455,7 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
return taskReasonLabel(task);
}
/** 文件工作面显示四阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
/** 文件工作面显示五阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
function workbenchFileLifecycleStage(file: WorkbenchFileRow): string {
const code = String(file.projection?.uiState?.lifecycleStage || '').trim();
const key = LIFECYCLE_STAGE_LABEL_KEYS[code];
@@ -2,7 +2,7 @@
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
* 用途:验收批次进度中心只投影后端实时状态,不再保留文件详情抽屉。
* 依赖:Vitest、Vue Test Utils、Timeline、ShippingConversationProcessingCard、shipping API。
* 逻辑:四阶段、生命周期入口与单文件取消均由后端 Projection/availableActions 决定。
* 逻辑:五阶段、生命周期入口与单文件取消均由后端 Projection/availableActions 决定。
*/
import { flushPromises, mount } from '@vue/test-utils';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -116,23 +116,29 @@ describe('ShippingWorkflowTimeline', () => {
api.reparseBatch.mockClear();
});
it('renders backend-owned four-stage summaries and the authorized download toolbar', async () => {
it('prefers backend five-stage lifecycle nodes and shows the authorized download toolbar in freight upload', async () => {
const processing = processingProjection({
four_stage_nodes: [
lifecycle_nodes: [
{ code: 'intake_parse', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
{ code: 'order_review', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
{ code: 'fulfillment_prep', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
{ code: 'upload_complete', status: 'running', summary: { total: 1, completed: 0, needs_action: 1, processing: 0, failed: 0, blocking_reason: { code: 'manual_upload_pending' } } },
{ code: 'freight_upload', status: 'running', summary: { total: 1, completed: 0, needs_action: 1, processing: 0, failed: 0, blocking_reason: { code: 'manual_upload_pending' } } },
{ code: 'upload_complete', status: 'pending', summary: { total: 1, completed: 0, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
],
// 新字段存在时必须优先使用,不能显示兼容字段的旧/冲突结果。
four_stage_nodes: [{ code: 'upload_complete', status: 'passed', summary: { total: 9, completed: 9, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } }],
output_artifacts: [{ order_task_no: 'OT-1', filename: 'notice.xlsx', type: 'xlsx', status: 'ready', action: { code: 'download_excel', enabled: true } }],
} as Partial<ConversationProcessingProjection>);
const wrapper = mountTimeline(processing, [fileProjection()]);
await flushPromises();
expect(wrapper.get('[data-testid="shipping-workflow-four-stage-progress"]').text()).toContain('接收解析');
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-upload_complete"]');
// 四阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。
expect(upload.text()).toBe('通知完成1');
const progress = wrapper.get('[data-testid="shipping-workflow-lifecycle-progress"]');
expect(progress.text()).toContain('接收解析');
expect(progress.text()).toContain('货代上传');
expect(progress.findAll('button')).toHaveLength(5);
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-freight_upload"]');
// 五阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。
expect(upload.text()).toBe('货代上传1');
await upload.trigger('click');
expect(wrapper.find('[data-testid="shipping-workflow-download-toolbar"]').exists()).toBe(true);
});
@@ -463,7 +469,7 @@ describe('ShippingWorkflowTimeline', () => {
}));
});
it('shows only title and total on four-stage cards', async () => {
it('falls back to the compatibility lifecycle field and shows only title and total', async () => {
const processing = processingProjection({
four_stage_nodes: [{
code: 'order_review', status: 'blocked',
@@ -1,6 +1,6 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「批次进度中心」——后端批次投影、四阶段进度和文件行操作。
* 用途:聊天页右侧「批次进度中心」——后端批次投影、五阶段进度和文件行操作。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
* ReasonDialog、ProcessGateRecoveryCard。
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
@@ -115,25 +115,28 @@ const processing = computed(() => ctl.value.processing?.value ?? null);
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
const displayProcessing = computed(() => processing.value);
const batchArtifacts = computed(() => displayProcessing.value?.output_artifacts || []);
const batchFourStageNodes = computed(() => displayProcessing.value?.four_stage_nodes || []);
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'>('all');
const batchLifecycleNodes = computed(() => (
displayProcessing.value?.lifecycle_nodes || displayProcessing.value?.four_stage_nodes || []
));
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete'>('all');
const fileSearchQuery = ref('');
const selectedDownloadTaskNos = ref<string[]>([]);
/** 四阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
/** 五阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
const BATCH_LIFECYCLE_I18N_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
order_review: 'orderReview',
fulfillment_prep: 'fulfillmentPrep',
freight_upload: 'freightUpload',
upload_complete: 'uploadComplete',
};
function batchFourStageLabelKey(code: string): string {
return BATCH_FOUR_STAGE_I18N_KEYS[code] || code;
function batchLifecycleLabelKey(code: string): string {
return BATCH_LIFECYCLE_I18N_KEYS[code] || code;
}
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete') {
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete') {
lifecycleFilter.value = lifecycleFilter.value === code ? 'all' : code;
}
/** 阶段卡仅展示后端统计总数;状态、阻塞和推进语义由颜色与边框表达。 */
function stageTotalText(node: NonNullable<typeof batchFourStageNodes.value>[number]): string {
function stageTotalText(node: NonNullable<typeof batchLifecycleNodes.value>[number]): string {
return String(Number(node.summary?.total || 0));
}
/** 下载资格仅来自后端 output_artifacts 的授权动作;筛选仅影响展示,不缩减授权集合。 */
@@ -1024,15 +1027,15 @@ watch(
/>
</div>
</div>
<section v-if="batchFourStageNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-four-stage-progress">
<div class="grid grid-cols-4 gap-2">
<button v-for="node in batchFourStageNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :class="[node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)">
<span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(node.code)}`) }}</span>
<section v-if="batchLifecycleNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-lifecycle-progress">
<div class="grid grid-cols-2 gap-2 sm:grid-cols-5">
<button v-for="node in batchLifecycleNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :class="[node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)">
<span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchLifecycleLabelKey(node.code)}`) }}</span>
<span class="mt-0.5 block text-[11px] opacity-80">{{ stageTotalText(node) }}</span>
</button>
</div>
<div v-if="lifecycleFilter !== 'all'" class="mt-2 flex items-center justify-between gap-2 text-xs text-secondary">
<span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(lifecycleFilter)}`) }) }}</span>
<span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchLifecycleLabelKey(lifecycleFilter)}`) }) }}</span>
<button type="button" class="text-brand-700 hover:underline" data-testid="shipping-workflow-clear-stage-filter" @click="lifecycleFilter = 'all'">{{ t('chat.shippingProcessing.batchWorkbench.clearStageFilter') }}</button>
</div>
<p v-if="Number(displayProcessing?.unclassified_summary?.count || 0) > 0" class="mt-2 text-xs text-amber-700" data-testid="shipping-workflow-unclassified-summary">
@@ -1048,7 +1051,7 @@ watch(
<span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.search.label') }}</span>
<input v-model="fileSearchQuery" type="search" class="w-full rounded-md border border-default bg-surface px-2.5 py-1.5 text-xs" :placeholder="t('chat.shippingProcessing.batchWorkbench.search.placeholder')" data-testid="shipping-workflow-file-search">
</label>
<div v-if="lifecycleFilter === 'upload_complete' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar">
<div v-if="lifecycleFilter === 'freight_upload' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar">
<label class="inline-flex items-center gap-1 text-xs text-secondary"><input type="checkbox" :checked="allDownloadableSelected" data-testid="shipping-workflow-download-select-all" @change="toggleAllDownloadSelections"><span>{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selectAll') }}</span></label>
<span class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selected', { count: selectedDownloadTaskNos.length }) }}</span>
<button type="button" class="rounded-md border border-brand-300 px-2.5 py-1 text-xs font-medium text-brand-700 disabled:opacity-50" :disabled="!selectedDownloadTaskNos.length" data-testid="shipping-workflow-download-selected" @click="downloadSelectedBatchArtifacts">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadSelected') }}</button>
@@ -65,12 +65,12 @@ describe('shipping order review workbench viewport layout contract', () => {
expect(share1440).toBeGreaterThanOrEqual(0.62);
});
it('keeps four lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
it('keeps five lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
const lifecycleNavigation = readFileSync(lifecycleNavigationPath, 'utf8');
const reviewWorkbench = readFileSync(reviewWorkbenchPath, 'utf8');
// 关键断言:接收解析为第四阶段;必须断言真实导航组件,不能只验证 spec 内常量。
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-4"');
// 关键断言:导航真实渲染五个业务阶段,不能只验证 spec 内常量。
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-5"');
// sidebar/sidebar_search 是唯一允许预留 16rem 的模式;tabs/hidden/narrow 均落入 contents。
expect(reviewWorkbench).toMatch(/reviewDocumentNavigationMode\.value === 'sidebar'\s*\|\|\s*reviewDocumentNavigationMode\.value === 'sidebar_search'/);
expect(reviewWorkbench).toMatch(/:class="reviewDocumentNavigationUsesSidebar\s*\? 'grid gap-2 lg:grid-cols-\[16rem_minmax\(0,1fr\)\] lg:items-start lg:gap-3'\s*:\s*'contents'"/);
@@ -669,6 +669,51 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.activeCase.value?.case_no).toBe('CASE-B');
});
it('keeps the latest Run and Case when an older load response arrives last', async () => {
// 关键断言:重识别跳转新版本后,旧 Run 的迟到响应不得覆盖新版工作面。
let resolveOldRun: ((value: Record<string, unknown>) => void) | null = null;
api.getRun.mockImplementation((runNo: string) => (runNo === 'RUN-OLD'
? new Promise<Record<string, unknown>>((resolve) => { resolveOldRun = resolve; })
: Promise.resolve({
run_no: runNo,
summary: {},
items: [{ case_no: 'CASE-NEW', document_id: 2, status: 'draft', issue_count: 0 }],
})));
api.getQueue.mockImplementation((runNo: string) => Promise.resolve({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: runNo === 'RUN-OLD' ? 'CASE-OLD' : 'CASE-NEW',
document_id: runNo === 'RUN-OLD' ? 1 : 2,
source_run_no: runNo,
status: 'draft', issue_count: 0, available_actions: [],
}],
}));
api.getCase.mockImplementation((caseNo: string) => Promise.resolve(buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-OLD' ? 'RUN-OLD' : 'RUN-NEW',
document: {
id: caseNo === 'CASE-OLD' ? 1 : 2,
file_name: caseNo === 'CASE-OLD' ? 'old.pdf' : 'new.pdf',
},
})));
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
const olderLoad = review.load('RUN-OLD', 'CASE-OLD');
await Promise.resolve();
await review.load('RUN-NEW', 'CASE-NEW');
resolveOldRun?.({
run_no: 'RUN-OLD',
summary: {},
items: [{ case_no: 'CASE-OLD', document_id: 1, status: 'superseded', issue_count: 0 }],
});
await olderLoad;
expect(review.reviewRun.value?.run_no).toBe('RUN-NEW');
expect(review.activeCase.value?.case_no).toBe('CASE-NEW');
});
it('blocks confirm when build eligibility cannot build', async () => {
const review = useShippingOrderReview();
@@ -654,21 +654,34 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
/**
* ???? WorkItem ???????????????????
*/
const refreshWorkItemContext = async (conversationId?: string, itemNo?: string) => {
const refreshWorkItemContext = async (
conversationId?: string,
itemNo?: string,
options?: { expectedLoadGeneration?: number },
) => {
const isExpectedLoad = () => (
options?.expectedLoadGeneration == null
|| options.expectedLoadGeneration === caseLoadGeneration
);
const conversation = String(conversationId || contextConversationId || '').trim();
if (conversation) contextConversationId = conversation;
if (itemNo) contextItemNo = itemNo;
if (!isExpectedLoad()) return;
versionsLoading.value = true;
try {
reviewProgressContext.value = await resolveWorkItem(conversation, {
const context = await resolveWorkItem(conversation, {
itemNo: contextItemNo || undefined,
caseNo: activeCase.value?.case_no,
});
if (!isExpectedLoad()) return;
reviewProgressContext.value = context;
versions.value = [];
} catch {
if (!isExpectedLoad()) return;
reviewProgressContext.value = null;
versions.value = [];
} finally {
if (!isExpectedLoad()) return;
versionsLoading.value = false;
refreshStatusMessage();
}
@@ -848,8 +861,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
preferredCaseNo?: string,
options?: { conversationId?: string; itemNo?: string; restoreProgress?: boolean },
) => {
++caseLoadGeneration;
const generation = ++caseLoadGeneration;
++intakeParseRequestGeneration;
requestedCaseNo.value = String(preferredCaseNo || '').trim() || null;
loading.value = true;
loadFailed.value = false;
draftConflict.value = null;
@@ -874,18 +888,25 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
getWorkspaceShippingOrderReviewRun(runNo),
getWorkspaceShippingOrderReviewQueue(runNo),
]);
if (generation !== caseLoadGeneration) return;
reviewRun.value = run;
reviewQueue.value = queue;
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
if (generation !== caseLoadGeneration) return;
applyCaseSnapshot(caseSnapshot);
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
const caseEvidence = caseNo ? await getWorkspaceShippingOrderReviewEvidence(caseNo) : null;
if (generation !== caseLoadGeneration) return;
evidence.value = caseEvidence?.items || [];
// [STEP] ??????? PDF??????????????????????
clearPreview();
await refreshWorkItemContext(contextConversationId, contextItemNo);
await refreshWorkItemContext(contextConversationId, contextItemNo, {
expectedLoadGeneration: generation,
});
// refreshWorkItemContext ????? ref???????? ref????? load ???????????
} catch {
if (generation !== caseLoadGeneration) return;
loadFailed.value = true;
reviewRun.value = null;
activeCase.value = null;
@@ -894,6 +915,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
versions.value = [];
statusMessage.value = null;
} finally {
if (generation !== caseLoadGeneration) return;
loading.value = false;
}
};
@@ -1235,7 +1235,9 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
}],
waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
},
four_stage_nodes: [{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }],
lifecycle_nodes: [{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }],
// 兼容字段故意给出不同值,验证适配层优先消费 lifecycle_nodes。
four_stage_nodes: [{ code: 'upload_complete', label_key: 'shipping.stage.complete', status: 'passed' }],
output_artifacts: [{ order_task_no: 'OT-API-1', filename: 'shipping.xlsx', type: 'excel', status: 'ready', action: { code: 'download_excel', enabled: true } }],
} as unknown as ConversationProcessingProjection;
@@ -1247,9 +1249,10 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
expect(eml.uiState?.primary_action?.i18nKey).toBe('shipping.retry');
expect(eml.aggregateChildren?.[0]?.uiState?.primary_action?.code).toBe('retry');
expect(eml.aggregateChildren?.[0]?.sourceSummary.filename).toBe('a.pdf');
// 批次统计、四阶段与产物均是后端事实,适配时不得从附件重算或丢失。
// 批次统计、五阶段与产物均是后端事实,适配时不得从附件重算或丢失。
expect(normalized.summary.total_files).toBe(7);
expect(normalized.four_stage_nodes).toEqual([{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }]);
expect(normalized.lifecycle_nodes).toEqual([{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }]);
expect(normalized.four_stage_nodes).toEqual([{ code: 'upload_complete', label_key: 'shipping.stage.complete', status: 'passed' }]);
expect(normalized.output_artifacts?.[0]?.action.enabled).toBe(true);
});
@@ -946,7 +946,7 @@ export function resolveConversationProcessingFromUnified(
stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
// [AUTHORITY] conversation_processing.status_groups 与 four_stage_nodes / ui_state
// [AUTHORITY] conversation_processing.status_groups 与 lifecycle_nodes / ui_state
// 同属后端一次裁决。即使顶层 work_items 非空,也不得前端二次聚合或用旧快照覆盖。
if (embedded && typeof embedded === 'object' && embedded.status_groups) {
return normalizeConversationProcessingProjection(embedded);
@@ -1035,11 +1035,11 @@ export function normalizeConversationProcessingProjection(
: null)
),
targetLifecycleStage: (
['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(
['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
String(rawAction.targetLifecycleStage),
)
? rawAction.targetLifecycleStage
: (['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(
: (['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
String(rawAction.target_lifecycle_stage),
)
? rawAction.target_lifecycle_stage
@@ -1192,7 +1192,8 @@ export function normalizeConversationProcessingProjection(
completed,
history,
status_groups: normalizedGroups || projection.status_groups,
four_stage_nodes: projection.four_stage_nodes || [],
lifecycle_nodes: projection.lifecycle_nodes || projection.four_stage_nodes || [],
four_stage_nodes: projection.four_stage_nodes || projection.lifecycle_nodes || [],
unclassified_summary: projection.unclassified_summary || { count: 0 },
ui_state: projection.ui_state || undefined,
output_artifacts: projection.output_artifacts || [],
@@ -1,6 +1,6 @@
/**
* features/chat/shipping/shippingStepper.spec.ts
* 用途:验证发货通知四阶段 Stepper 只消费后端 UI State 投影。
* 用途:验证发货通知五阶段 Stepper 只消费后端 UI State 投影。
* 依赖:shippingStepper 纯函数、vitest。
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
*/
@@ -12,19 +12,20 @@ import {
} from './shippingStepper';
describe('shippingStepper', () => {
it('renders exactly four stages from backend ui_state', () => {
it('renders exactly five stages from backend ui_state', () => {
const steps = resolveShippingWorkflowSteps({
ui_state: {
steps: [
{ id: 'shipping-stage-1', code: 'intake_parse', label: '接收解析', status: 'completed' },
{ id: 'shipping-stage-2', code: 'order_review', label: '订单复核', status: 'completed' },
{ id: 'shipping-stage-3', code: 'fulfillment_prep', label: '通知准备', status: 'blocked' },
{ id: 'shipping-stage-4', code: 'upload_complete', label: '通知完成', status: 'pending' },
{ id: 'shipping-stage-4', code: 'freight_upload', label: '货代上传', status: 'pending' },
{ id: 'shipping-stage-5', code: 'upload_complete', label: '通知完成', status: 'pending' },
],
},
});
expect(steps).toHaveLength(4);
expect(steps).toHaveLength(5);
expect(steps[2]?.status).toBe('blocked');
});
@@ -33,17 +34,18 @@ describe('shippingStepper', () => {
expect(normalizeShippingWorkflowSteps(null)).toEqual([]);
});
it('maps technical processing stages into the four business stages', () => {
it('maps technical processing stages into the five business stages', () => {
const base = normalizeShippingWorkflowSteps([
{ code: 'intake_parse', status: 'pending' },
{ code: 'order_review', status: 'pending' },
{ code: 'fulfillment_prep', status: 'pending' },
{ code: 'freight_upload', status: 'pending' },
{ code: 'upload_complete', status: 'pending' },
]);
const steps = applyShippingProcessingStageToSteps(base, {
stage: 'inventory_matching',
status: 'running',
});
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending']);
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending', 'pending']);
});
});
@@ -1,8 +1,8 @@
/**
* features/chat/shipping/shippingStepper.ts
* 用途:基于后端 ui_state 投影渲染四阶段业务 Stepper。
* 用途:基于后端 ui_state 投影渲染五阶段业务 Stepper。
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
* 逻辑:只消费后端 ui_state.steps 四阶段投影;缺失投影时 fail-closed。
* 逻辑:只消费后端 ui_state.steps 五阶段投影;缺失投影时 fail-closed。
*/
import {
FULFILLMENT_PROGRESS_NODES,
@@ -32,6 +32,7 @@ export const SHIPPING_WORKFLOW_STEP_LABELS = [
'chat.shippingNoticeUi.stage.intakeParse',
'chat.shippingNoticeUi.stage.orderReview',
'chat.shippingNoticeUi.stage.fulfillmentPrep',
'chat.shippingNoticeUi.stage.freightUpload',
'chat.shippingNoticeUi.stage.uploadComplete',
] as const;
@@ -90,7 +91,7 @@ const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
inventory_matching: 2,
excel_generating: 2,
freight_uploading: 3,
completed: 3,
completed: 4,
};
/**
@@ -163,7 +163,7 @@ export interface ShippingProcessingPrimaryAction {
}
/** 订单生命周期工作台的后端目标阶段。 */
export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
/** 文件级生命周期入口;状态、目标均由后端裁决。 */
export interface ShippingProcessingLifecycleEntry {
@@ -678,9 +678,23 @@ export interface ConversationProcessingProjection {
cancelled: ConversationProcessingUserTask[];
archived: ConversationProcessingUserTask[];
};
/** 会话批次主进度;后端已将技术阶段折叠为四个业务节点。 */
/** 会话批次主进度;后端已将技术阶段折叠为五个业务节点。 */
lifecycle_nodes?: Array<{
code: LifecycleWorkbenchStage;
label_key: string;
status: 'passed' | 'running' | 'blocked' | 'pending';
summary?: {
total: number;
completed: number;
needs_action: number;
processing: number;
failed: number;
blocking_reason?: ShippingProcessingBlockingReason | null;
};
}>;
/** @deprecated 兼容旧客户端;当前值同 lifecycle_nodes,已包含五阶段。 */
four_stage_nodes?: Array<{
code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
code: LifecycleWorkbenchStage;
label_key: string;
status: 'passed' | 'running' | 'blocked' | 'pending';
/** 批次阶段摘要由后端按完整叶子工作项裁决,禁止页面从筛选结果反算。 */
@@ -693,7 +707,7 @@ export interface ConversationProcessingProjection {
blocking_reason?: ShippingProcessingBlockingReason | null;
};
}>;
/** 后端无法归类到四阶段的业务文件数量;页面只提示,不擅自归类。 */
/** 后端无法归类到五阶段的业务文件数量;页面只提示,不擅自归类。 */
unclassified_summary?: { count: number };
/** 批次级用户态:状态、问题与可操作动作必须来自同一次后端裁决。 */
ui_state?: ConversationProcessingUiState;
@@ -711,8 +725,8 @@ export interface ConversationProcessingProjection {
export interface ConversationProcessingUiState {
status: ShippingUserProcessingStatus;
stage: string;
/** 后端从技术节点裁决的四阶段业务编码,批次中心与工作台共同消费。 */
lifecycleStage?: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
/** 后端从技术节点裁决的五阶段业务编码,批次中心与工作台共同消费。 */
lifecycleStage?: LifecycleWorkbenchStage;
lifecycleEntries?: ShippingProcessingLifecycleEntry[];
blocking_reason: ShippingProcessingBlockingReason | null;
primary_action: ShippingProcessingPrimaryAction | null;
@@ -1445,7 +1459,7 @@ export interface ShippingTaskUiState {
primary?: ShippingUnifiedAction | null;
secondary?: ShippingUnifiedAction[];
};
/** 四阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */
/** 五阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */
stage_context?: {
preparation?: {
status?: 'processing' | 'blocked' | 'ready' | string;
@@ -1483,6 +1497,14 @@ export interface ShippingTaskUiState {
} | null;
upload?: {
outcome?: 'not_started' | 'running' | 'awaiting_manual' | 'succeeded' | 'failed' | 'unknown' | string;
/** 仅 upload_complete 工作面读取的、后端验证过的成功上传事实。 */
succeeded_attempt?: {
id?: number | null;
status?: string | null;
mode?: string | null;
freight_ref_no?: string | null;
finished_at?: string | null;
} | null;
latest_attempt?: {
id?: number | null;
status?: string | null;
@@ -2255,6 +2277,8 @@ export interface ShippingOrderReviewCaseSummary {
draft_version?: number | null;
issue_count: number;
available_actions: string[];
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
intake_no?: string | null;
source_run_no?: string | null;
}
@@ -2435,7 +2459,8 @@ export interface ShippingOrderReviewBuildEligibilityIssue {
}
export interface ShippingOrderReviewBuildEligibility {
can_build: boolean;
/** 未执行校验时为 null;只有 validated/needs_review 才返回布尔结论。 */
can_build: boolean | null;
can_auto_create?: boolean;
status: string;
gates?: Record<string, boolean>;
@@ -2632,6 +2657,8 @@ export interface ShippingOrderReviewCase {
build_eligibility?: ShippingOrderReviewBuildEligibility;
} | null;
available_actions: string[];
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
intake_no?: string | null;
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
formal_editable_field_ids?: string[];
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
@@ -2936,6 +2963,14 @@ export interface ShippingOrderReviewProfileMatchCandidate {
hard_match?: boolean | null;
reason_codes?: string[];
missing_required_anchor_ids?: string[];
/** 管理员技术详情:共同 matcher 已确认的受限平移,不含正文或完整坐标。 */
coordinate_transform?: {
status: 'applied' | 'unavailable' | 'rejected' | string;
translate_x?: number | null;
translate_y?: number | null;
anchor_ids?: string[];
reason_codes?: string[];
} | null;
}
/** 建单前文档模板匹配只读投影。 */
@@ -21,6 +21,7 @@ import {
retryWorkspaceShippingOrderStpAutoCreate,
retryWorkspaceShippingTask,
retryWorkspaceShippingTaskLine,
retryShippingNoticeIntake,
} from '@/features/chat/api/shipping.api';
const { downloadWorkspaceShippingLineInventoryFileMock } = vi.hoisted(() => ({
@@ -111,6 +112,7 @@ const shippingProcessingProjection = ref<Record<string, any> | null>(null);
/** 正式任务投影的请求中状态;用于覆盖 Case 先到、Projection 后到的过渡窗口。 */
const shippingProcessingLoading = ref(false);
const intakeParseContext = ref<Record<string, any> | null>(null);
const requestedCaseNo = ref<string | null>(null);
/** 每个用例必须从独立的 Case 图快照开始,避免嵌套 schema/draft 被浅拷贝污染。 */
function createActiveCaseFixture() {
@@ -177,6 +179,7 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
job_id: 901,
case: null,
}),
retryShippingNoticeIntake: vi.fn().mockResolvedValue({ intake_no: 'SNI-RETRY-1', parse_status: 'queued' }),
getWorkspaceShippingTask: vi.fn().mockResolvedValue({
task_no: 'SN-MOCK',
status: 'created',
@@ -229,7 +232,7 @@ function createReviewComposableMock() {
loadFailed: ref(false),
caseSwitchLoading: ref(false),
caseSwitchFailed: ref(false),
requestedCaseNo: ref(null),
requestedCaseNo,
saving: ref(false),
validationInProgress: ref(false),
saveFailed: ref(false),
@@ -587,6 +590,7 @@ async function mountView(query: Record<string, string> = {}) {
intake_parse: '接收解析',
order_review: '订单复核',
fulfillment_prep: '通知准备',
freight_upload: '货代上传',
upload_complete: '通知完成',
},
prepare: {
@@ -665,6 +669,7 @@ async function mountView(query: Record<string, string> = {}) {
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
function resetActiveCaseFixture() {
activeCase.value = createActiveCaseFixture();
requestedCaseNo.value = null;
shippingProcessingProjection.value = null;
shippingProcessingLoading.value = false;
intakeParseContext.value = null;
@@ -679,6 +684,20 @@ describe('ShippingOrderReviewView layout phase 1', () => {
reviewProgressContext.value = null;
});
it('keeps the requested replacement Case when the loaded Run updates the URL', async () => {
// 关键断言:新版 Run 先到而旧 URL Case 仍在时,不能拼出 RUN-NEW + CASE-OLD。
const wrapper = await mountView({ case_no: 'CASE-OLD' });
requestedCaseNo.value = 'CASE-NEW';
reviewRun.value = {
...reviewRun.value,
run_no: 'RUN-NEW',
};
await flushPromises();
expect((wrapper.vm as any).$route.query.run_no).toBe('RUN-NEW');
expect((wrapper.vm as any).$route.query.case_no).toBe('CASE-NEW');
});
it('uses the current-task card as the only Gate action entry for every formal-OT Gate', async () => {
activeCase.value = {
...activeCase.value,
@@ -1031,7 +1050,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
const shell = wrapper.get('[data-testid="review-workbench-ot-shell"]');
const navigation = wrapper.get('[data-testid="review-document-navigation"]');
// 2–4 文件不浪费一列宽度,但必须在四阶段前完成文件选择。
// 2–4 文件不浪费一列宽度,但必须在五阶段前完成文件选择。
expect(navigation.attributes('data-nav-mode')).toBe('tabs');
expect(shell.classes()).toContain('contents');
expect(wrapper.html().indexOf('review-document-navigation'))
@@ -1082,6 +1101,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
@@ -1115,7 +1135,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
const wrapper = await mountView({ lifecycle_stage: 'order_review' });
await flushPromises();
for (const code of ['order_review', 'fulfillment_prep', 'upload_complete']) {
for (const code of ['order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete']) {
const stage = wrapper.get(`[data-testid="review-lifecycle-stage-${code}"]`);
expect(stage.findAll('button')[1].attributes('disabled')).toBeDefined();
}
@@ -1136,6 +1156,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
@@ -1151,6 +1172,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
@@ -1178,6 +1200,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
@@ -1193,6 +1216,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
@@ -1236,6 +1260,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
@@ -1322,6 +1347,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
@@ -1506,6 +1532,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
blocking_reason: null,
@@ -1587,7 +1614,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('3');
expect(wrapper.find('[data-testid="review-fulfillment-prep-workspace"]').exists()).toBe(true);
expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成');
// 通知准备工作区必须属于四阶段导航的下方主区,不能仍停留在导航之前的状态摘要区。
// 通知准备工作区必须属于五阶段导航的下方主区,不能仍停留在导航之前的状态摘要区。
expect(wrapper.html().indexOf('review-lifecycle-workbench-header'))
.toBeLessThan(wrapper.html().indexOf('review-fulfillment-prep-workspace'));
});
@@ -1760,6 +1787,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lifecycle_entries: [
{ code: 'order_review', state: 'available', target_surface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', target_surface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', target_surface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', target_surface: 'order_lifecycle_workbench' },
],
},
@@ -1802,7 +1830,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.get('[data-testid="review-footer-actions"]').text()).toContain('保存订单并校验');
});
it('keeps backend-authorized manual upload registration out of the upload main area', async () => {
it('keeps notification completion read-only even when an obsolete manual-upload action arrives', async () => {
const originalQueue = reviewQueue.value;
try {
activeCase.value = {
@@ -1817,6 +1845,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'current', targetSurface: 'order_lifecycle_workbench' },
],
}],
@@ -1836,7 +1865,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
target_surface: 'upload_complete',
target_surface: 'freight_upload',
target_anchor: 'manual_upload',
requires_confirmation: false,
},
@@ -1847,8 +1876,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
} as any);
const withAuthorization = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
// Gate 写操作只在右侧“当前任务”显示;主区只保留上传事实与审计摘要。
// 完成面必须屏蔽迟到的 Gate 写操作;主区只保留验证成功事实与审计摘要。
expect(withAuthorization.find('[data-testid="review-lifecycle-upload-manual"]').exists()).toBe(false);
expect(withAuthorization.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
// 正式动作直接提交当前 Gate,不允许无界面 TaskTodoPanel 作为隐藏执行器。
expect((withAuthorization.vm as { formalTodoPanelRef?: unknown }).formalTodoPanelRef).toBeUndefined();
} finally {
@@ -1856,7 +1886,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
}
});
it('opens the page-level evidence dialog when the authorized current-task action is manual upload', async () => {
it('opens the page-level evidence dialog from freight upload when the current-task action is manual upload', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-DIALOG', confirmed_task_id: 19, has_formal_ot: true,
@@ -1869,7 +1899,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
target_surface: 'upload_complete', target_anchor: 'manual_upload',
target_surface: 'freight_upload', target_anchor: 'manual_upload',
requires_confirmation: false,
},
secondary: [],
@@ -1878,7 +1908,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises();
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
await flushPromises();
@@ -1886,7 +1916,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(true);
});
it('renders the authorized Excel download in every upload-complete order line instead of the task rail', async () => {
it('renders the authorized Excel download in every freight-upload order line instead of the task rail', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-DOWNLOAD-DISPATCH', confirmed_task_id: 20, has_formal_ot: true,
@@ -1926,26 +1956,26 @@ describe('ShippingOrderReviewView layout phase 1', () => {
secondary: [{
code: 'download_excel', label: '下载 Excel', kind: 'view', enabled: true,
dispatch: 'view', ui_handler: 'excel_download',
target_surface: 'upload_complete', target_anchor: 'excel_artifact',
target_surface: 'freight_upload', target_anchor: 'excel_artifact',
requires_confirmation: false,
}],
},
lifecycle_stage: 'upload_complete',
lifecycle_entries: [{ code: 'upload_complete', state: 'current' }],
lifecycle_stage: 'freight_upload',
lifecycle_entries: [{ code: 'freight_upload', state: 'current' }],
process_gate: { execution_no: 'EXEC-DOWNLOAD-DISPATCH' }, summary: {}, steps: [],
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises();
const rows = wrapper.findAll('[data-testid="review-upload-complete-line"]');
const rows = wrapper.findAll('[data-testid="review-freight-upload-line"]');
expect(rows).toHaveLength(2);
expect(rows[0].text()).toContain('PN-ONE');
expect(rows[1].text()).toContain('PN-TWO');
expect(wrapper.find('[data-testid="review-current-task-recovery-download_excel"]').exists()).toBe(false);
await wrapper.get('[data-testid="review-upload-complete-download-LINE-1"]').trigger('click');
await wrapper.get('[data-testid="review-freight-upload-download-LINE-1"]').trigger('click');
await flushPromises();
// 下载是 Artifact 只读操作;订单行不按 PO 聚合,且不得伪装成 Gate mutation。
@@ -1969,6 +1999,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
@@ -2103,6 +2134,104 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="review-lifecycle-upload-download"]').exists()).toBe(false);
});
it('retries the server-authorized failed Intake from the current lifecycle card and refreshes projections', async () => {
const originalQueue = reviewQueue.value;
try {
activeCase.value = {
...activeCase.value,
available_actions: ['retry_parse'],
intake_no: 'SNI-RETRY-1',
};
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'intake_parse',
lifecycle_entries: [],
intake_parse_authorized: true,
available_actions: ['retry_parse'],
intake_no: 'SNI-RETRY-1',
}],
};
const wrapper = await mountView({ lifecycle_stage: 'intake_parse' });
// 关键断言:已发送 EML 的恢复从当前阶段卡执行,并且使用服务端下发的原 SNI。
await wrapper.get('[data-testid="review-lifecycle-stage-retry-parse"]').trigger('click');
await flushPromises();
expect(retryShippingNoticeIntake).toHaveBeenCalledWith('SNI-RETRY-1');
expect(reloadLatestDraftMock).toHaveBeenCalled();
expect(refreshShippingProcessingMock).toHaveBeenCalled();
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not show intake retry while parsing or after cancellation', async () => {
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0], lifecycle_stage: 'intake_parse', lifecycle_entries: [], intake_parse_authorized: true,
}],
};
for (const status of ['parsing', 'cancelled']) {
activeCase.value = { ...activeCase.value, status, available_actions: [], intake_no: null };
const wrapper = await mountView({ lifecycle_stage: 'intake_parse' });
// 关键断言:运行中等待超时回收,取消态不可复活,均无 retry_parse 入口。
expect(wrapper.find('[data-testid="review-lifecycle-stage-retry-parse"]').exists()).toBe(false);
}
} finally {
reviewQueue.value = originalQueue;
}
});
it('renders completion evidence only from the verified succeeded attempt', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-VERIFIED-EVIDENCE', confirmed_task_id: 22, has_formal_ot: true,
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-VERIFIED-EVIDENCE', status: 'completed', upload_status: 'uploaded', lines: [], events: [],
ui_state: {
lifecycle_stage: 'upload_complete',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available' },
{ code: 'order_review', state: 'available' },
{ code: 'fulfillment_prep', state: 'available' },
{ code: 'freight_upload', state: 'available' },
{ code: 'upload_complete', state: 'current' },
],
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
},
secondary: [],
},
stage_context: {
upload: {
latest_attempt: { status: 'failed', mode: 'rpa', freight_ref_no: 'LATEST-FAILED' },
succeeded_attempt: { status: 'succeeded', mode: 'manual', freight_ref_no: 'VERIFIED-REF' },
},
},
summary: {}, steps: [],
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
const evidence = wrapper.get('[data-testid="review-lifecycle-upload-complete"]');
expect(evidence.text()).toContain('VERIFIED-REF');
expect(evidence.text()).toContain('succeeded');
expect(evidence.text()).not.toContain('LATEST-FAILED');
expect(evidence.text()).not.toContain('failed');
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
});
it('renders empty optional schema fields as editable line columns', async () => {
const wrapper = await mountView();
const inputs = wrapper.findAll('[data-testid="review-line-field-input"]');
@@ -1,6 +1,6 @@
<!--
features/chat/views/ShippingOrderReviewView.vue
用途:建单前/正式任务「订单生命周期工作台」(主编辑区 + 四阶段导航 + 工作台侧栏 + workbenchMode)。
用途:建单前/正式任务「订单生命周期工作台」(主编辑区 + 五阶段导航 + 工作台侧栏 + workbenchMode)。
依赖:路由参数、useShippingOrderReview、ReviewWorkbenchHeader/Footer、ReviewDocumentNavigation、
ReviewProcessDetailDrawer、ReviewUnsavedSwitchDialog、
ReviewWorkbenchModeToggle、ReviewDocumentEvidenceDrawer、ReviewVersionHistoryDrawer、
@@ -31,6 +31,7 @@ import {
retryWorkspaceShippingOrderStpAutoCreate,
retryWorkspaceShippingTask,
retryWorkspaceShippingTaskLine,
retryShippingNoticeIntake,
decideWorkspaceShippingOrderReviewLineFulfillment,
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
} from '../api/shipping.api';
@@ -217,6 +218,7 @@ const LIFECYCLE_STAGE_CODES: ReviewLifecycleStageCode[] = [
'intake_parse',
'order_review',
'fulfillment_prep',
'freight_upload',
'upload_complete',
];
@@ -322,7 +324,40 @@ const isLifecycleIntakeParse = computed(() => (
lifecycleActiveStageCode.value === 'intake_parse' && intakeParseContextAuthorized.value
));
const isLifecycleFulfillmentPrep = computed(() => lifecycleActiveStageCode.value === 'fulfillment_prep');
const isLifecycleFreightUpload = computed(() => lifecycleActiveStageCode.value === 'freight_upload');
const isLifecycleUploadComplete = computed(() => lifecycleActiveStageCode.value === 'upload_complete');
/** 当前阶段重试只取 Case 的服务端授权,不从输入框附件卡或本地状态推断。 */
const intakeParseRetryAvailable = computed(() => (
isLifecycleIntakeParse.value
&& (activeCase.value?.available_actions || []).includes('retry_parse')
&& Boolean(String(activeCase.value?.intake_no || '').trim())
));
const intakeParseRetrying = ref(false);
/**
* 对已发送文件重投原 Intake 的解析任务。
* 成功后同步 Case、统一处理投影并重新读取 Intake 上下文;后端状态会转为 queued,
* 原有 polling 会继续推进,运行中不再展示 retry_parse。
*/
async function retryCurrentIntakeParse(): Promise<void> {
const intakeNo = String(activeCase.value?.intake_no || '').trim();
if (!intakeParseRetryAvailable.value || !intakeNo || intakeParseRetrying.value) return;
intakeParseRetrying.value = true;
try {
await retryShippingNoticeIntake(intakeNo);
await Promise.all([
reloadLatestDraft(),
refreshShippingProcessing(),
activeCase.value?.case_no
? ensureIntakeParseContextLoaded(activeCase.value.case_no)
: Promise.resolve(false),
]);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingNoticeRetryParse'));
} finally {
intakeParseRetrying.value = false;
}
}
/**
* 只切换前端工作面并同步可分享深链;禁止在导航点击中修改任何订单生命周期字段。
@@ -508,10 +543,10 @@ const formalTaskActions = computed(() => {
});
/**
* 通知完成明细的只读 Excel 动作。
* 货代上传工作面的 Excel 下载动作。
*
* Artifact 下载由后端 ui_state.actions 授权;它属于订单行结果表的行内操作,
* 不与右侧当前任务的 Gate 动作混排。每个行入口下载同一正式任务已校验的 Excel。
* Artifact 下载由后端 ui_state.actions 授权;它属于货代上传工作面,
* 不与只读成功证据或右侧当前任务 Gate 动作混排。
*/
const uploadCompletionExcelDownloadAction = computed(() => formalTaskActions.value.find((action) => (
action.enabled
@@ -573,6 +608,22 @@ const currentTaskRecoveryActions = computed(() => {
})).filter((action) => action.code)
});
/**
* 已验证的通知完成面只展示成功证据,不能因迟到或历史 Gate 动作再次提供写入口。
* 核心逻辑:货代上传工作面仍原样消费后端授权动作;完成面只把动作降为只读,
* 不修改服务端授权,也不根据客户端状态推导新的操作。
* @returns 当前工作面允许交给 ReviewCurrentProcessingCard 展示的动作。
*/
const visibleCurrentTaskPrimaryAction = computed(() => (
isLifecycleUploadComplete.value ? null : currentTaskPrimaryAction.value
));
const visibleCurrentTaskRecoveryActions = computed(() => (
isLifecycleUploadComplete.value ? [] : currentTaskRecoveryActions.value
));
const visibleCurrentTaskRetryable = computed(() => (
isLifecycleUploadComplete.value ? false : currentTaskRetryable.value
));
/** 管理员诊断:后端 technical_progress / automation.technical 仅 admin 投影。 */
const showAdminTaskMissingDiagnosis = computed(() => (
Boolean(displayCase.value?.task_missing)
@@ -1898,7 +1949,7 @@ const showWorkbenchGrid = computed(
const headerSchemaFields = computed(() => (displayCase.value?.schema.fields || []).filter((field) => field.scope === 'header'));
const lineSchemaFields = computed(() => (displayCase.value?.schema.fields || []).filter((field) => field.scope === 'line'));
/** 通知完成仅展示订单行的核心识别字段,字段值始终按当前行的 line_key 读取。 */
/** 货代上传仅展示订单行的核心识别字段,字段值始终按当前行的 line_key 读取。 */
const uploadCompletionLineFields = computed(() => {
const codes = ['line_no', 'part_number', 'quantity'];
return codes.map((code) => lineSchemaFields.value.find((field) => field.field_code === code))
@@ -2106,7 +2157,7 @@ async function retryFormalPreparationLine(lineKey: string) {
}
/**
* 人工上传登记是后端 Gate 的受控写动作;仅进入「通知完成」工作面不构成授权。
* 人工上传登记是后端 Gate 的受控写动作;仅进入「货代上传」工作面不构成授权。
* 任务详情与批次中心共用 ui_state.actions,避免页面按上传状态或生命周期自行放行。
*/
const manualUploadRegistrationAuthorized = computed(() => {
@@ -3308,6 +3359,7 @@ watch(
if (resolvedRunNo && resolvedRunNo !== runNo.value) {
const resolvedCaseNo = String(
pendingCrossRunCaseNo.value
|| requestedCaseNo.value
|| route.query.case_no
|| route.query.case
|| activeCase.value?.case_no
@@ -3464,8 +3516,11 @@ watch(
<ReviewLifecycleStageNavigation
:stages="lifecycleStageItems"
:active-code="lifecycleActiveStageCode"
:available-actions="activeCase?.available_actions || []"
:retrying="intakeParseRetrying"
@select="(code) => { void selectLifecycleStage(code); }"
@open-detail="() => { processDetailOpen = true; }"
@retry-parse="() => void retryCurrentIntakeParse()"
/>
</div>
</div>
@@ -3543,11 +3598,11 @@ watch(
:automation="displayCase?.automation"
:show-retry="showObjectRetryOnRail"
:user-status="currentTaskUserStatus"
:retryable="currentTaskRetryable"
:retryable="visibleCurrentTaskRetryable"
:blocking-reason="currentTaskBlockingReason"
:gate-status="currentTaskGateStatus"
:primary-action="currentTaskPrimaryAction"
:recovery-actions="currentTaskRecoveryActions"
:primary-action="visibleCurrentTaskPrimaryAction"
:recovery-actions="visibleCurrentTaskRecoveryActions"
:retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading"
:loading="caseContentSkeleton || formalTaskProjectionPending"
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"
@@ -3642,14 +3697,14 @@ watch(
</section>
<section
v-if="hasCreatedShippingTask && formalTaskDetail && isLifecycleUploadComplete"
v-if="hasCreatedShippingTask && formalTaskDetail && isLifecycleFreightUpload"
class="rounded-xl border border-default bg-surface p-3"
data-testid="review-lifecycle-upload-complete"
data-testid="review-lifecycle-freight-upload"
>
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.upload.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.upload.subtitle') }}</p>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.subtitle') }}</p>
</div>
<span class="rounded-full bg-surface-muted px-2 py-1 text-xs text-secondary">{{ formalTaskDetail.upload_status || '-' }}</span>
</div>
@@ -3658,7 +3713,7 @@ watch(
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt" class="mt-1">{{ t('chat.shippingOrderReview.lifecycle.upload.attempt', { status: formalTaskDetail.ui_state.stage_context.upload.latest_attempt.status || '-', mode: formalTaskDetail.ui_state.stage_context.upload.latest_attempt.mode || '-' }) }}</p>
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt?.error_code" class="mt-1 text-rose-700 dark:text-rose-300">{{ formalTaskDetail.ui_state.stage_context.upload.latest_attempt.error_code }}</p>
</div>
<div v-if="displayDraftLines.length" class="mt-3 overflow-x-auto" data-testid="review-upload-complete-lines">
<div v-if="displayDraftLines.length" class="mt-3 overflow-x-auto" data-testid="review-freight-upload-lines">
<table class="min-w-full text-left text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-secondary">
<tr>
@@ -3673,7 +3728,7 @@ watch(
v-for="line in displayDraftLines"
:key="String(line.line_key)"
class="border-b border-default last:border-0"
data-testid="review-upload-complete-line"
data-testid="review-freight-upload-line"
>
<td class="px-3 py-2 font-medium text-primary">{{ processDetailPoNumber || '—' }}</td>
<td v-for="field in uploadCompletionLineFields" :key="field.field_id" class="px-3 py-2">{{ lineFieldDisplayValue(line, field) || '—' }}</td>
@@ -3683,7 +3738,7 @@ watch(
v-if="uploadCompletionExcelDownloadAction"
type="button"
class="rounded border border-brand-200 px-2 py-1 font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50 dark:border-brand-800 dark:text-brand-200 dark:hover:bg-brand-950/40"
:data-testid="`review-upload-complete-download-${line.line_key}`"
:data-testid="`review-freight-upload-download-${line.line_key}`"
:disabled="saving"
@click="void executeFormalTaskAction(uploadCompletionExcelDownloadAction, {})"
>
@@ -3696,6 +3751,19 @@ watch(
</div>
</section>
<section
v-if="hasCreatedShippingTask && formalTaskDetail && isLifecycleUploadComplete"
class="rounded-xl border border-emerald-200 bg-emerald-50/40 p-3 dark:border-emerald-900 dark:bg-emerald-950/20"
data-testid="review-lifecycle-upload-complete"
>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.subtitle') }}</p>
<div class="mt-3 rounded-lg border border-emerald-200 bg-surface/70 p-3 text-xs text-secondary dark:border-emerald-900">
<p>{{ t('chat.shippingOrderReview.lifecycle.upload.receipt', { value: formalTaskDetail.ui_state?.stage_context?.upload?.succeeded_attempt?.freight_ref_no || '-' }) }}</p>
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.succeeded_attempt" class="mt-1">{{ t('chat.shippingOrderReview.lifecycle.upload.attempt', { status: formalTaskDetail.ui_state.stage_context.upload.succeeded_attempt.status || '-', mode: formalTaskDetail.ui_state.stage_context.upload.succeeded_attempt.mode || '-' }) }}</p>
</div>
</section>
<ReviewIntakeParsePanel
v-if="isLifecycleIntakeParse"
:context="intakeParseContext"
@@ -4138,11 +4206,11 @@ watch(
:has-formal-ot="shippingProcessingProjection?.hasFormalOt ?? hasFormalOt"
:shipping-notice-no="shippingProcessingProjection?.shippingNoticeNo ?? confirmedNoticeTaskNo"
:user-status="currentTaskUserStatus"
:retryable="currentTaskRetryable"
:retryable="visibleCurrentTaskRetryable"
:blocking-reason="currentTaskBlockingReason"
:gate-status="currentTaskGateStatus"
:primary-action="currentTaskPrimaryAction"
:recovery-actions="currentTaskRecoveryActions"
:primary-action="visibleCurrentTaskPrimaryAction"
:recovery-actions="visibleCurrentTaskRecoveryActions"
:retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading"
:loading="caseContentSkeleton || formalTaskProjectionPending"
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"