chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑

This commit is contained in:
hugo committed 2026-08-17 19:56:51 +08:00
1 parent 5ef8329bd8
commit 4ec4e57005
183 files changed
+14653 -3936

No files matched your search

@@ -18,6 +18,8 @@ const i18n = createI18n({
line: '第 {index} 行',
buildEligibility: {
overallResult: '整单结果', canBuildYes: '可建单', canBuildNo: '待处理',
manualBuildLabel: '人工建单', autoBuildLabel: '自动建单',
autoBuildYes: '可自动建单', autoBuildNo: '暂不可自动建单',
manualConfirmOnly: '需人工确认', blockReasons: { unknown: '未知阻断' },
routingStatus: { unknown: '未知' },
},
@@ -40,6 +42,49 @@ const eligibility = {
};
describe('ReviewBuildEligibilityDetailsDrawer', () => {
it('separates manual buildability from automatic creation eligibility', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
open: true,
eligibility: {
can_build: true,
can_auto_create: false,
status: 'ready',
failed_gates: ['field_conflicts_resolved'],
issues: [],
line_projections: [],
},
},
global: { plugins: [i18n] },
});
// 关键断言:抽屉不能只写“可建单”而让自动门禁失败看似矛盾。
expect(wrapper.find('[data-testid="review-eligibility-manual-status"]').text()).toContain('可建单');
expect(wrapper.find('[data-testid="review-eligibility-auto-status"]').text()).toContain('暂不可自动建单');
});
it('does not render an empty diagnostic section when there are no diagnostic facts', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
open: true,
eligibility: {
can_build: true,
can_auto_create: false,
status: 'ready',
issues: [],
failed_gates: [],
assessment: { missing_required_fields: [] },
line_projections: [{ line_key: 'L1', line_index: 0, can_build: true }],
},
fieldConflicts: [],
},
global: { plugins: [i18n] },
});
// 关键断言:没有问题明细时不能留下无内容的边框占位区。
expect(wrapper.findAll('section')).toHaveLength(1);
});
it('lists the exact conflicting field, line, sources and values', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
@@ -134,6 +134,15 @@ const unexplainedBlocked = computed(() => Boolean(
&& !props.eligibility.assessment?.missing_required_fields?.length
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
));
/** 有可解释的诊断事实时才渲染中段,避免通过订单留下空白占位框。 */
const hasDiagnosticDetails = computed(() => Boolean(
props.eligibility?.assessment?.missing_required_fields?.length
|| nonConflictIssues.value.length
|| unexplainedBlocked.value
|| props.fieldConflicts?.length
|| hasFieldConflictIssue.value
));
</script>
<template>
@@ -163,12 +172,27 @@ const unexplainedBlocked = computed(() => Boolean(
: '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"
>
<div class="flex items-center justify-between gap-2">
<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'">
{{ eligibility.can_build
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span>
</span>
</div>
<div class="mt-2 flex flex-wrap items-center justify-between gap-2">
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.autoBuildLabel') }}</span>
<span
class="rounded-full px-2 py-0.5 font-medium"
:class="eligibility.can_auto_create
? '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'"
data-testid="review-eligibility-auto-status"
>
{{ eligibility.can_auto_create
? t('chat.shippingOrderReview.buildEligibility.autoBuildYes')
: t('chat.shippingOrderReview.buildEligibility.autoBuildNo') }}
</span>
</div>
<p v-if="eligibility.can_build && eligibility.can_auto_create === false" class="mt-1">
@@ -183,7 +207,10 @@ const unexplainedBlocked = computed(() => Boolean(
</ul>
</div>
</section>
<section class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40">
<section
v-if="hasDiagnosticDetails"
class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40"
>
<div v-if="eligibility.assessment?.missing_required_fields?.length" class="mt-2">
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.requiredFields') }}</div>
<div class="mt-1 text-rose-700 dark:text-rose-300">
@@ -165,8 +165,8 @@ describe('ReviewBuildEligibilitySummary', () => {
expect(wrapper.text()).not.toContain('can_auto_create');
});
it('hides primary-block under focusBuildability for inventory combo (UI-03)', () => {
// 关键断言:库存阻断由 Gate 卡表达时,资格摘要不得再输出首要阻断标题。
it('keeps primary-block under focusBuildability for inventory combo (UI-03)', () => {
// 关键断言:当前任务卡只承载动作,资格摘要仍保留库存门禁的具体解释。
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
@@ -218,13 +218,14 @@ describe('ReviewBuildEligibilitySummary', () => {
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-build-eligibility-summary"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-exception-nav"]').exists()).toBe(true);
});
it('hides primary-block under focusBuildability for field completeness combo (UI-03)', () => {
// 关键断言:字段阻断组合态下资格卡只保留摘要与异常导航,不输出第二份首要阻断。
it('keeps concrete missing-field diagnostics visible under focusBuildability (UI-03)', () => {
// 关键断言:当前任务卡只承载动作;建单资格卡仍必须给出缺失字段和首要阻断,
// 否则用户无法从泛化 Gate 文案定位订单明细问题。
const wrapper = mount(ReviewBuildEligibilitySummary, {
props: {
eligibility: {
@@ -280,11 +281,13 @@ describe('ReviewBuildEligibilitySummary', () => {
})],
},
});
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(true);
expect(wrapper.text()).toContain('缺失必填:PO');
});
it('hides primary-block when technical_auto_only leaves business gate inactive (UI-03)', () => {
// 关键断言:仅技术 Gate pending 时 focusBuildability=false,资格卡可展示阻断;本测验证开启 focus 时仍唯一。
it('keeps passing eligibility concise when focusBuildability is enabled (UI-03)', () => {
// 关键断言:无阻断时不额外渲染首要阻断;focusBuildability 不影响资格事实展示。
const wrapper = mount(ReviewBuildEligibilitySummary, {
props: {
eligibility: {
@@ -21,8 +21,8 @@ const props = defineProps<{
/** 当前定位异常序号;未定位时为 0。 */
exceptionOrdinal?: number;
/**
* 为 true 时只展示能否建单/自动建单与异常导航,隐藏门禁清单与首要阻断文案,
* 避免与 ProcessGateRecoveryCard 重复表达同一业务阻断。
* 兼容旧调用方的展示偏好。当前任务卡只承载动作,建单门禁仍须完整展示,
* 因此该参数不再隐藏字段级诊断,避免用户只能看到泛化阻断原因。
*/
focusBuildability?: boolean;
}>();
@@ -233,7 +233,7 @@ const gateChecklist = computed(() => {
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
</p>
<ul
v-if="!focusBuildability && gateChecklist.length"
v-if="gateChecklist.length"
class="mt-2 space-y-1 text-xs"
data-testid="review-eligibility-gate-checklist"
>
@@ -285,7 +285,7 @@ const gateChecklist = computed(() => {
<p v-if="conflictFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}:</span>{{ [...new Set(conflictFields)].join('、') }}</p>
</div>
<div
v-if="!focusBuildability && lowConfidenceFields.length"
v-if="lowConfidenceFields.length"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-low-confidence-fields"
>
@@ -298,7 +298,7 @@ const gateChecklist = computed(() => {
</div>
<div
v-if="!focusBuildability && !eligibility.can_build && primaryBlockMessage"
v-if="!eligibility.can_build && primaryBlockMessage"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-eligibility-primary-block"
>
@@ -15,6 +15,32 @@ const i18n = createI18n({
messages: {
'zh-CN': {
'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching': '重新库存匹配',
workspace: {
shippingNotice: {
processGate: {
reasons: {
inventory_shortage_review_required: '存在库存缺口,需要人工处理',
},
},
},
},
chat: {
shippingOrderReview: {
saveOrderAndValidate: '保存订单并校验',
currentProcessing: {
waitingStart: '等待系统启动',
},
currentTask: {
statusRunning: '系统处理中',
nextStepWaitingExternal: '等待外部系统回执,暂不需要人工操作',
},
},
shippingProcessing: {
gateReasons: {
generic: '当前步骤需要人工处理',
},
},
},
},
},
});
@@ -44,6 +70,20 @@ describe('ReviewCurrentProcessingCard', () => {
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
});
it('hides the order-review entry when the user is already in the lifecycle workbench', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
primaryAction: { code: 'open_order_review', i18nKey: 'chat.shippingProcessing.action.open_order_review' },
},
global: { plugins: [i18n] },
});
// 批次中心可以用它进入工作台;工作台当前阶段不能再显示同一个自跳转入口。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
});
it('renders Gate label_key for every primary action presentation', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
@@ -60,13 +100,87 @@ describe('ReviewCurrentProcessingCard', () => {
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新库存匹配');
});
it('does not render save and validate as a current-task action', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
},
global: { plugins: [i18n] },
});
// 保存订单并校验是底栏唯一动作;未提交校验必须给出明确交接提示,不能显示系统处理中。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('保存订单并校验');
});
it('labels an unqueued automatic Gate as waiting for system start', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'fulfillment_prep',
userStatus: 'running',
gateStatus: 'pending',
},
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('等待系统启动');
});
it('explains external wait without calling it generic system processing', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'upload_complete',
userStatus: 'running',
gateStatus: 'waiting_external',
},
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text())
.toBe('等待外部系统回执,暂不需要人工操作');
});
it('never exposes an internal action code when its presentation is absent', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
primaryAction: { code: 'edit_draft' },
},
global: { plugins: [i18n] },
});
// 回退显示 edit_draft 会泄漏内部能力码;必须 fail-closed 隐藏。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('edit_draft');
});
it('renders a localized reason instead of an internal blocking code in the next step', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
userStatus: 'waiting_human',
blockingReason: { code: 'inventory_shortage_review_required' },
},
global: { plugins: [i18n] },
});
const nextStep = wrapper.get('[data-testid="review-current-task-next-step-text"]').text();
expect(nextStep).toBe('存在库存缺口,需要人工处理');
expect(nextStep).not.toContain('inventory_shortage_review_required');
});
it('renders server-provided recovery actions without duplicating the primary action', async () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
userStatus: 'waiting_human',
primaryAction: { code: 'retry_inventory_matching', i18nKey: 'retry_inventory_matching' },
recoveryActions: [{ code: 'retry_inventory_from_preparation' }],
recoveryActions: [{
code: 'retry_inventory_from_preparation',
i18nKey: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching',
}],
},
global: { plugins: [i18n] },
});
@@ -15,6 +15,8 @@ import type {
ShippingProcessingPrimaryAction,
} from '@/features/chat/types/shipping.api.types';
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
import { lookupWorkbenchAction, shouldRenderWorkbenchAction } from '@/features/shipping-progress/workbenchActionRegistry';
const props = defineProps<{
stageCode?: string | null;
@@ -41,6 +43,8 @@ const props = defineProps<{
label_key?: string | null;
parameters?: Record<string, unknown>;
}>;
/** 正式 Gate 原始状态仅用于区分未入队、运行中与外部回执等待;不参与按钮裁决。 */
gateStatus?: string | null;
taskMissing?: boolean;
confirmedTaskId?: number | null;
@@ -103,12 +107,16 @@ const statusLabel = computed(() => {
if (props.taskMissing) {
return t('chat.shippingOrderReview.currentProcessing.taskMissing');
}
if (s === 'running' && String(props.gateStatus || '').trim().toLowerCase() === 'pending') {
return t('chat.shippingOrderReview.currentProcessing.waitingStart');
}
if (!s) return t('chat.shippingOrderReview.currentProcessing.statusIdle');
return map[s] ?? t('chat.shippingOrderReview.currentProcessing.statusIdle');
});
/**
* 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason,否则按 user_status 给系统态文案。
* 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason 的统一 i18n 映射,
* 否则按 user_status 给系统态文案;禁止将后端内部原因码直接展示给用户。
*/
const nextStepText = computed(() => {
const safeMessage = (value: unknown): string => {
@@ -136,8 +144,27 @@ const nextStepText = computed(() => {
if (i18nKey && te(i18nKey)) {
return t(i18nKey);
}
// i18n 键缺失时回落为 code(不裸露给普通用户,最终 QA 期间应全部补齐)
return safeMessage(br.code) || t('chat.shippingOrderReview.currentTask.nextStepUnknown');
return resolveGateReasonLabel(br.code, { t, te })
|| t('chat.shippingOrderReview.currentTask.nextStepUnknown');
}
// 建单前订单冻结校验尚未提交时,明确告诉用户下一步是保存并校验。
// 保存是底栏唯一的表单提交入口,不升级为右栏 CTA;该分支也兼容历史响应
// 仍携带 validate 的情形,避免「待人工」与「无需操作」产生语义矛盾。
if (
String(props.stageCode || '').trim() === 'order_review'
&& !props.blockingReason
&& (
String(props.primaryAction?.code || '').trim() === 'validate'
|| String(props.userStatus || '').trim() === 'waiting_human'
)
) {
return t('chat.shippingOrderReview.saveOrderAndValidate');
}
if (
String(props.userStatus || '').trim() === 'running'
&& String(props.gateStatus || '').trim().toLowerCase() === 'waiting_external'
) {
return t('chat.shippingOrderReview.currentTask.nextStepWaitingExternal');
}
// 2) 无阻断时,按 user_status 给系统说明文案
const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | '';
@@ -168,9 +195,33 @@ const showNextStep = computed(() => {
return !['completed', 'cancelled'].includes(status);
});
/**
* 判断当前工作台是否应隐藏后端下发的纯导航动作。
* 批次中心可用它打开工作台;进入工作台后必须复用注册表规则,避免当前阶段再次显示
* 「进入订单复核」或「编辑正式任务」等自跳转入口。
*/
function isHiddenWorkbenchNavigationAction(code: string): boolean {
const entry = lookupWorkbenchAction(code);
return Boolean(entry && !shouldRenderWorkbenchAction(entry, {
actionsExecutable: true,
surface: 'review',
actionCode: code,
}));
}
/**
* 当前任务卡只承载正式 Gate 的可执行业务动作。
*
* 草稿编辑/建草稿是页面能力,保存校验是底栏唯一提交;它们即使出现在历史响应中,
* 也不能升级为右栏 CTA,更不能因缺失文案泄漏内部动作码。
*/
function isNonTaskCapabilityAction(code: string): boolean {
return new Set(['edit_draft', 'create_draft', 'validate']).has(code.trim().toLowerCase());
}
/**
* 业务动作按钮:后端确认 retryable=true → 主按钮为「重试」;
* 否则若 primary_action.code 非 retry → 用 primary_action.code + i18n_key 渲染对应人工动作(进入复核/确认客户等)。
* 否则若 primary_action.code 非 retry 且不是工作台内自跳转 → 渲染对应人工动作。
*/
const showBusinessAction = computed(() => {
if (props.loading) return false;
@@ -181,6 +232,8 @@ const showBusinessAction = computed(() => {
if (props.retryable) return true;
const code = String(props.primaryAction?.code || '').trim();
if (!code) return false;
if (isNonTaskCapabilityAction(code)) return false;
if (isHiddenWorkbenchNavigationAction(code)) return false;
// retry 仅当 retryable=true 时展示(避免按钮闪烁矛盾)
if (code === 'retry') return false;
return true;
@@ -195,6 +248,7 @@ const businessActionLabel = computed(() => {
}
const pa = props.primaryAction;
if (!pa) return '';
if (isNonTaskCapabilityAction(String(pa.code || ''))) return '';
// Gate action presentation uses label_key; normalize it at the shared card boundary
// so every gate renders its business label instead of exposing the action code.
const i18nKey = String(
@@ -210,7 +264,8 @@ const businessActionLabel = computed(() => {
if (te(legacyKey)) {
return t(legacyKey);
}
return pa.code;
// 当前任务按钮没有受控文案时 fail-closed,禁止泄漏内部 action code。
return '';
});
/** 题7A:按钮 tooltip(exhausted_sources 列表与文案)。 */
@@ -231,7 +286,14 @@ const businessActionTitle = computed(() => {
const actionIsRetry = computed(() => Boolean(props.retryable) || String(props.primaryAction?.code || '') === 'retry');
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
const code = String(action.code || '').trim();
return code && code !== String(props.primaryAction?.code || '').trim();
if (!code || isNonTaskCapabilityAction(code)) return false;
if (code === String(props.primaryAction?.code || '').trim()) return false;
const key = String(
action.i18nKey
|| action.label_key
|| `workspace.shippingNotice.processGate.actionCodes.${code}`,
).trim();
return Boolean(key && te(key));
}));
function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): string {
@@ -240,7 +302,7 @@ function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): st
|| action.label_key
|| `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
).trim();
return key && te(key) ? t(key) : action.code;
return key && te(key) ? t(key) : '';
}
function handleBusinessActionClick() {
@@ -20,6 +20,13 @@ const i18n = createI18n({
unnamedDocument: '未命名 PDF',
documentNavigation: '导航',
caseStatuses: { draft: '草稿', unknown: '未知' },
lifecycle: {
stages: {
order_review: '订单复核',
fulfillment_prep: '通知准备',
upload_complete: '通知完成',
},
},
otNav: {
listTitle: '订单列表 · {count}',
searchPlaceholder: '搜索',
@@ -71,16 +78,65 @@ describe('ReviewDocumentNavigation', () => {
expect(wrapper.find('[data-testid="review-document-navigation"]').exists()).toBe(false);
});
it('uses top tabs for 2–4 OTs', () => {
const wrapper = mountNav(3, 'tabs');
it('uses compact top tabs for 2–4 OTs', () => {
const wrapper = mountNav(3);
expect(wrapper.find('[data-testid="review-doc-nav-tabs"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(false);
expect(wrapper.attributes('data-nav-mode')).toBe('tabs');
});
it('uses sidebar list for 5–20 OTs', () => {
const wrapper = mountNav(8, 'sidebar');
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(true);
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
expect(wrapper.classes()).toContain('sticky');
});
it('keeps the sidebar collapse rail and the explicitly forced sidebar mode', async () => {
const wrapper = mount(ReviewDocumentNavigation, {
props: {
items: items(8),
activeCaseNo: 'C-1',
navAriaLabel: 'nav',
forceMode: 'sidebar',
initiallyCollapsed: true,
},
global: { plugins: [i18n] },
});
// 关键断言:生命周期四阶段兼容不能改变既有的强制侧栏与编号折叠轨交互。
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('2');
await wrapper.get('[data-testid="review-doc-nav-collapse"]').trigger('click');
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('f2.pdf');
});
it('keeps the file name as the queue row title while projecting PO, lifecycle stage and status', () => {
const rows = items(5);
rows[1] = {
...rows[1],
file_name: 'purchase-order-2.pdf',
po_number: 'PO-002',
lifecycle_stage: 'fulfillment_prep',
status: 'processing',
};
const wrapper = mount(ReviewDocumentNavigation, {
props: {
items: rows,
activeCaseNo: 'C-1',
navAriaLabel: 'nav',
forceMode: 'sidebar',
},
global: { plugins: [i18n] },
});
// 文件导航先展示可识别的文件名;PO/阶段/状态仍都来自后端队列 DTO。
const queueRow = wrapper.get('[data-testid="review-doc-nav-C-2"]');
expect(queueRow.find('.font-medium').text()).toBe('purchase-order-2.pdf');
expect(queueRow.text()).toContain('PO-002');
expect(queueRow.text()).toContain('通知准备');
// 关键断言:队列行内容必须是实际 DOM 子节点,不能被原生 template 隐藏成空白框。
expect(queueRow.find('template').exists()).toBe(false);
});
it('shows search for 20+ OTs', () => {
@@ -94,4 +150,25 @@ describe('ReviewDocumentNavigation', () => {
await wrapper.get('[data-testid="review-doc-nav-C-2"]').trigger('click');
expect(wrapper.emitted('select')?.[0]).toEqual(['C-2']);
});
it('keeps backend lifecycle stage visible in tabs and narrow queue', async () => {
const rows = items(2);
rows[1] = { ...rows[1], lifecycle_stage: 'fulfillment_prep', status: 'processing' };
const tabs = mount(ReviewDocumentNavigation, {
props: { items: rows, activeCaseNo: 'C-1', navAriaLabel: 'nav', forceMode: 'tabs' },
global: { plugins: [i18n] },
});
const narrow = mount(ReviewDocumentNavigation, {
props: { items: rows, activeCaseNo: 'C-1', navAriaLabel: 'nav', forceMode: 'narrow' },
global: { plugins: [i18n] },
attachTo: document.body,
});
// 关键断言:文件队列在任何响应式形态都只投影后端已裁决阶段。
expect(tabs.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('通知准备');
await narrow.get('[data-testid="review-doc-nav-narrow-trigger"]').trigger('click');
// 窄屏抽屉通过 Teleport 挂到 body,断言真实可见容器而非组件根节点。
expect(document.body.querySelector('[data-testid="review-doc-nav-C-2"]')?.textContent).toContain('通知准备');
narrow.unmount();
});
});
@@ -1,8 +1,8 @@
<!--
features/chat/components/shipping-review/ReviewDocumentNavigation.vue
用途:订单处理工作台 OT/PDF 导航(按数量响应式:隐藏 / 顶栏标签 / 左侧列表 / 窄屏抽屉)。
用途:订单处理工作台 OT/PDF 导航(按数量响应式:隐藏 / 紧凑标签 / 左侧列表 / 窄屏抽屉)。
依赖:vue-i18n、lucide-vue-next。
逻辑:1 份隐藏;2–4 顶栏;≥5 左侧列表(可收起);20+ 搜索过滤;窄屏「订单 i/n」抽屉。
逻辑:1 份隐藏;桌面端 2–4 紧凑标签、5–20 左侧列表(可收起);20+ 搜索过滤;窄屏「订单 i/n」抽屉。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
@@ -26,8 +26,12 @@ export type ReviewDocumentNavItem = {
po_number?: string | null;
customer_name?: string | null;
stage_label?: string | null;
/** 队列接口下发的生命周期码;仅用于本地化展示,不参与阶段裁决。 */
lifecycle_stage?: ReviewLifecycleStageCode | null;
};
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
const props = defineProps<{
@@ -82,6 +86,7 @@ const mode = computed<ReviewDocumentNavMode>(() => {
const count = props.items.length;
if (count <= 1) return 'hidden';
if (isNarrow.value) return 'narrow';
// 多文件先选文件、后查看阶段;2–4 用紧凑标签,5+ 才占用左侧工作列。
if (count <= 4) return 'tabs';
if (count <= 20) return 'sidebar';
return 'sidebar_search';
@@ -102,6 +107,14 @@ function caseStatusLabel(status: string): string {
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
}
/** 后端阶段码只做 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;
const key = `chat.shippingOrderReview.lifecycle.stages.${code}`;
return te(key) ? t(key) : null;
}
/**
* 导航状态图标语义。
*/
@@ -208,11 +221,15 @@ function onSelect(caseNo: string) {
class="h-3 w-3 shrink-0 text-slate-400"
aria-hidden="true"
/>
<span class="truncate">{{ item.po_number || item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
<span class="truncate">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
</span>
<span class="truncate text-[10px] text-slate-500 dark:text-slate-400">
{{ item.customer_name || caseStatusLabel(item.status) }}
<template v-if="item.stage_label"> · {{ item.stage_label }}</template>
{{ [
item.po_number,
lifecycleStageLabel(item),
item.stage_label,
item.customer_name || caseStatusLabel(item.status),
].filter(Boolean).join(' · ') }}
</span>
</button>
</div>
@@ -310,10 +327,14 @@ function onSelect(caseNo: string) {
/>
<span class="min-w-0 flex-1">
<span class="block truncate font-medium text-primary">
{{ item.po_number || item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}
{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}
</span>
<span class="block truncate text-[10px] text-muted">
{{ item.customer_name || caseStatusLabel(item.status) }}
{{ [
item.po_number,
lifecycleStageLabel(item),
item.customer_name || caseStatusLabel(item.status),
].filter(Boolean).join(' · ') }}
</span>
</span>
</template>
@@ -367,7 +388,9 @@ function onSelect(caseNo: string) {
@click="onSelect(item.case_no)"
>
<span class="font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
<span class="text-[10px] text-muted">{{ caseStatusLabel(item.status) }}</span>
<span class="text-[10px] text-muted">
{{ [lifecycleStageLabel(item), caseStatusLabel(item.status)].filter(Boolean).join(' · ') }}
</span>
</button>
</div>
</aside>
@@ -0,0 +1,68 @@
/**
* features/chat/components/shipping-review/ReviewFieldConflictPanel.spec.ts
* 用途:验证过期字段冲突卡在服务端返回 404 后会刷新,而不会保留为可再次提交的错误入口。
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewFieldConflictPanel。
* 逻辑:模拟并发刷新已消耗冲突,组件必须通知父工作台重取 Case 最新投影。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it, vi } from 'vitest';
import { BusinessError } from '@/shared/api/client';
import ReviewFieldConflictPanel from './ReviewFieldConflictPanel.vue';
const { resolveFieldConflict } = vi.hoisted(() => ({
resolveFieldConflict: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
resolveWorkspaceShippingOrderReviewFieldConflict: resolveFieldConflict,
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: { shippingOrderReview: {
fieldConflict: {
title: '字段冲突 {count} 项', subtitle: '请选择值', focusEvidence: '定位证据',
customValue: '手工值', customPlaceholder: '请输入', submitCustom: '确认手工值',
resolveReason: '人工裁决', resolveFailed: '提交失败', resolveSuccess: '已处理',
fields: { part_number: '料号' }, reasons: { field_conflict: '字段冲突' },
evidenceRole: {}, optionLabel: '候选 {index}', adoptOption: '采用候选值',
},
resume: { autoCreated: '已自动建单', waitingManualConfirm: '待人工确认' },
} },
},
},
});
describe('ReviewFieldConflictPanel', () => {
it('refreshes the case when confirming a stale manual value returns conflict-not-found', async () => {
resolveFieldConflict.mockRejectedValueOnce(new BusinessError({
message: 'Field conflict not found',
code: 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
status: 404,
}));
const wrapper = mount(ReviewFieldConflictPanel, {
props: {
caseNo: 'SORC-1', draftVersion: 1, editable: true,
conflicts: [{
conflict_key: '-1:part_number', field_code: 'part_number', line_index: -1,
reason: 'field_conflict', options: [],
}],
},
global: { plugins: [i18n] },
});
await wrapper.get('[data-testid="review-field-conflict-custom-toggle"]').trigger('click');
await wrapper.get('[data-testid="review-field-conflict-custom-input"]').setValue('PN-001');
await wrapper.get('[data-testid="review-field-conflict-custom-submit"]').trigger('click');
await vi.waitFor(() => expect(wrapper.emitted('refreshed')).toHaveLength(1));
// 关键断言:404 代表页面投影过期,父工作台会加载最新 Case 并移除这张卡。
expect(resolveFieldConflict).toHaveBeenCalledWith('SORC-1', '-1:part_number', expect.objectContaining({
resolution: 'custom', custom_value: 'PN-001', expected_draft_version: 1,
}));
});
});
@@ -105,6 +105,12 @@ async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionInd
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
if (error instanceof BusinessError && error.code === 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND') {
// 冲突已被其他刷新/裁决消耗:以服务端最新 Case 为准,撤掉当前过期卡片。
msg.info(resolveLocalizedErrorMessage(error.code, error.message));
emit('refreshed');
return;
}
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
@@ -146,6 +152,12 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
if (error instanceof BusinessError && error.code === 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND') {
// 与采用候选值保持同一 stale-data 恢复路径,禁止把已解决冲突留在页面上。
msg.info(resolveLocalizedErrorMessage(error.code, error.message));
emit('refreshed');
return;
}
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
@@ -0,0 +1,139 @@
/**
* features/chat/components/shipping-review/ReviewIntakeParsePanel.spec.ts
* 用途:锁定接收解析工作面只展示当前 Case 已授权的邮件正文与附件预览。
* 依赖:Vitest、Vue Test Utils、vue-i18n、ReviewIntakeParsePanel。
* 逻辑:PDF 才允许嵌入预览;非 PDF 明确降级;所有处置仅向父级发出意图。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import ReviewIntakeParsePanel from './ReviewIntakeParsePanel.vue';
import type { ShippingOrderReviewIntakeParseContext } from '@/features/chat/types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
lifecycle: {
intakeParse: {
title: '接收解析',
email: '邮件正文',
noEmail: '无邮件上下文',
attachment: '当前附件',
fileName: '文件名',
fileType: '文件类型',
preview: '附件预览',
loadPreview: '加载附件预览',
previewUnsupported: '当前附件不支持预览',
loadFailed: '接收解析上下文加载失败',
retry: '重试',
loading: '正在加载接收解析上下文',
},
},
markNonOrder: '标记为非订单',
markQualityIssue: '文件质量异常',
reparse: '重新识别此 PDF',
uploadReplacement: '上传替代 PDF',
},
},
},
},
});
const emailPdfContext: ShippingOrderReviewIntakeParseContext = {
case_no: 'CASE-1',
attachment: {
document_id: 11,
filename: 'current.pdf',
mime_type: 'application/pdf',
preview_kind: 'pdf',
},
email: {
document_id: 7,
filename: 'source.eml',
text: 'approved body text',
},
};
const unsupportedContext: ShippingOrderReviewIntakeParseContext = {
...emailPdfContext,
attachment: {
document_id: 12,
filename: 'source.xlsx',
mime_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
preview_kind: 'unsupported',
},
email: null,
};
function mountPanel(props: Record<string, unknown>) {
return mount(ReviewIntakeParsePanel, {
props: {
loading: false,
loadFailed: false,
previewUrl: null,
previewLoading: false,
saving: false,
canMarkNonOrder: false,
canMarkQualityIssue: false,
canReparse: false,
canUploadReplacement: false,
...props,
},
global: { plugins: [i18n] },
});
}
describe('ReviewIntakeParsePanel', () => {
it('renders EML text and only the selected attachment preview', () => {
const wrapper = mountPanel({ context: emailPdfContext, previewUrl: 'blob:pdf' });
// 关键断言:邮件正文与当前附件来自同一个受控 Case context,PDF 才嵌入预览。
expect(wrapper.get('[data-testid="intake-parse-email-body"]').text()).toContain('approved body text');
expect(wrapper.get('[data-testid="intake-parse-attachment-preview"] iframe').attributes('src')).toBe('blob:pdf');
});
it('does not render a PDF frame for an unsupported attachment', () => {
const wrapper = mountPanel({ context: unsupportedContext });
// 关键断言:非 PDF 不得退化为 iframe,必须明确告知不可预览。
expect(wrapper.find('[data-testid="intake-parse-attachment-preview"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="intake-parse-preview-unsupported"]').exists()).toBe(true);
expect(wrapper.get('[data-testid="intake-parse-no-email"]').text()).toContain('无邮件上下文');
});
it('emits parse disposition intent without executing Case commands', async () => {
const wrapper = mountPanel({
context: emailPdfContext,
canMarkNonOrder: true,
canMarkQualityIssue: true,
canReparse: true,
canUploadReplacement: true,
});
await wrapper.get('[data-testid="intake-parse-mark-non-order"]').trigger('click');
await wrapper.get('[data-testid="intake-parse-mark-quality-issue"]').trigger('click');
await wrapper.get('[data-testid="intake-parse-reparse"]').trigger('click');
await wrapper.get('[data-testid="intake-parse-upload-replacement"] input').trigger('change');
expect(wrapper.emitted('mark-non-order')).toHaveLength(1);
expect(wrapper.emitted('mark-quality-issue')).toHaveLength(1);
expect(wrapper.emitted('reparse')).toHaveLength(1);
expect(wrapper.emitted('upload-replacement')).toHaveLength(1);
});
it('does not infer replacement permission from another disposition permission', () => {
const wrapper = mountPanel({
context: emailPdfContext,
canMarkQualityIssue: true,
canUploadReplacement: false,
});
// 关键断言:父级必须显式授予替代上传,不能因质量异常动作可用而显示上传入口。
expect(wrapper.get('[data-testid="intake-parse-mark-quality-issue"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="intake-parse-upload-replacement"]').exists()).toBe(false);
});
});
@@ -0,0 +1,200 @@
<!--
features/chat/components/shipping-review/ReviewIntakeParsePanel.vue
用途:在接收解析阶段展示当前 Case 已授权的邮件正文、当前附件及安全预览。
依赖:vue、vue-i18n、ShippingOrderReviewIntakeParseContext。
逻辑:只消费父级按 Case 获取的受控上下文;仅 PDF 可请求/渲染 iframe;处置操作只 emit,
由父页沿用既有确认弹窗和 Case 命令。
-->
<script setup lang="ts">
import { watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewIntakeParseContext } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
context: ShippingOrderReviewIntakeParseContext | null;
loading: boolean;
loadFailed: boolean;
previewUrl: string | null;
previewLoading: boolean;
saving: boolean;
canMarkNonOrder: boolean;
canMarkQualityIssue: boolean;
canReparse: boolean;
canUploadReplacement: boolean;
}>();
const emit = defineEmits<{
'retry-context': [];
'load-preview': [];
'mark-non-order': [];
'mark-quality-issue': [];
reparse: [];
'upload-replacement': [event: Event];
}>();
const { t } = useI18n();
/**
* 当前附件为 PDF 且尚无受控 Blob 时,通知父级使用当前 Case 加载预览。
* 仅 Case context 改变时触发,禁止对不受支持文件发起预览请求。
*/
watch(
() => props.context,
(context) => {
if (context?.attachment.preview_kind === 'pdf' && !props.previewUrl) {
emit('load-preview');
}
},
{ immediate: true },
);
</script>
<template>
<section
class="space-y-4"
data-testid="intake-parse-panel"
>
<div
v-if="loading"
class="rounded-xl border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-600 dark:border-slate-700 dark:bg-slate-900/40 dark:text-slate-300"
data-testid="intake-parse-loading"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loading') }}
</div>
<div
v-else-if="loadFailed"
class="rounded-xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-900 dark:bg-rose-950/40 dark:text-rose-100"
data-testid="intake-parse-load-failed"
>
<p>{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loadFailed') }}</p>
<button
type="button"
class="mt-3 rounded border border-rose-300 px-2.5 py-1 text-xs hover:bg-rose-100 dark:border-rose-800 dark:hover:bg-rose-950"
data-testid="intake-parse-retry-context"
@click="emit('retry-context')"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.retry') }}
</button>
</div>
<template v-else-if="context">
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.email') }}</h2>
<template v-if="context.email">
<p class="mt-1 text-xs text-slate-500">{{ context.email.filename }}</p>
<pre
class="mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-slate-50 p-3 text-xs text-slate-700 dark:bg-slate-950/50 dark:text-slate-200"
data-testid="intake-parse-email-body"
>{{ context.email.text }}</pre>
</template>
<p
v-else
class="mt-2 text-sm text-slate-500"
data-testid="intake-parse-no-email"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.noEmail') }}
</p>
</section>
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.attachment') }}</h2>
<dl class="mt-3 grid gap-2 text-sm sm:grid-cols-2">
<div>
<dt class="text-xs text-slate-500">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.fileName') }}</dt>
<dd class="mt-0.5 break-all">{{ context.attachment.filename }}</dd>
</div>
<div>
<dt class="text-xs text-slate-500">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.fileType') }}</dt>
<dd class="mt-0.5 break-all">{{ context.attachment.mime_type || '-' }}</dd>
</div>
</dl>
<div
v-if="context.attachment.preview_kind === 'pdf'"
class="mt-4"
data-testid="intake-parse-attachment-preview"
>
<h3 class="text-xs font-medium text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.preview') }}</h3>
<p
v-if="previewLoading"
class="mt-2 text-sm text-slate-500"
data-testid="intake-parse-preview-loading"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewLoading') }}
</p>
<iframe
v-else-if="previewUrl"
:src="previewUrl"
:title="context.attachment.filename"
class="mt-2 h-[32rem] w-full rounded border border-slate-200 dark:border-slate-700"
/>
<button
v-else
type="button"
class="mt-2 rounded border border-slate-300 px-2.5 py-1 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="intake-parse-load-preview"
@click="emit('load-preview')"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loadPreview') }}
</button>
</div>
<p
v-else
class="mt-4 rounded bg-slate-50 p-3 text-sm text-slate-500 dark:bg-slate-950/50"
data-testid="intake-parse-preview-unsupported"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewUnsupported') }}
</p>
</section>
<div class="flex flex-wrap gap-2" data-testid="intake-parse-disposition-actions">
<button
v-if="canMarkNonOrder"
type="button"
:disabled="saving"
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300"
data-testid="intake-parse-mark-non-order"
@click="emit('mark-non-order')"
>
{{ t('chat.shippingOrderReview.markNonOrder') }}
</button>
<button
v-if="canMarkQualityIssue"
type="button"
:disabled="saving"
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200"
data-testid="intake-parse-mark-quality-issue"
@click="emit('mark-quality-issue')"
>
{{ t('chat.shippingOrderReview.markQualityIssue') }}
</button>
<button
v-if="canReparse"
type="button"
:disabled="saving"
class="rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300"
data-testid="intake-parse-reparse"
@click="emit('reparse')"
>
{{ t('chat.shippingOrderReview.reparse') }}
</button>
<label
v-if="canUploadReplacement"
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300"
:class="saving ? 'pointer-events-none opacity-50' : ''"
data-testid="intake-parse-upload-replacement"
>
<input
class="sr-only"
type="file"
accept="application/pdf,.pdf"
:disabled="saving"
@change="emit('upload-replacement', $event)"
>
{{ t('chat.shippingOrderReview.uploadReplacement') }}
</label>
</div>
</template>
</section>
</template>
@@ -0,0 +1,94 @@
/**
* features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts
* 用途:验收订单生命周期阶段导航的只读查看与前置阻断交互。
* 依赖:ReviewLifecycleStageNavigation;Vue Test Utils 与 Vue I18n 测试运行时。
* 逻辑:阶段状态由父级传入;本测试只验证组件不会绕过 blocked 状态发出选择事件。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewLifecycleStageNavigation, {
type ReviewLifecycleStageItem,
} from './ReviewLifecycleStageNavigation.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
lifecycle: {
navigation: '订单生命周期阶段',
current: '当前可处理',
completed: '已完成,可查看',
blocked: '前置未完成',
},
},
},
},
},
});
const stages: ReviewLifecycleStageItem[] = [
{ code: 'order_review', label: '订单复核', state: 'completed' },
{ code: 'fulfillment_prep', label: '通知准备', state: 'current' },
{ code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' },
];
/** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */
function mountNavigation() {
return mount(ReviewLifecycleStageNavigation, {
props: { stages, activeCode: 'fulfillment_prep' },
global: { plugins: [i18n] },
});
}
describe('ReviewLifecycleStageNavigation', () => {
it('renders intake_parse as the first lifecycle stage', () => {
const wrapper = mount(ReviewLifecycleStageNavigation, {
props: {
stages: [
{ code: 'intake_parse' as ReviewLifecycleStageItem['code'], label: '接收解析', state: 'current' },
...stages,
],
activeCode: 'intake_parse' as ReviewLifecycleStageItem['code'],
},
global: { plugins: [i18n] },
});
const nodes = wrapper.findAll('div[data-testid^="review-lifecycle-stage-"]');
// 关键断言:接收解析必须在用户生命周期导航首位,不得回退为三阶段。
expect(nodes.map((node) => node.attributes('data-testid'))).toEqual([
'review-lifecycle-stage-intake_parse',
'review-lifecycle-stage-order_review',
'review-lifecycle-stage-fulfillment_prep',
'review-lifecycle-stage-upload_complete',
]);
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-4');
});
it('allows opening a completed stage for inspection', async () => {
const wrapper = mountNavigation();
await wrapper.get('[data-testid="review-lifecycle-stage-order_review"]').findAll('button')[1].trigger('click');
// 关键断言:完成的阶段可回看,不会因已完成而被禁用。
expect(wrapper.emitted('select')).toEqual([['order_review']]);
});
it('disables a future stage and does not emit a selection', async () => {
const wrapper = mountNavigation();
const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
// 关键断言:前置未完成只展示原因,不能通过前端导航越过后端阶段。
expect(future.text()).toContain('请先完成通知准备');
await future.findAll('button')[1].trigger('click');
expect(wrapper.emitted('select')).toBeUndefined();
});
it('opens process details from the stage label without reserving a separate row', async () => {
const wrapper = mountNavigation();
const detail = wrapper.get('[data-testid="review-lifecycle-stage-detail-fulfillment_prep"]');
// 关键断言:阶段名称本身是流程详情入口,不额外占用工作台一整行。
await detail.trigger('click');
expect(wrapper.emitted('open-detail')).toEqual([['fulfillment_prep']]);
});
});
@@ -0,0 +1,87 @@
<!--
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 ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
export interface ReviewLifecycleStageItem {
code: ReviewLifecycleStageCode;
label: string;
state: ReviewLifecycleStageState;
reason?: string | null;
}
const props = defineProps<{
stages: ReviewLifecycleStageItem[];
/** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */
activeCode: ReviewLifecycleStageCode | null;
}>();
const emit = defineEmits<{
select: [code: ReviewLifecycleStageCode];
'open-detail': [code: ReviewLifecycleStageCode];
}>();
/**
* 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。
*/
function selectStage(stage: ReviewLifecycleStageItem) {
if (stage.state === 'blocked') return;
emit('select', stage.code);
}
</script>
<template>
<nav
class="rounded-xl border border-default bg-surface p-2"
:aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')"
data-testid="review-lifecycle-stage-navigation"
>
<div class="grid gap-2 sm:grid-cols-4">
<div
v-for="stage in props.stages"
:key="stage.code"
class="min-w-0 rounded-lg border px-3 py-2 text-left transition-colors"
:class="[
stage.code === props.activeCode
? 'border-brand-500 bg-brand-50 text-brand-950 dark:bg-brand-950/30 dark:text-brand-50'
: 'border-transparent hover:bg-surface-soft',
stage.state === 'blocked' ? 'opacity-60' : '',
]"
:data-testid="`review-lifecycle-stage-${stage.code}`"
>
<span class="flex items-center gap-2 text-sm font-semibold">
<Check v-if="stage.state === 'completed'" class="h-4 w-4 shrink-0 text-emerald-600" />
<LockKeyhole v-else-if="stage.state === 'blocked'" class="h-4 w-4 shrink-0 text-muted" />
<span v-else class="h-2 w-2 shrink-0 rounded-full bg-brand-600" aria-hidden="true" />
<button
type="button"
class="truncate text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500"
:data-testid="`review-lifecycle-stage-detail-${stage.code}`"
@click="emit('open-detail', stage.code)"
>{{ stage.label }}</button>
</span>
<button
type="button"
class="mt-1 block w-full truncate text-left text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 disabled:cursor-not-allowed"
:class="stage.state === 'blocked' ? 'text-muted' : 'text-secondary'"
:title="stage.reason || undefined"
:disabled="stage.state === 'blocked'"
@click="selectStage(stage)"
>
{{ stage.state === 'current'
? $t('chat.shippingOrderReview.lifecycle.current')
: stage.state === 'completed'
? $t('chat.shippingOrderReview.lifecycle.completed')
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
</button>
</div>
</div>
</nav>
</template>
@@ -0,0 +1,44 @@
/**
* features/chat/components/shipping-review/ReviewWorkbenchFooter.spec.ts
* 用途:验证字段冲突的 Gate 主动作只由右栏当前任务卡承载,底栏不得重复展示。
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewWorkbenchFooter。
* 逻辑:订单复核底栏只保留保存校验,不展示已由当前任务卡或阶段页承载的流程动作。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import ReviewWorkbenchFooter from './ReviewWorkbenchFooter.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingProcessing: { action: { resolve_field_conflicts: '处理字段冲突', view_result: '查看结果', none: '无操作' } },
shippingOrderReview: { unsavedSwitch: { unsavedCount: '未保存 {count} 项' } },
},
workspace: { shippingNotice: { processGate: { actions: {} } } },
},
},
});
describe('ReviewWorkbenchFooter', () => {
it('does not duplicate current-case flow actions in the order-review footer', () => {
const wrapper = mount(ReviewWorkbenchFooter, {
props: {
availableActions: [], canConfirmBuild: false, saving: false, isReadOnly: false, hasDraft: true,
flowPresentation: {
primary: { intent: 'resolve_field_conflicts', actionCode: 'resolve_field_conflicts', labelKey: 'chat.shippingProcessing.action.resolve_field_conflicts' },
secondary: { intent: 'view_result', actionCode: 'view_result', labelKey: 'chat.shippingProcessing.action.view_result' },
overflow: [],
},
},
global: { plugins: [i18n] },
});
// 关键断言:字段冲突、重试和查看结果各有上游上下文,复核底栏不得重复它们。
expect(wrapper.find('[data-testid="review-footer-flow-resolve_field_conflicts"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-footer-flow-view_result"]').exists()).toBe(false);
});
});
@@ -3,7 +3,7 @@
用途:订单处理工作台底部唯一写操作栏(处置 / 保存 / 统一流程动作)。
依赖:vue-i18n、lucide-vue-next、ActionPresentation。
逻辑:ShippingOrderReviewView 传入 available_actions 与流程动作投影;sticky bottom;
只读查看时仍可展示 view_result/view_record;写按钮受 actionsExecutable 约束;
订单复核只保留保存校验;流程动作由所属阶段或当前任务卡承载;写按钮受 actionsExecutable 约束;
流程写操作经 flow-action emit(与 Resolver 同链);flowBusy||saving 时禁用。
-->
<script setup lang="ts">
@@ -36,6 +36,8 @@ const props = withDefaults(defineProps<{
actionsExecutable?: boolean;
/** 统一流程动作提交中 */
flowBusy?: boolean;
/** 解析处置入口由接收解析工作面承载时,订单复核底栏隐藏四项解析操作。 */
showParseDispositions?: boolean;
}>(), {
unsavedCount: 0,
flowPresentation: null,
@@ -46,6 +48,7 @@ const props = withDefaults(defineProps<{
autoGateHint: '',
actionsExecutable: true,
flowBusy: false,
showParseDispositions: true,
});
const emit = defineEmits<{
@@ -59,7 +62,7 @@ const emit = defineEmits<{
'flow-action': [item: ActionPresentationItem];
}>();
const { t, te } = useI18n();
const { t } = useI18n();
/**
* 判断某 action 是否在当前 Case 可用。
@@ -68,40 +71,25 @@ function hasAction(action: string): boolean {
return props.availableActions.includes(action);
}
const flowItems = computed((): ActionPresentationItem[] => {
const presentation = props.flowPresentation;
if (!presentation) return [];
const items: ActionPresentationItem[] = [];
if (presentation.primary) items.push(presentation.primary);
if (presentation.secondary) items.push(presentation.secondary);
items.push(...presentation.overflow);
// 刷新留给顶部只读区;底栏不重复。
return items.filter((item) => item.intent !== 'refresh');
});
/**
* 订单复核底栏不承载流程投影动作。
*
* 核心逻辑:保存并校验是表单级提交,固定放在这里;字段裁决、重试、查看结果等
* Case/阶段级动作必须留在其业务上下文中,避免同一动作在顶栏、右栏和底栏重复出现。
*/
const footerFlowItems = computed((): ActionPresentationItem[] => []);
const hasViewOnlyFlow = computed(() => flowItems.value.some((item) => (
item.intent === 'view_result'
|| item.intent === 'view_record'
|| item.intent === 'open_profile_review'
)));
/** 保留统一动作的文案解析,供后续恢复 Footer 流程动作时复用。 */
function flowLabel(item: ActionPresentationItem): string {
return t(item.labelKey);
}
/** 可编辑底栏,或只读但仍有导航/查看类流程动作。 */
const showFooter = computed(() => (
props.hasDraft && (!props.isReadOnly || hasViewOnlyFlow.value)
));
/** 仅可编辑草稿显示表单提交底栏;只读版本不显示无上下文的流程按钮。 */
const showFooter = computed(() => props.hasDraft && !props.isReadOnly);
const controlsBusy = computed(() => props.saving || props.flowBusy);
const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isReadOnly);
/**
* 流程动作文案。
*/
function flowLabel(item: ActionPresentationItem): string {
if (te(item.labelKey)) return t(item.labelKey);
const gateKey = `workspace.shippingNotice.processGate.actions.${item.actionCode}`;
if (te(gateKey)) return t(gateKey);
return t('chat.shippingProcessing.action.none');
}
</script>
<template>
@@ -116,7 +104,7 @@ function flowLabel(item: ActionPresentationItem): string {
<div class="order-1 flex flex-wrap items-center gap-2 sm:order-1">
<template v-if="!automating && canWriteCaseActions">
<button
v-if="hasAction('mark_non_order')"
v-if="showParseDispositions && hasAction('mark_non_order')"
type="button"
:disabled="controlsBusy"
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/40"
@@ -125,7 +113,7 @@ function flowLabel(item: ActionPresentationItem): string {
{{ t('chat.shippingOrderReview.markNonOrder') }}
</button>
<button
v-if="hasAction('mark_quality_issue')"
v-if="showParseDispositions && hasAction('mark_quality_issue')"
type="button"
:disabled="controlsBusy"
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 hover:bg-amber-50 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200 dark:hover:bg-amber-950/40"
@@ -134,7 +122,7 @@ function flowLabel(item: ActionPresentationItem): string {
{{ t('chat.shippingOrderReview.markQualityIssue') }}
</button>
<button
v-if="hasAction('reparse')"
v-if="showParseDispositions && hasAction('reparse')"
type="button"
:disabled="controlsBusy"
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
@@ -143,7 +131,7 @@ function flowLabel(item: ActionPresentationItem): string {
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
</button>
<label
v-if="hasAction('mark_quality_issue')"
v-if="showParseDispositions && hasAction('mark_quality_issue')"
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
:class="controlsBusy ? 'pointer-events-none opacity-50' : ''"
>
@@ -159,7 +147,7 @@ function flowLabel(item: ActionPresentationItem): string {
</template>
<button
v-for="item in flowItems"
v-for="item in footerFlowItems"
:key="`${item.intent}-${item.actionCode}`"
type="button"
:disabled="controlsBusy"
@@ -195,16 +183,6 @@ function flowLabel(item: ActionPresentationItem): string {
{{ autoGateHint || t('chat.shippingOrderReview.buildEligibility.autoGateWaitingHint') }}
</p>
<template v-if="!automating && canWriteCaseActions">
<button
v-if="showStpRetry || hasAction('retry_stp_auto_create')"
type="button"
:disabled="controlsBusy"
class="inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-3 py-2 text-sm text-amber-950 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-retry-stp-auto-create"
@click="emit('retry-stp')"
>
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.autoProgress.retryObject') }}
</button>
<button
v-if="hasAction('validate')"
type="button"
@@ -212,7 +190,7 @@ function flowLabel(item: ActionPresentationItem): string {
class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50"
@click="emit('validate')"
>
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveOrderAndValidate') }}
</button>
</template>
</div>
@@ -14,6 +14,7 @@ const props = defineProps<{
runNo: string;
itemNo?: string | null;
versionLabel?: string;
selectedOrderSummary?: string | null;
saving: boolean;
saveFailed: boolean;
draftConflict: boolean;
@@ -38,19 +39,6 @@ const emit = defineEmits<{
const { t } = useI18n();
/**
* 副标题:优先工作项编号与版本,否则识别批次号。
*/
const subtitle = computed(() => {
if (props.itemNo) {
return t('chat.shippingOrderReview.workItemHeader', {
itemNo: props.itemNo,
version: props.versionLabel || '',
});
}
return t('chat.shippingOrderReview.run', { runNo: props.runNo });
});
const showRetry = computed(() => (
Boolean(props.showConversationRetry)
&& Number(props.conversationRetryEligibleCount || 0) > 0
@@ -69,7 +57,11 @@ const showRetry = computed(() => (
</button>
<div class="min-w-0 flex-1">
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
<p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ subtitle }}</p>
<p
v-if="selectedOrderSummary"
class="truncate text-xs text-slate-600 dark:text-slate-300"
data-testid="review-selected-order-summary"
>{{ selectedOrderSummary }}</p>
</div>
<button
v-if="showRetry"
@@ -117,6 +117,210 @@ function buildWorkItem(
}
describe('ShippingConversationProcessingCard', () => {
it('only exposes file cancellation when the backend explicitly authorizes cancel_unit', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-CANCEL-UNIT', group: 'processing', status_label: 'extracting',
file_count: 1, run_no: 'RUN-CANCEL-UNIT', can_append: false,
objects: [{ kind: 'document', object_key: 'DOC-9', label: 'cancel.pdf', filename: 'cancel.pdf',
document_id: 9, root_document_id: 9, status_label: 'extracting' }],
}];
const workItem = buildWorkItem('OT-CANCEL-UNIT', {
availableActions: ['cancel_unit'],
sourceSummary: { ...buildWorkItem('OT-CANCEL-UNIT').sourceSummary, documentId: 9 },
uiState: {
status: 'running',
stage: 'document_parsing',
blocking_reason: null,
primary_action: null,
secondary_actions: [{ code: 'cancel_unit', enabled: true }],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [workItem], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
await wrapper.find('summary').trigger('click');
await wrapper.find('[data-testid="shipping-processing-file-cancel"]').trigger('click');
expect(wrapper.emitted('fileAction')?.[0]?.[0]).toMatchObject({
action: 'cancel_unit', projection: { workItemNo: 'OT-CANCEL-UNIT' },
});
});
it('does not fall back to legacy cancellation when ui_state revokes it', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-CANCEL-REVOKED', group: 'processing', status_label: 'extracting',
file_count: 1, run_no: 'RUN-CANCEL-REVOKED', can_append: false,
objects: [{ kind: 'document', object_key: 'DOC-10', label: 'revoked.pdf', filename: 'revoked.pdf',
document_id: 10, root_document_id: 10, status_label: 'extracting' }],
}];
const workItem = buildWorkItem('OT-CANCEL-REVOKED', {
availableActions: ['cancel_unit'],
sourceSummary: { ...buildWorkItem('OT-CANCEL-REVOKED').sourceSummary, documentId: 10 },
uiState: {
status: 'running',
stage: 'document_parsing',
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [workItem], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
// ui_state 已出现即表示后端完成了正式动作裁决;遗留 availableActions 不得重新授权。
expect(wrapper.find('[data-testid="shipping-processing-file-cancel"]').exists()).toBe(false);
expect(wrapper.emitted('fileAction')).toBeUndefined();
});
it('does not render legacy document_names as a batch file row without a live leaf projection', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-HISTORICAL-SNAPSHOT', group: 'processing', status_label: 'extracting',
title: 'legacy-run.pdf', document_names: ['legacy-run.pdf'], file_count: 1,
run_no: 'RUN-HISTORICAL-SNAPSHOT', can_append: false,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
// 批次中心没有实时叶子投影时不得由历史 Run 快照补造文件行或操作入口。
expect(wrapper.find('[data-testid="shipping-processing-file-OT-HISTORICAL-SNAPSHOT-document-0"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('legacy-run.pdf');
});
it('uses the live leaf summary instead of a stale task object in batch mode', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-LIVE-LEAF', group: 'processing', status_label: 'extracting',
title: 'snapshot-old-name.pdf', file_count: 1, run_no: 'RUN-LIVE-LEAF', can_append: false,
objects: [{
kind: 'document', object_key: 'DOC-88', label: 'snapshot-old-name.pdf',
filename: 'snapshot-old-name.pdf', document_id: 88, root_document_id: 88,
status_label: 'pending_review',
}],
}];
const live = buildWorkItem('OT-LIVE-LEAF', {
runNo: 'RUN-LIVE-LEAF',
sourceSummary: {
emailSubject: null, filename: 'realtime-name.pdf', documentId: 88,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-REALTIME',
},
uiState: {
status: 'running', stage: 'order_review', lifecycleStage: 'order_review',
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [live], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-88"]');
expect(row.text()).toContain('realtime-name.pdf');
expect(row.text()).toContain('PO:PO-REALTIME');
expect(row.text()).not.toContain('snapshot-old-name.pdf');
});
it('expands EML files only from the live aggregate work item', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'INTAKE:EML-LIVE', group: 'processing', status_label: 'extracting',
title: 'snapshot-mail.eml', document_names: ['snapshot-attachment.pdf'],
file_count: 1, run_no: 'RUN-EML-LIVE', can_append: false,
aggregateChildren: [],
}];
const liveChild = buildWorkItem('DOCUMENT:77', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
sourceSummary: {
emailSubject: null, filename: 'live-attachment.pdf', documentId: 77,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-EML-LIVE',
},
uiState: {
status: 'running', stage: 'order_review', lifecycleStage: 'order_review',
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const liveEmlRoot = buildWorkItem('INTAKE:EML-LIVE', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
sourceSummary: {
emailSubject: 'Live mail', filename: 'live-mail.eml', documentId: null,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: null,
},
aggregateChildren: [liveChild],
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [liveEmlRoot], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-77"]');
expect(row.text()).toContain('live-attachment.pdf');
expect(row.text()).toContain('PO:PO-EML-LIVE');
expect(wrapper.text()).not.toContain('snapshot-attachment.pdf');
});
it('keeps an EML attachment when it has a linked child order task', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'INTAKE:EML-WITH-CHILD-OT', group: 'processing', status_label: 'extracting',
title: 'mail.eml', file_count: 2, run_no: 'RUN-EML-WITH-CHILD-OT', can_append: false,
}];
const firstAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: null, filename: 'first.pdf', documentId: 266,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-FIRST',
},
childOrderTasks: [{
orderTaskNo: 'OT-EML-WITH-CHILD-OT-C1', status: 'blocked', stage: 'inventory_matching',
customerName: null, poNumber: 'PO-SECOND', lastActivityAt: null,
}],
});
const secondAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT-C1', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: null, filename: 'second.pdf', documentId: 267,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-SECOND',
},
});
const liveEmlRoot = buildWorkItem('INTAKE:EML-WITH-CHILD-OT', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: 'Mail', filename: 'mail.eml', documentId: null,
documentCount: 2, parsedDocumentCount: 2, candidateCount: 2,
customerName: null, poNumber: null,
},
aggregateChildren: [firstAttachment, secondAttachment],
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [liveEmlRoot], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-266"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-267"]').exists()).toBe(true);
expect(wrapper.text()).toContain('处理中 · 2 个文件');
});
it('renders needs_action / processing groups and collapsible processing records with three subsections', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection: buildProjection() },
@@ -127,8 +331,9 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
expect(wrapper.text()).toContain('异常 / 失败 · 1 个任务');
expect(wrapper.text()).toContain('系统处理中 · 1 个任务');
// 批次中心统一按文件计数;旧任务数文案不再是页面统计口径。
expect(wrapper.text()).toContain('异常 · 0 个文件');
expect(wrapper.text()).toContain('处理中 · 0 个文件');
expect(wrapper.text()).toContain('刚刚创建');
// 处理记录默认折叠;标题 count = completed + history 返回条数。
@@ -559,7 +764,110 @@ describe('ShippingConversationProcessingCard', () => {
});
await flushPromises();
expect(wrapper.text()).toContain('待复核');
// 旧聚合卡不再显示内部 Case 状态;工作台文件行才展示后端 ui_state。
expect(wrapper.text()).not.toContain('review_case_draft');
expect(wrapper.text()).not.toContain('review_case_draft');
});
it('renders a compact V3 file row with named lifecycle entries', async () => {
const projection = buildProjection();
projection.processing = [{
...projection.processing[0],
user_task_no: 'OT-LIFECYCLE',
run_no: 'RUN-LIFECYCLE',
file_count: 1,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection,
workbenchMode: true,
workItems: [buildWorkItem('OT-LIFECYCLE', {
runNo: 'RUN-LIFECYCLE',
caseNo: 'CASE-LIFECYCLE',
sourceSummary: {
emailSubject: null,
filename: 'lifecycle.pdf',
documentId: 9,
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-LIFECYCLE',
},
uiState: {
status: 'running',
stage: 'inventory_match',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
})],
},
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-9"]');
expect(row.exists()).toBe(true);
expect(row.text()).toContain('lifecycle.pdf');
expect(row.text()).toContain('PO:PO-LIFECYCLE');
expect(row.text()).toContain('通知准备');
expect(row.text()).toContain('订单复核 · 可进入');
expect(row.text()).toContain('通知准备 · 当前可处理');
expect(row.text()).toContain('通知完成 · 前置未完成');
});
it('fails closed when a lifecycle entry has an unknown backend state', async () => {
const projection = buildProjection();
projection.processing = [{
...projection.processing[0],
user_task_no: 'OT-LIFECYCLE-UNKNOWN',
run_no: 'RUN-LIFECYCLE-UNKNOWN',
file_count: 1,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection,
workbenchMode: true,
workItems: [buildWorkItem('OT-LIFECYCLE-UNKNOWN', {
runNo: 'RUN-LIFECYCLE-UNKNOWN',
sourceSummary: {
emailSubject: null,
filename: 'unknown-entry.pdf',
documentId: 10,
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-UNKNOWN',
},
uiState: {
status: 'running',
stage: 'inventory_match',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [
{ code: 'order_review', state: 'paused', targetSurface: 'order_lifecycle_workbench' },
] as unknown as ShippingProcessingProjection['uiState']['lifecycleEntries'],
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
})],
},
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
const orderReview = row.findAll('button').find((button) => button.text().includes('订单复核'));
expect(orderReview?.attributes('disabled')).toBeDefined();
await orderReview?.trigger('click');
expect(wrapper.emitted('openLifecycleStage')).toBeUndefined();
});
});
@@ -13,10 +13,11 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight } from 'lucide-vue-next';
import { ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-vue-next';
import type {
ConversationProcessingProjection,
ConversationProcessingUserTask,
ShippingProcessingLifecycleEntry,
ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import { getPrimaryDocumentName } from '@/features/chat/shipping/conversationProcessingDisplay';
@@ -30,8 +31,9 @@ import {
} from '@/features/chat/shipping/conversationProcessingState';
import {
resolveShippingProcessingMessage,
resolveShippingProcessingReasonLabel,
resolveShippingProcessingStageLabel,
resolveShippingProcessingStatusLabel,
shippingProcessingStageKey,
} from '@/features/chat/shipping/shippingProcessingLabels';
import { flattenBusinessFileProjections } from '@/features/chat/shipping/conversationProcessingProjection';
import { resolveConversationTaskActionPresentation, resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
@@ -48,6 +50,13 @@ const props = defineProps<{
hasMoreHistory?: boolean;
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
workbenchMode?: boolean;
/** 批次四阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
/** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */
fileSearchQuery?: string;
/** 后端已授权下载的正式 Excel 对应 OT。 */
downloadableTaskNos?: string[];
selectedDownloadTaskNos?: string[];
}>();
const emit = defineEmits<{
@@ -61,6 +70,12 @@ const emit = defineEmits<{
intakeAction: [payload: { item: ShippingProcessingProjection; action: string }];
/** OT 卡内统一进度动作。 */
projectionAction: [payload: { projection: ShippingProcessingProjection; item: ActionPresentationItem }];
downloadArtifact: [taskNo: string];
toggleDownloadSelection: [taskNo: string];
/** 文件级生命周期入口;父级只切换工作台展示,不在导航时写入业务状态。 */
openLifecycleStage: [payload: { projection: ShippingProcessingProjection; entry: ShippingProcessingLifecycleEntry }];
/** 单文件低频操作;仅当后端明确授权该动作时才发出。 */
fileAction: [payload: { projection: ShippingProcessingProjection; action: string }];
}>();
const { t, te } = useI18n();
@@ -76,8 +91,17 @@ type WorkbenchFileRow = {
filename?: string | null;
document_id?: number | null;
status_label?: string | null;
po_number?: string | null;
projection?: ShippingProcessingProjection;
};
const LIFECYCLE_STAGE_CODES = ['order_review', 'fulfillment_prep', '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',
upload_complete: 'uploadComplete',
};
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
const activeProjection = computed((): ConversationProcessingProjection | null => (
@@ -100,6 +124,23 @@ const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'waiting_human'));
const processingTasks = computed(() => statusGroups.value?.processing || activeProjection.value?.processing || []);
/** 任务只要含一个命中附件即保留,避免筛选后打散同一封 EML 的上下文。 */
function taskMatchesLifecycleFilter(task: ConversationProcessingUserTask): boolean {
const filter = props.lifecycleFilter || 'all';
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
// 非批次中心保留历史任务卡兼容展示;只有批次中心才按叶子文件筛选。
if (!props.workbenchMode && filter === 'all' && !query) return true;
return workbenchFileRows(task).some((file) => {
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
return !query || [file.filename, file.label, file.po_number]
.some((value) => String(value || '').toLowerCase().includes(query));
});
}
const visibleFailedTasks = computed(() => failedTasks.value.filter(taskMatchesLifecycleFilter));
const visibleWaitingHumanTasks = computed(() => waitingHumanTasks.value.filter(taskMatchesLifecycleFilter));
const visibleProcessingTasks = computed(() => processingTasks.value.filter(taskMatchesLifecycleFilter));
const visibleCompletedTasks = computed(() => completedTasks.value.filter(taskMatchesLifecycleFilter));
/** history 中非取消 →「历史版本」。 */
const historyVersionTasks = computed(() => historyTasks.value.filter(
(task) => String(task.status_label || '').trim().toLowerCase() !== 'cancelled',
@@ -109,6 +150,8 @@ const historyVersionTasks = computed(() => historyTasks.value.filter(
const cancelledHistoryTasks = computed(() => historyTasks.value.filter(
(task) => String(task.status_label || '').trim().toLowerCase() === 'cancelled',
));
const visibleHistoryVersionTasks = computed(() => historyVersionTasks.value.filter(taskMatchesLifecycleFilter));
const visibleCancelledHistoryTasks = computed(() => cancelledHistoryTasks.value.filter(taskMatchesLifecycleFilter));
/** 处理记录标题计数:当前返回的 completed + history。 */
const recordTaskCount = computed(() => (
@@ -249,6 +292,45 @@ function groupTitle(task: ConversationProcessingUserTask): string {
/** 工作台文件行:只展示后端 document objects,避免用任务标题冒充文件。 */
function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const children = task.aggregateChildren || [];
// [AUTHORITY] 批次模式只以实时 work_items 作为文件行真相。Conversation task 的
// children / objects / document_names 是 Run 级兼容快照,可用于非批次卡历史展示,
// 但不得重建批次中的文件名、状态、阶段或操作。
if (props.workbenchMode) {
const taskNo = String(task.user_task_no || '').trim();
const liveLeaves = (props.workItems || []).flatMap((item) => {
const isTaskRoot = String(item.rootOrderTaskNo || '').trim() === taskNo
|| String(item.workItemNo || '').trim() === taskNo;
if (!isTaskRoot) return [];
// EML 父项的实时附件只存在于 aggregateChildren;展开同一份后端 work_item,
// 不读取 conversation task 兼容快照。
return item.sourceType === 'eml'
? flattenBusinessFileProjections([item])
: [item];
}).filter((item) => (
Number(item.sourceSummary?.documentId || 0) > 0
));
const seenLiveDocumentIds = new Set<number>();
const uniqueLiveLeaves = liveLeaves.filter((item) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
if (seenLiveDocumentIds.has(documentId)) return false;
seenLiveDocumentIds.add(documentId);
return true;
});
return uniqueLiveLeaves.map((item, index) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
return {
kind: 'document' as const,
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-live-${item.workItemNo || index}`,
label: filename || item.workItemNo || `文件 ${index + 1}`,
filename: filename || item.workItemNo || `文件 ${index + 1}`,
document_id: documentId || null,
status_label: String(item.uiState?.status || item.userStatus || item.status || ''),
po_number: item.sourceSummary?.poNumber || null,
projection: item,
};
});
}
if (children.length) {
return flattenBusinessFileProjections(children).map((child, index) => {
const filename = String(child.sourceSummary?.filename || '').trim();
@@ -259,6 +341,7 @@ function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileR
label: filename || child.workItemNo || `文件 ${index + 1}`,
filename: filename || child.workItemNo || `文件 ${index + 1}`,
status_label: String(child.uiState?.status || child.userStatus || child.status || ''),
po_number: child.sourceSummary?.poNumber || null,
projection: child,
};
});
@@ -278,6 +361,7 @@ function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileR
filename: item.filename,
document_id: item.document_id,
status_label: item.status_label,
po_number: directFileProjection?.sourceSummary?.poNumber || null,
projection: directFileProjection?.sourceType === 'direct_pdf'
? directFileProjection
: undefined,
@@ -285,15 +369,60 @@ function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileR
}
const taskName = String(task.title || '').trim().toLowerCase();
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
// 新版实时投影可只返回 work_items,不重复旧 task.objects;此时以同一 OT 的叶子
// document 投影生成行,确保文件状态、阶段和按钮仍完全来自后端。
const taskNo = String(task.user_task_no || '').trim();
const liveLeaves = (props.workItems || []).filter((item) => (
String(item.rootOrderTaskNo || '').trim() === taskNo
&& Number(item.sourceSummary?.documentId || 0) > 0
&& !item.childOrderTasks?.length
));
if (liveLeaves.length) {
return liveLeaves.map((item, index) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
return {
kind: 'document' as const,
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-live-${item.workItemNo || index}`,
label: filename || item.workItemNo || `文件 ${index + 1}`,
filename: filename || item.workItemNo || `文件 ${index + 1}`,
document_id: documentId || null,
status_label: String(item.uiState?.status || item.userStatus || item.status || ''),
po_number: item.sourceSummary?.poNumber || null,
projection: item,
};
});
}
return (task.document_names || []).map((filename, index) => ({
kind: 'document' as const,
object_key: `${task.user_task_no}-document-${index}`,
label: filename,
filename,
status_label: task.status_label,
po_number: null,
}));
}
/** 阶段筛选只收窄附件行,EML 卡本身仍保留以便用户识别邮件来源。 */
function visibleWorkbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const filter = props.lifecycleFilter || 'all';
const rows = workbenchFileRows(task);
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
return rows.filter((file) => {
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
if (!query) return true;
return [file.filename, file.label, file.po_number].some((value) => String(value || '').toLowerCase().includes(query));
});
}
function fileDownloadTaskNo(file: WorkbenchFileRow): string | null {
const taskNo = String(file.projection?.rootOrderTaskNo || '').trim();
return taskNo && (props.downloadableTaskNos || []).includes(taskNo) ? taskNo : null;
}
function isDownloadSelected(taskNo: string): boolean {
return (props.selectedDownloadTaskNos || []).includes(taskNo);
}
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
const seen = new Set<string>();
@@ -320,20 +449,51 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
const reason = file.projection.uiState
? file.projection.uiState.blocking_reason
: file.projection.blockingReason;
if (!reason) return '';
const key = String(reason.i18nKey || '').trim();
return key && te(key) ? t(key) : String(reason.code || '').trim();
return resolveShippingProcessingReasonLabel(reason, te, t);
}
return taskReasonLabel(task);
}
/** 附件阶段来自叶子 ui_state;EML 父阶段只适用于 EML 卡,不得复制到不同状态的附件。 */
function workbenchFileStage(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
const stage = file.projection
? (file.projection.uiState?.stage || file.projection.userStage || file.projection.stage)
: stageLabel(task);
const key = shippingProcessingStageKey(String(stage || ''));
return key && te(key) ? t(key) : String(stage || '');
/** 文件工作面显示四阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
function workbenchFileLifecycleStage(file: WorkbenchFileRow): string {
const code = String(file.projection?.uiState?.lifecycleStage || '').trim();
const key = LIFECYCLE_STAGE_LABEL_KEYS[code];
return key
? t(`chat.shippingNoticeUi.stage.${key}`)
: t('chat.shippingProcessing.stageLabel.waiting_system_start');
}
/** 生命周期入口仅消费后端投影;禁止按候选、Case 或阶段顺序二次裁决。 */
function lifecycleEntries(file: WorkbenchFileRow): ShippingProcessingLifecycleEntry[] {
return file.projection?.uiState?.lifecycleEntries || [];
}
function lifecycleEntry(file: WorkbenchFileRow, target: LifecycleStageCode): ShippingProcessingLifecycleEntry | null {
return lifecycleEntries(file).find((entry) => entry.code === target) || null;
}
function lifecycleEntryState(file: WorkbenchFileRow, target: LifecycleStageCode): 'available' | 'current' | 'unavailable' {
const state = lifecycleEntry(file, target)?.state;
// [FAIL-CLOSED] 服务端新增或异常状态不得被 UI 当作可进入工作台。
return state === 'available' || state === 'current' ? state : 'unavailable';
}
function lifecycleEntryLabel(file: WorkbenchFileRow, target: LifecycleStageCode): string {
const stage = t(`chat.shippingNoticeUi.stage.${LIFECYCLE_STAGE_LABEL_KEYS[target]}`);
const state = lifecycleEntryState(file, target);
const stateKey = state === 'current'
? 'chat.shippingOrderReview.lifecycle.current'
: state === 'available'
? 'chat.shippingOrderReview.lifecycle.available'
: 'chat.shippingOrderReview.lifecycle.blocked';
return `${stage} · ${t(stateKey)}`;
}
function onOpenLifecycleStage(file: WorkbenchFileRow, lifecycleStage: LifecycleStageCode) {
const entry = lifecycleEntry(file, lifecycleStage);
if (!file.projection || !entry) return;
if (lifecycleEntryState(file, lifecycleStage) === 'unavailable') return;
emit('openLifecycleStage', { projection: file.projection, entry });
}
/** 叶子文件动作由自身 ui_state 裁决;没有叶子投影时不伪造可操作按钮。 */
@@ -392,11 +552,7 @@ function taskReasonLabel(task: ConversationProcessingUserTask): string {
const reason = task.uiState
? task.uiState.blocking_reason
: task.blockingReason;
if (!reason) return '';
const key = String(reason.i18nKey || '').trim();
if (key && te(key)) return t(key);
// 未升级响应没有 i18n_key 时仅透传后端原因码,不根据文件名、状态或动作伪造说明。
return String(reason.code || '').trim();
return resolveShippingProcessingReasonLabel(reason, te, t);
}
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
@@ -548,7 +704,27 @@ function presentationActionLabel(task: ConversationProcessingUserTask, item: Act
if (key && te(key)) return t(key);
const extractionKey = `chat.shippingOrderExtractionAction.${code}`;
if (te(extractionKey)) return t(extractionKey);
return code;
return t('chat.shippingProcessing.action.unknown');
}
/**
* 文件低频操作优先读取正式 ui_state;旧 availableActions 仅兼容未下发 ui_state 的旧投影。
* 一旦后端提供 ui_state,遗留字段绝不能重新授予已撤销的操作。
*/
function canCancelFile(file: WorkbenchFileRow): boolean {
const projection = file.projection;
if (!projection) return false;
if (projection.uiState) {
return projection.uiState.secondary_actions.some(
(action) => action.enabled && action.code === 'cancel_unit',
);
}
return projection.availableActions.includes('cancel_unit');
}
function onFileAction(file: WorkbenchFileRow, action: string) {
if (!file.projection || action !== 'cancel_unit' || !canCancelFile(file)) return;
emit('fileAction', { projection: file.projection, action });
}
/**
@@ -579,8 +755,7 @@ function toggleHistorySection() {
* Intake 阶段文案。
*/
function intakeStageLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingStageKey(item.stage);
return te(key) ? t(key) : String(item.stage || '');
return resolveShippingProcessingStageLabel(item.stage, te, t);
}
</script>
@@ -591,15 +766,15 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
data-testid="shipping-conversation-processing-card"
>
<section
v-if="failedTasks.length"
v-if="visibleFailedTasks.length"
data-testid="shipping-processing-group-failed"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ t('chat.shippingProcessing.batchWorkbench.groups.failed', { count: groupFileCount(failedTasks) }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.failed', { count: groupFileCount(visibleFailedTasks) }) }}
</div>
<div class="space-y-2">
<article
v-for="task in failedTasks"
v-for="task in visibleFailedTasks"
:key="task.user_task_no"
class="rounded-lg border px-2.5 py-2 transition"
:class="[
@@ -649,13 +824,24 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
</button>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-rose-200/70 pt-2">
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-white/70 px-2 py-2 dark:bg-slate-950/30">
<div class="min-w-0 flex-1">
<div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div>
<div v-if="workbenchFileReason(file, task)" class="mt-0.5 truncate text-[11px] text-rose-600 dark:text-rose-300">{{ workbenchFileReason(file, task) }}</div>
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-white/70 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center dark:bg-slate-950/30" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div>
<div class="flex min-w-0 flex-wrap items-center gap-1">
<span class="w-fit shrink-0 rounded-full bg-rose-100 px-2 py-0.5 font-medium text-rose-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.failedFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md border border-rose-300 px-2 py-0.5 font-medium text-rose-700 hover:bg-rose-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
<label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label>
<button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button>
</div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5">
<div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600 dark:text-rose-300" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div>
<div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div>
<details v-if="canCancelFile(file)" class="relative shrink-0">
<summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary>
<button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button>
</details>
</div>
<span class="shrink-0 rounded-full bg-rose-100 px-2 py-0.5 text-[11px] font-medium text-rose-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.failedFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md border border-rose-300 px-2.5 py-1 text-[11px] font-medium text-rose-700 hover:bg-rose-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
</div>
</div>
<SidebarProgressInline
@@ -666,7 +852,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
/>
<div
v-if="shouldShowTaskLevelActions(task) || (!projectionForTask(task) && canExpandFileDetails(task))"
v-if="shouldShowTaskLevelActions(task) || (!workbenchMode && !projectionForTask(task) && canExpandFileDetails(task))"
class="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1"
data-testid="shipping-processing-task-actions"
>
@@ -686,15 +872,15 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</section>
<section
v-if="waitingHumanTasks.length"
v-if="visibleWaitingHumanTasks.length"
data-testid="shipping-processing-group-waiting_human"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ t('chat.shippingProcessing.batchWorkbench.groups.waitingHuman', { count: groupFileCount(waitingHumanTasks) }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.waitingHuman', { count: groupFileCount(visibleWaitingHumanTasks) }) }}
</div>
<div class="space-y-2">
<article
v-for="task in waitingHumanTasks"
v-for="task in visibleWaitingHumanTasks"
:key="task.user_task_no"
class="rounded-lg border border-amber-400 bg-amber-50/80 px-2.5 py-2 transition dark:border-amber-700 dark:bg-amber-950/30"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -709,13 +895,12 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
</button>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-amber-200/70 pt-2">
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-white/70 px-2 py-2 dark:bg-slate-950/30">
<div class="min-w-0 flex-1">
<div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div>
<div v-if="workbenchFileReason(file, task)" class="mt-0.5 truncate text-[11px] text-rose-600 dark:text-rose-300">{{ workbenchFileReason(file, task) }}</div>
</div>
<span class="shrink-0 rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium text-amber-800">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.waitingFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-white/70 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center dark:bg-slate-950/30" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div>
<div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-amber-100 px-2 py-0.5 font-medium text-amber-800">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.waitingFallback') }}</span><button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md bg-brand-600 px-2 py-0.5 font-medium text-white hover:bg-brand-700" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600 dark:text-rose-300" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div><details v-if="canCancelFile(file)" class="relative shrink-0"><summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary><button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button></details></div>
</div>
</div>
<SidebarProgressInline
@@ -738,15 +923,15 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</section>
<section
v-if="processingTasks.length"
v-if="visibleProcessingTasks.length"
data-testid="shipping-processing-group-processing"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
{{ t('chat.shippingProcessing.batchWorkbench.groups.processing', { count: groupFileCount(processingTasks) }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.processing', { count: groupFileCount(visibleProcessingTasks) }) }}
</div>
<div class="space-y-2">
<article
v-for="task in processingTasks"
v-for="task in visibleProcessingTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:class="focusedTaskNo === task.user_task_no
@@ -790,10 +975,11 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
</button>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-sky-200/70 pt-2">
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-surface-muted/40 px-2 py-2">
<div class="min-w-0 flex-1"><div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div><div class="mt-0.5 text-[11px] text-secondary">{{ workbenchFileStage(file, task) || t('chat.shippingProcessing.batchWorkbench.fileProcessing') }}</div></div>
<span class="shrink-0 rounded-full bg-sky-100 px-2 py-0.5 text-[11px] font-medium text-sky-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.processingFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md border border-brand-300 px-2.5 py-1 text-[11px] font-medium text-brand-700 hover:bg-brand-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-surface-muted/40 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div><div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-sky-100 px-2 py-0.5 font-medium text-sky-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.processingFallback') }}</span><button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md border border-brand-300 px-2 py-0.5 font-medium text-brand-700 hover:bg-brand-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div><details v-if="canCancelFile(file)" class="relative shrink-0"><summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary><button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button></details></div>
</div>
</div>
<SidebarProgressInline
@@ -818,7 +1004,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
</button>
<button
v-if="canExpandFileDetails(task)"
v-if="!workbenchMode && canExpandFileDetails(task)"
type="button"
class="inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
data-testid="shipping-processing-expand-files"
@@ -841,7 +1027,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</button>
</div>
<button
v-else-if="canExpandFileDetails(task)"
v-else-if="!workbenchMode && canExpandFileDetails(task)"
type="button"
class="mt-1.5 inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
data-testid="shipping-processing-expand-files"
@@ -902,7 +1088,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
data-testid="shipping-processing-history-body"
>
<div
v-if="completedTasks.length"
v-if="visibleCompletedTasks.length"
data-testid="shipping-processing-history-completed"
>
<div class="mb-1 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">
@@ -910,7 +1096,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div class="space-y-2">
<article
v-for="task in completedTasks"
v-for="task in visibleCompletedTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -934,6 +1120,14 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
{{ taskReasonLabel(task) }}
</div>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-emerald-200/70 pt-2">
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-emerald-50/40 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div><div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-emerald-100 px-2 py-0.5 font-medium text-emerald-700">{{ workbenchFileStatus(file, task) }}</span><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div></div>
</div>
</div>
<button
v-if="recordViewDetailsItem(task)"
type="button"
@@ -948,7 +1142,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div
v-if="historyVersionTasks.length"
v-if="visibleHistoryVersionTasks.length"
data-testid="shipping-processing-history-versions"
>
<div class="mb-1 text-[11px] font-medium text-slate-600 dark:text-slate-300">
@@ -956,7 +1150,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div class="space-y-2">
<article
v-for="task in historyVersionTasks"
v-for="task in visibleHistoryVersionTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -990,7 +1184,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div
v-if="cancelledHistoryTasks.length"
v-if="visibleCancelledHistoryTasks.length"
data-testid="shipping-processing-history-cancelled"
>
<div class="mb-1 text-[11px] font-medium text-slate-500 dark:text-slate-400">
@@ -998,7 +1192,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div class="space-y-2">
<article
v-for="task in cancelledHistoryTasks"
v-for="task in visibleCancelledHistoryTasks"
:key="task.user_task_no"
class="rounded-lg border border-dashed border-default bg-surface/60 px-2.5 py-2 opacity-90"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -77,6 +77,44 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
});
it('does not present historical handling items or CTA as current work when the live projection exists', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
status: 'review_required',
availableActions: ['review_candidate'],
primaryNotice: 'candidate_confirmation',
handlingItems: [{
category: 'candidate_confirmation', count: 2, reasonCodes: [],
affectedRefs: [], primaryAction: 'review_candidate',
}],
}),
},
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running' },
summary: { total_files: 1, completed_files: 0, waiting_human_files: 0, failed_files: 0 },
status_groups: {
failed: [], waiting_human: [], processing: [{
user_task_no: 'OT-LIVE', title: 'live.pdf', file_count: 1,
userGroup: 'processing', group: 'processing', aggregateChildren: [],
}], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
expect(wrapper.text()).not.toContain('候选待人工确认');
expect(wrapper.find('[data-testid="shipping-order-extraction-handling-summary"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
});
it('collapses file-level progress when the batch workbench is open', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-COMPACT', compactProgress: true },
@@ -206,7 +244,7 @@ describe('ShippingOrderExtractionCard', () => {
await wrapper.get('[data-testid="shipping-order-extraction-eml-failed-INTAKE:SNI-DETAIL"] button').trigger('click');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('failed.pdf');
expect(wrapper.text()).toContain('异常 1');
expect(wrapper.text()).toContain('文件处理需要人工确认');
expect(wrapper.text()).toContain('当前步骤需要人工处理');
expect(wrapper.text()).not.toContain('PARSE_FAILED');
expect(wrapper.get('[data-testid="shipping-order-extraction-child-status-OT-CHILD-1"]')
.classes()).toContain('text-rose-600');
@@ -253,6 +291,8 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.text()).toContain('共 2 个文件');
// 关键断言:待人工处理不是完成,聊天摘要必须与批次中心 completed_files 同口径。
expect(wrapper.text()).toContain('0/2 已处理');
expect(wrapper.text()).not.toContain('共 6 个文件');
expect(wrapper.text()).not.toContain('stale.pdf');
});
@@ -454,7 +494,7 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).toContain('3 个文件');
expect(wrapper.text()).toContain('系统处理中');
expect(wrapper.text()).toContain('处理时间偏长');
expect(wrapper.text()).toContain('查看详情');
expect(wrapper.text()).toContain('打开批次进度中心');
expect(wrapper.text()).not.toContain('刷新状态');
expect(wrapper.text()).not.toContain('取消本次识别');
expect(wrapper.text()).not.toContain('PO-450003.pdf');
@@ -527,7 +567,7 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.text()).toContain('订单候选已生成');
expect(wrapper.text()).toContain('候选待人工确认 · 2 项');
expect(wrapper.text()).toContain('继续处理');
expect(wrapper.text()).toContain('打开批次进度中心');
expect(wrapper.text()).not.toContain('部分附件需人工处理');
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
});
@@ -586,8 +626,8 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).not.toContain('ST-88');
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBe(0);
// 失败优先:唯一主 CTA 为重试解析。
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('重试解析');
// 当前原型将执行入口统一收敛到批次进度中心,旧消息卡不再保留重试 CTA。
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
});
it('keeps only the batch workbench CTA for review-required without retry', () => {
@@ -20,7 +20,10 @@ import type {
} from '../../types/shipping.api.types';
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
import { shippingProcessingStageKey } from '../../shipping/shippingProcessingLabels';
import {
resolveShippingProcessingReasonLabel,
resolveShippingProcessingStageLabel,
} from '../../shipping/shippingProcessingLabels';
import {
listWorkspaceShippingOrderExtractionDocuments,
listWorkspaceShippingOrderExtractionProgressEvents,
@@ -99,65 +102,9 @@ function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]
const projection = statusTaskProjection(task);
if (!projection) return [];
if (projection?.aggregateChildren?.length) return projection.aggregateChildren;
const projectionChildren = (projection?.childOrderTasks || []).map((child) => ({
...projection,
workItemNo: child.orderTaskNo,
status: child.status,
stage: child.stage,
userStatus: child.status === 'completed' ? 'completed' : child.status === 'failed' ? 'failed' : 'running',
userStage: child.stage,
sourceSummary: {
...projection.sourceSummary,
filename: child.orderTaskNo,
documentCount: 1,
},
} as ShippingProcessingProjection));
if (projectionChildren.length) return projectionChildren;
// 系统处理中 work_item 可能只有 EML 摘要;附件真实状态仍由当前 Run 文档列表承载。
const emailName = String(projection.sourceSummary?.filename || task.aggregateSummary?.intakeNo || '').trim().toLowerCase();
const emailRow = emailRows.value.find((row) => (
String(row.fileName || '').trim().toLowerCase() === emailName
|| String(row.intakeId || '').trim() === String(task.aggregateSummary?.intakeNo || '').trim()
));
if (!emailRow) return [];
return childRows(emailRow).map((row) => ({
workItemType: 'order_task',
workItemNo: `DOCUMENT:${row.documentId || row.unitId}`,
sourceType: 'eml',
rootOrderTaskNo: null,
shippingNoticeNo: null,
runNo: props.runNo || props.state.runNo || null,
caseNo: null,
conversationId: null,
submissionNo: '',
intakeNo: String(emailRow.intakeId || task.aggregateSummary?.intakeNo || ''),
status: row.status === 'failed' ? 'failed' : row.status === 'review_required' ? 'waiting_review' : row.status === 'candidate_ready' ? 'completed' : 'processing',
stage: String(row.userVisibleStage || row.status || 'processing'),
progressVersion: 0,
lastActivityAt: '',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: row.fileName,
documentId: row.documentId || null,
documentCount: 1,
parsedDocumentCount: row.status === 'failed' ? 0 : 1,
candidateCount: row.status === 'candidate_ready' ? 1 : 0,
customerName: null,
poNumber: null,
failureReasonCode: row.reasonCode || null,
},
childOrderTasks: [],
userStatus: row.status === 'failed' ? 'failed' : row.status === 'review_required' ? 'waiting_human' : row.status === 'candidate_ready' ? 'completed' : 'running',
userStage: row.userVisibleStage || row.status,
blockingReason: row.explainability?.message ? { code: row.reasonCode || 'DOCUMENT_PROCESSING_FAILED', details: { message: row.explainability.message } } : null,
retryable: false,
primaryAction: null,
facts: { uploadState: row.status === 'candidate_ready' ? 'succeeded' : 'not_created' },
userGroup: null,
} as ShippingProcessingProjection));
// 后端未返回 aggregate_children 时只展示聚合摘要。禁止用 childOrderTasks 或
// 历史聊天 Run 快照重新推导附件、Candidate、阶段或按钮。
return [];
}
function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[]; file_count?: number | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
// EML 是来源容器;统一只计其附件,避免聊天卡与批次中心相差一份 EML 本体。
@@ -183,10 +130,7 @@ function childStatusLabel(child: ShippingProcessingProjection) {
function displayReason(
reason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null,
) {
if (!reason) return '';
const key = String(reason.i18nKey || '').trim();
if (key && te(key)) return t(key);
return String(reason.code || '').trim();
return resolveShippingProcessingReasonLabel(reason, te, t);
}
/** 新投影有 ui_state 时严格消费其状态;旧响应才回退 userStatus / status。 */
function displayProjectionStatus(item: ShippingProcessingProjection): string {
@@ -209,8 +153,7 @@ function taskReason(task: { uiState?: { blocking_reason: import('../../types/shi
}
function childStageLabel(child: ShippingProcessingProjection) {
const stage = String(child.uiState?.stage || child.userStage || child.stage || '').trim();
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
return resolveShippingProcessingStageLabel(stage, te, t);
}
function statusTaskProjection(task: { user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
const items = shippingWorkflow?.processingWorkItems.value || [];
@@ -272,8 +215,7 @@ const emlAggregateChildren = computed(() => emlAggregate.value?.aggregateChildre
const emlAggregateExpanded = ref(false);
function aggregateStageLabel(item: ShippingProcessingProjection): string {
const stage = String(item.uiState ? item.uiState.stage : (item.userStage || item.stage || '')).trim();
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
return resolveShippingProcessingStageLabel(stage, te, t);
}
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
const status = displayProjectionStatus(item);
@@ -303,7 +245,14 @@ const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
const displaySummary = computed(() => props.state.summary);
const handlingItems = computed(() => props.state.handlingItems || []);
/**
* 旧聊天消息中的 handlingItems 是当时的 Run 快照;实时会话投影已返回时,
* 绝不能把它重新展示成当前待办或用它决定 CTA。当前待办仅由后端 work_items
* 与其 ui_state 裁决,旧卡在此模式下只保留历史消息本身。
*/
const handlingItems = computed(() => (
hasConversationStatusGroups.value ? [] : (props.state.handlingItems || [])
));
const fileRows = computed(() => props.state.documents || []);
const isEmailRow = (row: ShippingOrderExtractionFileState) => (
row.documentType === 'email_body' || row.fileName?.toLowerCase().endsWith('.eml')
@@ -356,9 +305,10 @@ const failedRows = computed(() => fileRows.value.filter((row) => (
const processedCount = computed(() => {
if (hasConversationStatusGroups.value) {
const summary = conversationProcessing.value?.summary;
return Math.max(0, Number(summary?.completed_files || 0))
+ Math.max(0, Number(summary?.waiting_human_files || 0))
+ Math.max(0, Number(summary?.failed_files || 0));
// [AUTHORITY] “已处理/完成率”只表示已经完成通知生命周期的业务文件。
// waiting_human / failed 只是后端裁决出的待处理事项,不能借用历史 Run 的
// “处理过”口径累计为完成,否则会与批次进度中心的 completed_files 冲突。
return Math.max(0, Number(summary?.completed_files || 0));
}
return emlAggregate.value?.aggregateSummary?.completed
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments);
@@ -372,7 +322,7 @@ const completedExpanded = ref(false);
/** 新版会话批次的业务文件数由后端汇总;旧 Run 卡仍保留历史兼容计数。 */
const batchFileCount = computed(() => {
if (hasConversationStatusGroups.value) {
return Math.max(0, Number(conversationProcessing.value?.summary.total_files || 0));
return Math.max(0, Number(conversationProcessing.value?.summary?.total_files || 0));
}
return Math.max(0, Number(emlAggregate.value?.sourceSummary.documentCount ?? props.state.summary.totalDocuments));
});
@@ -513,7 +463,7 @@ const handlingSummaryLine = computed(() => {
* 唯一主 CTA:失败→重试解析;需处理→继续处理;否则不展示。
*/
const primaryChatAction = computed((): { kind: 'retry' | 'continue'; label: string } | null => {
if (props.readonly) return null;
if (props.readonly || hasConversationStatusGroups.value) return null;
const actions = props.state.availableActions || [];
const canRetry = actions.includes('retry_failed_attachments')
|| actions.includes('retry_failed_documents')
@@ -735,7 +685,7 @@ async function onPrimaryChatAction() {
</button>
<div class="mt-1 text-xs text-slate-500">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
<div v-if="expandedEmlTasks.has(task.user_task_no)" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
<div class="min-w-0">
<div class="truncate font-medium">{{ child.sourceSummary.filename || child.workItemNo }}</div>
@@ -30,6 +30,7 @@ function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowI
current_run_no: 'SNER-9',
lifecycle_status: 'extracting',
current_stage: 'extracting',
available_actions: ['cancel'],
lock_version: 1,
events: [
{
@@ -113,11 +114,35 @@ describe('ShippingWorkflowItemDetailDrawer', () => {
wrapper.unmount();
});
it('does not infer any write or lifecycle entry from a local file status', () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({
lifecycle_status: 'pending_review',
available_actions: [],
}),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
// 空动作契约表示后端没有授予操作;状态名不得让前端补造入口。
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-action-open-review"]')).toBeNull();
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-item-drawer-reparse"]')).toBeNull();
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).toBeNull();
wrapper.unmount();
});
it('hides cancel for closed items and emits close', async () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({ lifecycle_status: 'closed', closed_reason: 'user_cancelled' }),
item: buildItem({
lifecycle_status: 'closed',
closed_reason: 'user_cancelled',
available_actions: [],
}),
},
global: { plugins: [i18n] },
attachTo: document.body,
@@ -52,17 +52,13 @@ const events = computed((): ShippingWorkflowEvent[] => (
const canCancel = computed(() => {
const actions = props.item?.available_actions;
if (Array.isArray(actions)) return actions.includes('cancel') || Boolean(props.item);
const status = String(props.item?.lifecycle_status || '').trim();
return Boolean(props.item) && !['closed', 'cancelled'].includes(status);
// [AUTHORITY] 文件动作只能由文档级 available_actions 授权;空数组就是明确无权限。
return Array.isArray(actions) && actions.includes('cancel');
});
const canReparse = computed(() => {
const actions = props.item?.available_actions;
if (Array.isArray(actions)) return actions.includes('reparse')
|| ['failed', 'reparse_failed'].includes(String(props.item?.lifecycle_status || '').trim());
// 无契约时 fail-closed,禁止仅凭 pending_review 展示。
return false;
return Array.isArray(actions) && actions.includes('reparse');
});
const reparseActionLabel = computed(() => {
@@ -75,13 +71,8 @@ const reparseActionLabel = computed(() => {
const canOpenReview = computed(() => {
if (!props.item) return false;
const actions = props.item.available_actions;
const status = String(props.item.lifecycle_status || '').trim();
if (Array.isArray(actions)) {
return actions.includes('view_details')
|| actions.includes('enter_manual_review')
|| status === 'pending_review';
}
return status === 'pending_review';
// 生命周期工作台是独立授权,详情/人工复核动作不得隐式升级为生命周期入口。
return Array.isArray(actions) && actions.includes('open_order_review');
});
const filename = computed(() => {
File diff suppressed because it is too large. Load diff
@@ -1,48 +1,50 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「批次进度中心」——OT 任务卡 + 按需展开的文件明细。
* 用途:聊天页右侧「批次进度中心」——后端批次投影、四阶段进度和文件行操作。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
* conversationProcessingProjection、DetailDrawer、ReasonDialog、ProcessGateRecoveryCard。
* ReasonDialog、ProcessGateRecoveryCard。
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
* 文件总览和进度仅消费后端批次 summary;
* mapUserTaskObjectsToFileRows 合成文件行;取消/重识别走 Run API;
* 文件清单消费后端 conversation_processing.status_groups;work_items 仅用于定位同一
* 展示 DTO 的操作对象;整批操作走 Run API,单文件取消走 Unit API;
* 路由 focus_task_no / 服务端 focused_task_no 驱动本地选中卡;
* 详情抽屉仅用列表投影,不再请求 WorkflowItem 详情 API。
* 前端只投影后端阶段与授权动作,不保留文件详情抽屉或本地阶段回退。
*/
<script setup lang="ts">
import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { ChevronDown, ChevronRight, Lock, RefreshCw } from 'lucide-vue-next';
import { downloadWorkspaceShippingExcelFile } from '@/features/chat/shipping/shippingDownload';
import {
downloadWorkspaceShippingExcelFile,
downloadWorkspaceShippingExportArchive,
} from '@/features/chat/shipping/shippingDownload';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import { useShippingProcessGateRecovery } from '@/features/shipping-process-gates/composables/useShippingProcessGateRecovery';
import {
cancelWorkspaceShippingOrderExtractionRun,
cancelWorkspaceShippingOrderExtractionDocument,
reparseWorkspaceShippingOrderExtractionRun,
retryWorkspaceShippingOrderExtractionRun,
retryShippingNoticeIntake,
} from '@/features/chat/api/shipping.api';
import type {
ConversationProcessingUserTask,
LifecycleWorkbenchStage,
ShippingProcessingLifecycleEntry,
ShippingProcessingProjection,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
import {
mapUserTaskObjectsToFileRows,
resolveItemDisplayStatus,
} from '@/features/chat/shipping/conversationProcessingProjection';
import { resolveShippingProcessingMessage } from '@/features/chat/shipping/shippingProcessingLabels';
resolveShippingProcessingMessage,
} from '@/features/chat/shipping/shippingProcessingLabels';
import {
SHIPPING_WORKFLOW_KEY,
useShippingNoticeWorkflow,
type UseShippingNoticeWorkflowReturn,
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
import ShippingConversationProcessingCard from './ShippingConversationProcessingCard.vue';
import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer.vue';
import ShippingWorkflowReasonDialog, {
type ShippingWorkflowReasonAction,
} from './ShippingWorkflowReasonDialog.vue';
@@ -72,13 +74,6 @@ const gateNavigationContext = computed(() => ({
}));
const { submitPrimaryAction: submitGatePrimaryAction } = useShippingProcessGateRecovery();
/**
* Gate「确认客户」:打开对话叠层客户选择弹窗(非跳转复核)。
*/
async function onGateConfirmCustomer(taskNo: string) {
await chatPage?.openShippingCustomerDialog?.(taskNo);
}
const injected = inject(SHIPPING_WORKFLOW_KEY, null);
/** 父级已 provide/传入时本地 composable 以空 conversationId 待机,避免双轮询。 */
const localController = useShippingNoticeWorkflow({
@@ -101,29 +96,25 @@ const collapsed = ref(false);
/** 复核返回对话时展示的聚焦提示(由 focus_notice 触发一次)。 */
const focusTaskBanner = ref<string | null>(null);
const actionBusyItemNo = ref<string | null>(null);
const detailOpen = ref(false);
const detailLoading = ref(false);
const detailItem = ref<ShippingWorkflowItem | null>(null);
const reasonDialogOpen = ref(false);
const reasonDialogAction = ref<ShippingWorkflowReasonAction>('cancel');
const reasonDialogItem = ref<ShippingWorkflowItem | null>(null);
/** 任务级取消:走 Run API,不绑单个 WorkflowItem。 */
const reasonDialogRunNo = ref<string | null>(null);
/** 移除右侧常驻批次与文件列表:文件明细改为进入订单处理工作台后展示。 */
const expandedTask = ref<ConversationProcessingUserTask | null>(null);
/** 文件行仅用于 Gate 恢复卡、路由聚焦匹配 activeItem 与 open_review 动作兜底。 */
const items = computed((): ShippingWorkflowItem[] => (
mapUserTaskObjectsToFileRows(expandedTask.value)
));
/** 单文件取消:仅由后端 cancel_unit 授权的 document_id 赋值。 */
const reasonDialogDocumentId = ref<number | null>(null);
const processingWorkItems = computed((): ShippingProcessingProjection[] => (
Array.isArray(ctl.value.processingWorkItems?.value)
? ctl.value.processingWorkItems.value
: []
));
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 fileSearchQuery = ref('');
const selectedDownloadTaskNos = ref<string[]>([]);
/** 四阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
@@ -134,6 +125,36 @@ const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
function batchFourStageLabelKey(code: string): string {
return BATCH_FOUR_STAGE_I18N_KEYS[code] || code;
}
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete') {
lifecycleFilter.value = lifecycleFilter.value === code ? 'all' : code;
}
/** 阶段卡仅展示后端统计总数;状态、阻塞和推进语义由颜色与边框表达。 */
function stageTotalText(node: NonNullable<typeof batchFourStageNodes.value>[number]): string {
return String(Number(node.summary?.total || 0));
}
/** 下载资格仅来自后端 output_artifacts 的授权动作;筛选仅影响展示,不缩减授权集合。 */
const downloadableTaskNos = computed(() => {
return [...new Set(batchArtifacts.value
.filter((artifact) => artifact.action?.enabled)
.map((artifact) => String(artifact.order_task_no || '').trim())
.filter(Boolean))];
});
const allDownloadableSelected = computed(() => (
downloadableTaskNos.value.length > 0
&& downloadableTaskNos.value.every((taskNo) => selectedDownloadTaskNos.value.includes(taskNo))
));
watch(downloadableTaskNos, (taskNos) => {
selectedDownloadTaskNos.value = selectedDownloadTaskNos.value.filter((taskNo) => taskNos.includes(taskNo));
}, { immediate: true });
function toggleDownloadSelection(taskNo: string) {
if (!downloadableTaskNos.value.includes(taskNo)) return;
selectedDownloadTaskNos.value = selectedDownloadTaskNos.value.includes(taskNo)
? selectedDownloadTaskNos.value.filter((value) => value !== taskNo)
: [...selectedDownloadTaskNos.value, taskNo];
}
function toggleAllDownloadSelections() {
selectedDownloadTaskNos.value = allDownloadableSelected.value ? [] : [...downloadableTaskNos.value];
}
async function downloadBatchArtifact(taskNo: string) {
if (!taskNo) return;
try {
@@ -142,25 +163,29 @@ async function downloadBatchArtifact(taskNo: string) {
msg.error(err instanceof Error ? err.message : t('chat.shippingProcessing.batchWorkbench.artifacts.singleDownloadFailed'));
}
}
/** 批量下载仅遍历后端标记为可下载的产物,单项失败不阻断其余产物。 */
/** 批量下载将后端已授权任务一次归档;不在浏览器循环触发多个下载。 */
async function downloadAllBatchArtifacts() {
const artifacts = batchArtifacts.value.filter((artifact) => artifact.action?.enabled);
if (!artifacts.length) return;
let failed = 0;
for (const artifact of artifacts) {
try {
await downloadWorkspaceShippingExcelFile(artifact.order_task_no);
} catch {
failed += 1;
}
}
if (failed) {
msg.error(t('chat.shippingProcessing.batchWorkbench.artifacts.downloadFailed', { count: failed }));
await downloadBatchArchive(downloadableTaskNos.value);
}
async function downloadSelectedBatchArtifacts() {
await downloadBatchArchive(selectedDownloadTaskNos.value.filter((taskNo) => downloadableTaskNos.value.includes(taskNo)));
}
async function downloadBatchArchive(taskNos: string[]) {
if (!taskNos.length) return;
try {
const { blob, filename } = await downloadWorkspaceShippingExportArchive({ task_nos: taskNos });
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
} catch (err) {
msg.error(err instanceof Error ? err.message : t('chat.shippingProcessing.batchWorkbench.artifacts.downloadFailed', { count: taskNos.length }));
}
}
const processing = computed(() => ctl.value.processing?.value ?? null);
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
const displayProcessing = computed(() => processing.value);
/**
* 批次总览一律按文件计数。会话 summary 中 processing/needs_action 是任务数,
* 不能直接填入原型的“处理中/需处理”文件统计卡。
@@ -248,45 +273,6 @@ const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
const manualRefreshing = computed(() => Boolean(ctl.value.manualRefreshing?.value));
const isRefreshing = computed(() => Boolean(ctl.value.isRefreshing?.value));
const error = computed(() => ctl.value.error.value);
const routeFocusedTaskNo = computed(() => String(
route.query.focus_task_no
|| focusTaskBanner.value
|| displayProcessing.value?.focused_task_no
|| '',
).trim());
/**
* 当前阶段摘要优先跟随路由/服务端聚焦 OT 对应文件行,再回退首个活跃项。
*/
const activeItem = computed(() => {
const focus = routeFocusedTaskNo.value;
if (focus) {
const matched = items.value.find((item) => {
const userTask = String(item.user_task_no || '').trim();
const itemNo = String(item.item_no || '').trim();
return userTask === focus || itemNo === focus;
});
if (matched) return matched;
}
return items.value.find((item) => {
const status = resolveItemDisplayStatus(item);
return status === 'layout_parsing' || status === 'extracting' || status === 'building_order'
|| status === 'inventory_matching' || status === 'generating_excel' || status === 'queued';
}) || items.value.find((item) => resolveItemDisplayStatus(item) === 'pending_review') || items.value[0] || null;
});
/** 任务聚合投影存在时隐藏独立「当前阶段」卡,避免三套状态重复(UI-F04)。 */
const showStandaloneCurrentStage = computed(() => {
const projection = displayProcessing.value;
if (!projection) return true;
return !(
projection.needs_action?.length
|| projection.processing?.length
|| projection.completed?.length
|| projection.history?.length
);
});
/**
* 右侧仍有用户必须持续可见的任务时,禁止收起整个处理面板。
* 核心逻辑:处理中 / 待处理 / 未查看完成均属活跃可见任务;无此类任务才允许收起侧栏。
@@ -325,31 +311,6 @@ watch(
* 文件明细进入订单处理工作台后展示;此处仅保留 Gate 卡与独立 DetailDrawer,避免两套投影矛盾与高度抖动。
*/
function itemActivityLabel(item: ShippingWorkflowItem | null): string {
if (!item) return t('chat.shippingProcessing.emptyCompact');
const status = resolveItemDisplayStatus(item);
const key = `chat.shippingProcessing.activity.${status}`;
return te(key) ? t(key) : statusLabel(status);
}
/**
* 打开当前 PDF 对应的订单处理工作台(fileItems 行)。
* 核心逻辑:复用 Run/Case/文档上下文,避免用户重新寻找待处理文件。
*/
async function openReview(item: ShippingWorkflowItem) {
const runNo = String(item.current_run_no || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingOrderReview.caseRequired'));
return;
}
await pushOrderReviewQuery({
runNo,
documentId: item.current_document_id,
caseNo: item.current_case_no,
taskNo: item.current_task_no,
});
}
/**
* 从 OT 任务投影打开订单处理工作台(无 fileItems 时的生产路径)。
* 核心逻辑:必须有 run_no;缺失时 toast 提示,禁止静默 return。
@@ -378,6 +339,7 @@ async function pushOrderReviewQuery(input: {
documentId?: number | null;
caseNo?: string | null;
taskNo?: string | null;
lifecycleStage?: LifecycleWorkbenchStage;
}) {
const query: Record<string, string> = {
mode: 'order-review',
@@ -391,6 +353,7 @@ async function pushOrderReviewQuery(input: {
if (conversationId) query.conversation_id = conversationId;
const taskNo = String(input.taskNo || route.query.focus_task_no || '').trim();
if (taskNo) query.focus_task_no = taskNo;
if (input.lifecycleStage) query.lifecycle_stage = input.lifecycleStage;
await router.push({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
@@ -398,14 +361,31 @@ async function pushOrderReviewQuery(input: {
});
}
const counts = computed(() => ({
total: items.value.length,
processing: Number(displayProcessing.value?.summary?.processing || 0),
pending_review: Number(displayProcessing.value?.summary?.needs_action || 0),
waiting_manual_upload: 0,
failed: 0,
completed: Number(displayProcessing.value?.summary?.completed || 0),
}));
/** 聚合任务卡内的文件入口:只接收叶子投影提供的深链上下文。 */
async function onOpenLifecycleStage(payload: {
projection: ShippingProcessingProjection;
entry: ShippingProcessingLifecycleEntry;
}) {
const item = payload.projection;
const entry = payload.entry;
// 文件行深链必须携带后端 lifecycle entry;阶段码本身不构成授权。
if (
entry.targetSurface !== 'order_lifecycle_workbench'
|| (entry.state !== 'current' && entry.state !== 'available')
) return;
const runNo = String(item.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable'));
return;
}
await pushOrderReviewQuery({
runNo,
documentId: item.sourceSummary?.documentId,
caseNo: item.caseNo,
taskNo: item.rootOrderTaskNo || item.workItemNo,
lifecycleStage: entry.code,
});
}
/**
/**
@@ -419,31 +399,17 @@ async function onProcessingFocus(taskNo: string) {
}
/**
* 展开文件详情 → 保留本地聚焦并打开文件级详情抽屉。
* 文件明细在工作台展示;此处额外打开详情抽屉供复核线框与测试断言。
* 无 run_no 时 toast 提示,禁止静默 return。
* 旧文件详情入口已下线:批次中心的文件行直接承载阶段入口与更多操作。
*/
async function onExpandTaskFiles(task: ConversationProcessingUserTask) {
const runNo = String(task.run_no || '').trim();
expandedTask.value = task;
// 打开文件明细抽屉:优先选与 run_no 匹配的 item,否则取 items[0] 兜底
if (items.value.length) {
const target = runNo
? items.value.find((row) => String(row.current_run_no || '').trim() === runNo)
: items.value[0];
if (target) {
detailItem.value = target;
detailOpen.value = true;
}
}
// 仅展开本地详情;进入订单处理工作台由抽屉中的显式「打开复核」动作触发。
await onProcessingFocus(task.user_task_no);
}
/**
* 收起文件详情:仅清空本地过滤聚焦态,右侧不再常驻文件长列表。
*/
function onCollapseTaskFiles() {
expandedTask.value = null;
return;
}
/**
@@ -476,8 +442,8 @@ async function onProcessingIntakeAction(payload: {
}
/**
* 任务级权威操作:查看详情 / 复核 / 取消 / 重试失败文件。
* 查看详情仅打开本地抽屉,禁止写 viewed 后重算右侧业务投影。
* 任务级权威操作:聚焦 / 复核 / 整批取消 / 重试。
* 文件详情已下线;所有文件级动作由叶子投影的 fileAction 处理。
*/
async function onProcessingTaskAction(payload: {
task: ConversationProcessingUserTask;
@@ -487,7 +453,7 @@ async function onProcessingTaskAction(payload: {
const task = payload.task;
const runNo = String(task.run_no || '').trim();
if (action === 'view_details') {
onExpandTaskFiles(task);
await onProcessingFocus(task.user_task_no);
return;
}
if (
@@ -496,15 +462,6 @@ async function onProcessingTaskAction(payload: {
|| action === 'open_order_review'
|| action === 'open_order_processing'
) {
const target = items.value.find((item) => (
String(item.current_run_no || '').trim() === runNo
&& resolveItemDisplayStatus(item) === 'pending_review'
)) || items.value.find((item) => String(item.current_run_no || '').trim() === runNo);
if (target) {
await openReview(target);
return;
}
// 无 fileItems 时直接用任务投影打开复核(生产主路径)。
await openReviewFromTask(task);
return;
}
@@ -517,9 +474,7 @@ async function onProcessingTaskAction(payload: {
msg.warning(t('chat.shippingOrderReview.caseRequired'));
return;
}
const target = items.value.find((item) => String(item.current_run_no || '').trim() === runNo);
if (target) openReparseDialog(target);
else msg.warning(t('chat.shippingOrderReview.caseRequired'));
openReparseRunDialog(runNo);
return;
}
if (action === 'retry_parse' || action === 'retry') {
@@ -577,25 +532,6 @@ async function onProcessingTaskAction(payload: {
}
}
/**
* 列表主标题:优先文件名。
*/
function itemTitle(item: ShippingWorkflowItem): string {
const filename = String(item.current_document_filename || '').trim();
if (filename) return filename;
return t('chat.shippingProcessing.filenameFallback', {
docId: item.current_document_id,
});
}
/**
* 解析生命周期状态文案。
*/
function statusLabel(status: string): string {
const key = `chat.shippingProcessing.itemStatus.${status}`;
return te(key) ? t(key) : t('chat.shippingProcessing.itemStatus.unknown');
}
/**
* 手动刷新。
*/
@@ -606,35 +542,43 @@ async function onRefresh() {
/**
* 打开取消原因弹窗:优先绑定 current_run_no,走 Run 级取消 API。
*/
function openCancelDialog(item: ShippingWorkflowItem) {
const runNo = String(item.current_run_no || '').trim();
reasonDialogItem.value = item;
reasonDialogRunNo.value = runNo || null;
reasonDialogAction.value = 'cancel';
reasonDialogOpen.value = true;
}
/**
* 打开任务级取消原因弹窗(Run 级 API)。
*/
function openCancelRunDialog(runNo: string) {
reasonDialogItem.value = null;
reasonDialogRunNo.value = String(runNo || '').trim() || null;
reasonDialogDocumentId.value = null;
reasonDialogAction.value = 'cancel';
reasonDialogOpen.value = true;
}
/**
* 打开重识别原因弹窗:优先绑定 current_run_no,走 Run 级 reparse API。
* 打开重识别原因弹窗:走 Run 级 reparse API。
*/
function openReparseDialog(item: ShippingWorkflowItem) {
const runNo = String(item.current_run_no || '').trim();
reasonDialogItem.value = item;
reasonDialogRunNo.value = runNo || null;
function openReparseRunDialog(runNo: string) {
reasonDialogRunNo.value = String(runNo || '').trim() || null;
reasonDialogDocumentId.value = null;
reasonDialogAction.value = 'reparse';
reasonDialogOpen.value = true;
}
/**
* 文件级取消:只能接受后端叶子投影明确授予的 cancel_unit。
*/
function onProcessingFileAction(payload: {
projection: ShippingProcessingProjection;
action: string;
}) {
if (payload.action !== 'cancel_unit') return;
const runNo = String(payload.projection.runNo || '').trim();
const documentId = Number(payload.projection.sourceSummary?.documentId || 0);
if (!runNo || documentId <= 0) {
msg.warning(t('chat.shippingProcessing.cancelTaskMissingRun'));
return;
}
reasonDialogRunNo.value = runNo;
reasonDialogDocumentId.value = documentId;
reasonDialogAction.value = 'cancel';
reasonDialogOpen.value = true;
}
/**
* 将重新识别失败转换为可执行提示,而不是直接展示内部配置错误。
* @param error - API 层 BusinessError 或未知异常
@@ -666,12 +610,11 @@ function reparseErrorMessage(error: unknown): { title: string; message: string }
}
/**
* 原因弹窗确认:取消/重识别一律走订单抽取 Run API(不再调用 Workflow Item ledger)。
* 原因弹窗确认:单文件取消走 Unit API;整批取消与重识别走 Run API。
*/
async function onReasonConfirm(payload: { reason: string; comment?: string }) {
const runNo = String(reasonDialogRunNo.value || reasonDialogItem.value?.current_run_no || '').trim();
const item = reasonDialogItem.value;
const itemNo = String(item?.item_no || '').trim();
const runNo = String(reasonDialogRunNo.value || '').trim();
const documentId = reasonDialogDocumentId.value;
if (!runNo || actionBusyItemNo.value) return;
actionBusyItemNo.value = runNo;
try {
@@ -688,23 +631,21 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
comment,
});
} else {
await cancelWorkspaceShippingOrderExtractionRun(runNo, {
reason: payload.reason,
});
if (documentId && documentId > 0) {
await cancelWorkspaceShippingOrderExtractionDocument(runNo, documentId, { reason: payload.reason });
} else {
await cancelWorkspaceShippingOrderExtractionRun(runNo, { reason: payload.reason });
}
}
await ctl.value.refresh();
reasonDialogOpen.value = false;
reasonDialogItem.value = null;
reasonDialogRunNo.value = null;
if (itemNo && detailItem.value?.item_no === itemNo) {
detailOpen.value = false;
detailItem.value = null;
}
reasonDialogDocumentId.value = null;
} catch (err) {
// 失败时关闭原因确认框,避免与错误提示双遮罩。
reasonDialogOpen.value = false;
reasonDialogItem.value = null;
reasonDialogRunNo.value = null;
reasonDialogDocumentId.value = null;
msg.error(reparseErrorMessage(err));
} finally {
actionBusyItemNo.value = null;
@@ -723,12 +664,55 @@ async function onTaskProjectionAction(payload: {
const { projection, item } = payload;
const taskNo = String(projection.workItemNo || '').trim();
const code = String(item.actionCode || '').trim();
/**
* 跳转目标完全由后端 ui_state 声明;必须匹配用户实际点击的主/次动作。
* 否则次动作虽已完成 Projection 透传,仍会误落入旧的“查看结果”处理分支。
*/
const authoritativeAction = [
projection.uiState?.primary_action,
...(projection.uiState?.secondary_actions || []),
].find((action) => (
action?.code === code
&& action.executionMode === 'navigate'
&& action.targetSurface === 'order_lifecycle_workbench'
&& action.targetLifecycleStage
));
if (
authoritativeAction?.code === code
&& authoritativeAction.executionMode === 'navigate'
&& authoritativeAction.targetSurface === 'order_lifecycle_workbench'
&& authoritativeAction.targetLifecycleStage
) {
const runNo = String(projection.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable'));
return;
}
await pushOrderReviewQuery({
runNo,
documentId: projection.sourceSummary?.documentId,
caseNo: projection.caseNo,
taskNo: projection.rootOrderTaskNo || taskNo,
lifecycleStage: authoritativeAction.targetLifecycleStage,
});
return;
}
if (code === 'reparse') {
const task = [
...(displayProcessing.value?.needs_action || []),
...(displayProcessing.value?.processing || []),
].find((row) => String(row.user_task_no || '').trim() === taskNo);
if (task) void onProcessingTaskAction({ task, action: 'reparse' });
if (task) {
void onProcessingTaskAction({ task, action: 'reparse' });
return;
}
// 文件叶子没有父任务同名 workItemNo;仅使用后端下发的当前 Run,不反推任务或阶段。
const runNo = String(projection.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
return;
}
openReparseRunDialog(runNo);
return;
}
if (code === 'retry_inventory_preparation') {
@@ -747,8 +731,26 @@ async function onTaskProjectionAction(payload: {
}
return;
}
if (code === 'retry_parse' || item.intent === 'retry') {
void onProcessingIntakeAction({ item: projection, action: code || 'retry_parse' });
if (code === 'retry_parse') {
void onProcessingIntakeAction({ item: projection, action: code });
return;
}
if (code === 'retry' || item.intent === 'retry') {
const runNo = String(projection.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
return;
}
if (actionBusyItemNo.value) return;
actionBusyItemNo.value = runNo;
try {
await retryWorkspaceShippingOrderExtractionRun(runNo);
await ctl.value.refresh();
} catch (err) {
msg.error(reparseErrorMessage(err));
} finally {
actionBusyItemNo.value = null;
}
return;
}
if (item.intent === 'refresh') {
@@ -788,17 +790,21 @@ async function onTaskProjectionAction(payload: {
].find((row) => String(row.user_task_no || '').trim() === taskNo);
if (task) {
await onProcessingFocus(taskNo);
await onExpandTaskFiles(task);
return;
}
// 未获得后端导航目标且无法关联父任务时,必须可见地失败,禁止静默无响应。
msg.warning(t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable'));
return;
}
if (item.intent === 'open_manual_upload' && taskNo) {
void router.push({
name: 'workspace-shipping-my-tasks',
query: { task_no: taskNo },
query: { task_no: projection.rootOrderTaskNo || taskNo },
});
return;
}
// 其余 intent 由任务卡/ Gate 卡片承载,此处安全 no-op。
// 未注册的旧动作不得静默吞掉,也不在此处伪造业务写操作。
msg.warning(t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable'));
}
watch(
@@ -906,8 +912,8 @@ watch(
</template>
<template v-else>
{{ t('chat.shippingProcessing.compactSummary', {
active: items.length,
total: counts.total,
active: 0,
total: 0,
}) }}
</template>
</div>
@@ -962,48 +968,34 @@ watch(
</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">
<div v-for="node in batchFourStageNodes" :key="node.code" class="rounded-lg border px-2 py-2 text-center text-xs" :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'">
{{ t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(node.code)}`) }}
</div>
<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>
<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>
<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">
{{ t('chat.shippingProcessing.batchWorkbench.unclassified', { count: displayProcessing?.unclassified_summary?.count }) }}
</p>
</section>
<section
class="mb-4 rounded-xl border border-default bg-surface p-4"
data-testid="shipping-workflow-batch-artifacts"
class="mb-3 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-default bg-surface px-3 py-2"
data-testid="shipping-workflow-file-toolbar"
>
<div class="flex items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-primary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.title') }}</h3>
</div>
<button
type="button"
class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="!batchArtifacts.some((artifact) => artifact.action.enabled)"
data-testid="shipping-workflow-batch-artifact-download"
@click="downloadAllBatchArtifacts"
>
{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadAll') }}
</button>
<label class="relative block min-w-48 flex-1 sm:max-w-sm">
<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">
<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>
<button type="button" class="rounded-md bg-brand-600 px-2.5 py-1 text-xs font-medium text-white disabled:opacity-50" :disabled="!downloadableTaskNos.length" data-testid="shipping-workflow-download-all" @click="downloadAllBatchArtifacts">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadAll') }}</button>
</div>
<div v-if="batchArtifacts.length" class="mt-3 divide-y divide-default">
<div v-for="artifact in batchArtifacts" :key="artifact.order_task_no" class="flex items-center justify-between gap-3 py-2 text-xs">
<span class="truncate text-primary">{{ artifact.filename }}</span>
<div class="flex shrink-0 items-center gap-2">
<span class="text-emerald-700">{{ artifact.status }}</span>
<button
type="button"
class="rounded px-2 py-1 font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50"
:disabled="!artifact.action.enabled"
:data-testid="`shipping-workflow-batch-artifact-download-${artifact.order_task_no}`"
@click="downloadBatchArtifact(artifact.order_task_no)"
>
{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}
</button>
</div>
</div>
</div>
<p v-else class="mt-3 text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.empty') }}</p>
</section>
<div
@@ -1020,29 +1012,22 @@ watch(
:work-items="processingWorkItems"
:conversation-id="conversationId"
:workbench-mode="true"
:lifecycle-filter="lifecycleFilter"
:file-search-query="fileSearchQuery"
:downloadable-task-nos="downloadableTaskNos"
:selected-download-task-nos="selectedDownloadTaskNos"
:has-more-history="Boolean(displayProcessing?.summary?.has_more_history)"
@expand-files="onExpandTaskFiles"
@collapse-files="onCollapseTaskFiles"
@task-action="(payload) => void onProcessingTaskAction(payload)"
@intake-action="(payload) => void onProcessingIntakeAction(payload)"
@projection-action="onTaskProjectionAction"
@file-action="onProcessingFileAction"
@download-artifact="downloadBatchArtifact"
@toggle-download-selection="toggleDownloadSelection"
@open-lifecycle-stage="onOpenLifecycleStage"
/>
<section
v-if="!displayProcessing && showStandaloneCurrentStage"
class="mb-3 rounded-xl border border-brand-200 bg-brand-50/60 p-3 dark:border-brand-900/60 dark:bg-brand-950/20"
data-testid="shipping-workflow-current-stage"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="text-[11px] font-medium uppercase tracking-wide text-brand-700 dark:text-brand-300">{{ t('chat.shippingProcessing.activity.currentStageTitle') }}</div>
<div class="mt-1 text-sm font-semibold text-primary">{{ itemActivityLabel(activeItem) }}</div>
<div v-if="activeItem" class="mt-1 truncate text-[11px] text-secondary">{{ itemTitle(activeItem) }}</div>
</div>
<span class="shrink-0 rounded-full bg-white/80 px-2 py-1 text-[11px] font-medium text-brand-700 dark:bg-slate-900/60 dark:text-brand-200">{{ activeItem ? statusLabel(resolveItemDisplayStatus(activeItem)) : t('chat.shippingProcessing.emptyCompact') }}</span>
</div>
</section>
<div
v-if="error === 'network_recoverable'"
class="mb-3 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
@@ -1057,66 +1042,8 @@ watch(
{{ error }}
</div>
<!-- 侧栏内直接展示阻断 Gate 与文件明细,避免重复弹层。 -->
<div
v-if="!displayProcessing"
class="space-y-2"
data-testid="shipping-workflow-compact-gates"
>
<ProcessGateRecoveryCard
v-for="item in items.filter((row) => row.process_gate?.current_blocking_gate)"
:key="`gate-${item.item_no}`"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
</div>
<!-- 聚焦任务下的文件行列表:供跨 Run 合并与文件筛选断言。 -->
<ul
v-if="!displayProcessing && expandedTask && items.length"
class="my-3 space-y-1.5"
>
<li
v-for="row in items"
:key="row.item_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2 text-[11px] text-secondary"
:data-testid="`shipping-workflow-item-${row.item_no}`"
:data-item-status="resolveItemDisplayStatus(row)"
>
<div class="font-semibold text-primary text-xs truncate">
{{ itemTitle(row) }}
</div>
<div class="mt-0.5 truncate">
{{ statusLabel(resolveItemDisplayStatus(row)) }}
</div>
</li>
</ul>
</div>
<!--
方案 7:移除右侧常驻「批次与文件列表」聚合抽屉,避免与任务卡投影矛盾与高度抖动。
文件明细统一在订单处理工作台展示;任务卡仅显示任务名 / 文件数 / 状态 / 主按钮。
Gate 级阻断与进度详情仍通过 ProcessGateRecoveryCard 与 ShippingWorkflowItemDetailDrawer 呈现。
-->
<ShippingWorkflowItemDetailDrawer
:open="detailOpen"
:item="detailItem"
:loading="detailLoading"
:cancelling="Boolean(detailItem && actionBusyItemNo === detailItem.item_no && reasonDialogAction === 'cancel')"
:reparsing="Boolean(detailItem && actionBusyItemNo === detailItem.item_no && reasonDialogAction === 'reparse')"
@close="detailOpen = false; detailItem = null"
@cancel="openCancelDialog"
@reparse="openReparseDialog"
@open-review="(row) => openReview(row)"
@refreshed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<ShippingWorkflowReasonDialog
v-model="reasonDialogOpen"
:action="reasonDialogAction"