feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

@@ -77,6 +77,35 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
);
/** 同一 Run 只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
const current = items[index];
if (!current?.shipping_order_extraction_state) return false;
const payload = current.payload && typeof current.payload === 'object'
? current.payload as Record<string, unknown>
: {};
const identity = String(
payload.order_extraction_run_no
|| payload.formId
|| current.shipping_order_extraction_state.runNo
|| '',
).trim();
if (!identity) return false;
return items.slice(index + 1).some((candidate) => {
if (!candidate?.shipping_order_extraction_state) return false;
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
? candidate.payload as Record<string, unknown>
: {};
const candidateIdentity = String(
candidatePayload.order_extraction_run_no
|| candidatePayload.formId
|| candidate.shipping_order_extraction_state.runNo
|| '',
).trim();
return candidateIdentity === identity;
});
};
/**
* 标记“当前消息后面是否还存在新的 assistant 消息”。
* 核心逻辑:培训题卡属于“最新一张 assistant 题卡”才能继续交互;
@@ -111,7 +140,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
<template v-for="(msg, index) in messages" :key="getMessageKey(msg, index)">
<ChatMessageBubble
v-if="shouldRenderMessage(msg)"
v-if="shouldRenderMessage(msg) && !isDuplicateShippingExtractionMessage(messages, index)"
:message="msg"
:index="index"
:message-count="messages.length"
@@ -84,11 +84,11 @@ type MaintenanceRecordPanelCommand = {
const page = useChatPageContext();
const shippingWorkflow = useShippingNoticeWorkflow({
const shippingProcessing = useShippingNoticeWorkflow({
conversationId: () => page.conversationId,
refreshTrigger: () => page.workflowRefreshTrigger,
});
provide(SHIPPING_WORKFLOW_KEY, shippingWorkflow);
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
const route = useRoute();
@@ -155,12 +155,7 @@ const activeExtractionRunNo = computed(() => {
const showShippingWorkflowTimeline = computed(() => (
page.isShippingNoticeAgent
&& Boolean(
page.conversationId
|| page.shippingBatchSummary
|| page.shippingConversationWorkspace?.batches?.length
|| activeExtractionRunNo.value
)
&& Boolean(page.conversationId || activeExtractionRunNo.value)
));
const embeddedIframeSrc = computed(() => {
@@ -673,7 +668,7 @@ watch(() => page.currentAgentId, () => {
v-if="showShippingWorkflowTimeline"
:conversation-id="page.conversationId"
:refresh-trigger="page.workflowRefreshTrigger"
:controller="shippingWorkflow"
:controller="shippingProcessing"
/>
@@ -134,6 +134,10 @@ const shippingOrderExtractionRunNo = computed(() => {
: {};
return String(payload.order_extraction_run_no || '').trim();
});
const shippingOrderExtractionReadonly = computed(() => (
shippingOrderExtractionState.value?.isCurrent === false
|| Boolean(shippingOrderExtractionState.value?.supersedingRunNo)
));
/** 失败卡片复用原 Run 重试;按钮本地防重,成功后状态卡由 Run 轮询原位更新。 */
const retryShippingOrderExtraction = async () => {
if (!shippingOrderExtractionRunNo.value || retryingOrderExtraction.value) return;
@@ -690,6 +694,8 @@ function handleInlineDownload(file: InlineDownloadFile): void {
v-if="shippingOrderExtractionState"
:state="shippingOrderExtractionState"
:run-no="shippingOrderExtractionRunNo"
:readonly="shippingOrderExtractionReadonly"
:readonly-reason="shippingOrderExtractionState?.readOnlyReason"
:retrying="retryingOrderExtraction"
:refreshing="refreshingOrderExtraction"
:cancelling="cancellingOrderExtraction"
@@ -0,0 +1,326 @@
<!--
features/chat/components/shipping-review/ReviewAuditTrailDrawer.vue
用途:复核 Case 业务审计时间线按需抽屉(含变更前后快照与字段差异)。
依赖:vue-i18n、listWorkspaceShippingOrderReviewAuditTimeline。
逻辑:open 时拉取第一页;展开优先展示业务可读差异(字段名/前后值/原因);
原始 JSON 折叠为技术详情;敏感事件显示脱敏提示。
-->
<script setup lang="ts">
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { listWorkspaceShippingOrderReviewAuditTimeline } from '@/features/chat/api/shipping.api';
import type { ShippingOrderReviewAuditTimelineItem } from '@/features/chat/types/shipping.api.types';
type AuditDiffRow = {
key?: string;
path?: string;
field?: string;
label?: string;
change?: string;
before?: unknown;
after?: unknown;
};
const props = defineProps<{
open: boolean;
caseNo: string;
}>();
const emit = defineEmits<{
close: [];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const items = ref<ShippingOrderReviewAuditTimelineItem[]>([]);
const loading = ref(false);
const page = ref(1);
const total = ref(0);
const expandedId = ref<number | null>(null);
const pageSize = 50;
/**
* 格式化审计时间。
*/
function formatTime(value: string | null | undefined): string {
if (!value) return '—';
const date = new Date(value);
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}
/**
* 事件类型本地化。
*/
function eventLabel(item: ShippingOrderReviewAuditTimelineItem): string {
const eventType = String(item.event_type || item.action || '').trim();
const key = `chat.shippingOrderReview.auditTrail.events.${eventType}`;
if (eventType && te(key)) return t(key);
return eventType || t('chat.shippingOrderReview.auditTrail.unknownEvent');
}
/**
* 将审计标量格式化为业务可读短文本。
*/
function formatScalar(value: unknown): string {
if (value == null || value === '') return '—';
if (typeof value === 'boolean') {
return value
? t('chat.shippingOrderReview.auditTrail.boolTrue')
: t('chat.shippingOrderReview.auditTrail.boolFalse');
}
if (typeof value === 'object') {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
return String(value);
}
/**
* 快照/差异技术详情(原始 JSON)。
*/
function formatJson(value: unknown): string {
if (value == null) return '—';
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
/**
* 复制技术详情 JSON 到剪贴板。
*/
async function copyJson(value: unknown) {
const text = formatJson(value);
try {
await navigator.clipboard.writeText(text);
msg.success(t('chat.shippingOrderReview.auditTrail.copyDone'));
} catch {
msg.warning(t('chat.shippingOrderReview.auditTrail.copyFailed'));
}
}
/**
* 差异字段业务名称(优先 label/field,其次 path)。
*/
function diffFieldLabel(row: AuditDiffRow): string {
const label = String(row.label || row.field || row.key || row.path || '').trim();
return label || t('chat.shippingOrderReview.auditTrail.unknownField');
}
/**
* 规范化差异列表,供业务表格渲染。
*/
function normalizeDiffRows(diff: unknown): AuditDiffRow[] {
if (!Array.isArray(diff)) return [];
return diff.filter((row): row is AuditDiffRow => Boolean(row) && typeof row === 'object');
}
/**
* 切换条目展开。
*/
function toggleExpand(id: number) {
expandedId.value = expandedId.value === id ? null : id;
}
/**
* 拉取指定页审计条目并合并。
*/
async function loadPage(nextPage: number, append = false) {
if (!props.caseNo || loading.value) return;
loading.value = true;
try {
const result = await listWorkspaceShippingOrderReviewAuditTimeline(props.caseNo, {
page: nextPage,
page_size: pageSize,
});
total.value = result.total;
page.value = result.page;
items.value = append ? [...items.value, ...result.items] : result.items;
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.auditTrail.loadFailed'));
msg.warning(message);
} finally {
loading.value = false;
}
}
/**
* 打开抽屉时重置并加载第一页。
*/
watch(
() => [props.open, props.caseNo] as const,
([isOpen, caseNo]) => {
if (!isOpen || !caseNo) return;
items.value = [];
page.value = 1;
total.value = 0;
expandedId.value = null;
void loadPage(1, false);
},
);
/**
* 加载下一页。
*/
function loadMore() {
if (items.value.length >= total.value) return;
void loadPage(page.value + 1, true);
}
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
data-testid="review-audit-trail-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-xl flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.auditTrail.title') }}</h2>
<p class="text-[11px] text-muted">{{ t('chat.shippingOrderReview.auditTrail.subtitle') }}</p>
</div>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-audit-trail-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<p v-if="loading && !items.length" class="text-sm text-muted">
{{ t('chat.shippingOrderReview.auditTrail.loading') }}
</p>
<p v-else-if="!items.length" class="text-sm text-muted">
{{ t('chat.shippingOrderReview.auditTrail.empty') }}
</p>
<ol v-else class="space-y-3">
<li
v-for="item in items"
:key="item.id"
class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-950/40"
:data-testid="`review-audit-item-${item.id}`"
>
<button
type="button"
class="flex w-full flex-wrap items-center justify-between gap-2 text-left"
@click="toggleExpand(item.id)"
>
<span class="font-medium text-primary">{{ eventLabel(item) }}</span>
<time class="text-[10px] text-muted">{{ formatTime(item.created_at) }}</time>
</button>
<div class="mt-1 space-y-0.5 text-muted">
<p v-if="item.actor_display || item.actor_type">
{{ t('chat.shippingOrderReview.auditTrail.actor', {
actor: item.actor_display || item.actor_type || '—',
}) }}
</p>
<p v-if="item.task_no">
{{ t('chat.shippingOrderReview.auditTrail.taskNo', { taskNo: item.task_no }) }}
</p>
<p v-if="item.result">
{{ t('chat.shippingOrderReview.auditTrail.result', { result: item.result }) }}
</p>
<p v-if="item.error_code" class="text-rose-700 dark:text-rose-300">
{{ item.error_code }}
</p>
<p v-if="item.reason" class="text-secondary">{{ item.reason }}</p>
</div>
<div
v-if="expandedId === item.id"
class="mt-2 space-y-2 border-t border-slate-200 pt-2 dark:border-slate-800"
data-testid="review-audit-item-details"
>
<p v-if="item.sensitive_redacted" class="text-amber-800 dark:text-amber-200">
{{ t('chat.shippingOrderReview.auditTrail.sensitiveRedacted') }}
</p>
<template v-else>
<div v-if="normalizeDiffRows(item.diff).length" data-testid="review-audit-business-diff">
<p class="mb-1 font-medium text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.diff') }}
</p>
<ul class="space-y-1.5">
<li
v-for="(row, idx) in normalizeDiffRows(item.diff)"
:key="idx"
class="rounded bg-white px-2 py-1.5 text-[11px] dark:bg-slate-900"
>
<p class="font-medium text-primary">{{ diffFieldLabel(row) }}</p>
<p class="mt-0.5 text-muted">
{{ t('chat.shippingOrderReview.auditTrail.beforeValue') }}:
<span class="text-secondary">{{ formatScalar(row.before) }}</span>
</p>
<p class="text-muted">
{{ t('chat.shippingOrderReview.auditTrail.afterValue') }}:
<span class="text-secondary">{{ formatScalar(row.after) }}</span>
</p>
</li>
</ul>
</div>
<p v-if="item.reason" class="text-[11px] text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.reason') }}:{{ item.reason }}
</p>
<details class="rounded border border-slate-200 dark:border-slate-800">
<summary class="cursor-pointer px-2 py-1 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.auditTrail.technicalDetails') }}
</summary>
<div class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-800">
<div class="flex items-center justify-between gap-2">
<p class="font-medium text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.before') }}
</p>
<button
type="button"
class="rounded border border-slate-300 px-1.5 py-0.5 text-[11px] hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-audit-copy-before"
@click="copyJson(item.before_snapshot)"
>
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
</button>
</div>
<pre class="max-h-32 overflow-auto rounded bg-white p-2 text-xs leading-relaxed dark:bg-slate-900">{{ formatJson(item.before_snapshot) }}</pre>
<div class="flex items-center justify-between gap-2">
<p class="font-medium text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.after') }}
</p>
<button
type="button"
class="rounded border border-slate-300 px-1.5 py-0.5 text-[11px] hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-audit-copy-after"
@click="copyJson(item.after_snapshot)"
>
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
</button>
</div>
<pre class="max-h-32 overflow-auto rounded bg-white p-2 text-xs leading-relaxed dark:bg-slate-900">{{ formatJson(item.after_snapshot) }}</pre>
</div>
</details>
</template>
</div>
</li>
</ol>
<button
v-if="items.length < total"
type="button"
class="mt-3 w-full rounded border border-slate-300 px-2 py-1.5 text-xs hover:bg-slate-50 disabled:opacity-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-audit-trail-load-more"
:disabled="loading"
@click="loadMore"
>
{{ loading ? t('chat.shippingOrderReview.auditTrail.loading') : t('chat.shippingOrderReview.auditTrail.loadMore') }}
</button>
</div>
</aside>
</div>
</template>
@@ -0,0 +1,57 @@
/**
* features/chat/components/shipping-review/ReviewAutomationStatusPanel.spec.ts
* 用途:锁定自动处理状态仅在建单后展示,并保持阶段顺序一致。
* 依赖:vitest、@vue/test-utils、vue-i18n。
* 逻辑:上游未开始时,下游即使后端旧投影为 passed 也按未开始展示。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewAutomationStatusPanel from './ReviewAutomationStatusPanel.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
automationStatus: {
title: '自动处理状态',
subtitle: '状态',
statuses: { not_started: '未开始', passed: '已通过' },
},
},
},
},
},
});
const processGate = {
execution_no: 'EX-1',
status: 'pending',
gates_track: [
{ gate_code: 'document', label: '文档解析', status: 'not_started', sequence_no: 1 },
{ gate_code: 'reservation', label: '预约校验', status: 'passed', sequence_no: 2 },
],
};
describe('ReviewAutomationStatusPanel', () => {
it('stays hidden before a ShippingTask is created', () => {
const wrapper = mount(ReviewAutomationStatusPanel, {
props: { processGate, taskCreated: false },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-automation-status-panel"]').exists()).toBe(false);
});
it('does not show a downstream stage as passed when its upstream stage has not started', () => {
const wrapper = mount(ReviewAutomationStatusPanel, {
props: { processGate, taskCreated: true },
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('预约校验');
expect(wrapper.text()).not.toContain('已通过');
expect(wrapper.text().match(/未开始/g)).toHaveLength(2);
});
});
@@ -0,0 +1,107 @@
<!--
features/chat/components/shipping-review/ReviewAutomationStatusPanel.vue
用途:复核工作台「自动处理状态」只读区(技术 Gate 进度,禁止业务用户点技术重试)。
依赖:vue-i18n、ShippingProcessGateUserSummary。
逻辑:仅在任务已创建后展示 gates_track;按 sequence_no 排序,并在首个未完成阶段后
抑制矛盾的下游“已通过”,不提供技术写操作。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingProcessGateUserSummary } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
processGate: ShippingProcessGateUserSummary | null | undefined;
taskCreated?: boolean;
}>();
const { t, te } = useI18n();
const track = computed(() => {
if (!props.taskCreated) return [];
const ordered = [...(props.processGate?.gates_track || [])]
.sort((left, right) => Number(left.sequence_no || 0) - Number(right.sequence_no || 0));
let upstreamReached = true;
return ordered.map((item) => {
const status = String(item.status || 'not_started');
const normalizedStatus = upstreamReached ? status : 'not_started';
if (!['passed', 'skipped'].includes(status)) upstreamReached = false;
return { ...item, status: normalizedStatus };
});
});
const visible = computed(() => track.value.length > 0);
const technicalOnly = computed(() => Boolean(
(props.processGate as { technical_auto_only?: boolean } | null | undefined)?.technical_auto_only,
));
/**
* Gate 状态本地化标签。
*/
function statusLabel(status: string): string {
const key = `chat.shippingOrderReview.automationStatus.statuses.${status}`;
return te(key) ? t(key) : status;
}
/**
* 状态点样式。
*/
function statusClass(status: string): string {
const s = String(status || '');
if (s === 'passed' || s === 'skipped') {
return 'bg-emerald-500';
}
if (s === 'running' || s === 'queued') {
return 'bg-sky-500 animate-pulse';
}
if (s === 'blocked_manual' || s === 'blocked_retryable' || s === 'waiting_external') {
return 'bg-amber-500';
}
if (s === 'failed_terminal') {
return 'bg-rose-500';
}
return 'bg-slate-300 dark:bg-slate-600';
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-automation-status-panel"
>
<header class="mb-2">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.automationStatus.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.automationStatus.subtitle') }}</p>
</header>
<ol class="space-y-1.5">
<li
v-for="item in track"
:key="String(item.gate_code)"
class="flex items-center gap-2 text-[11px] text-secondary"
>
<span
class="inline-block h-2 w-2 shrink-0 rounded-full"
:class="statusClass(String(item.status || ''))"
aria-hidden="true"
/>
<span class="min-w-0 flex-1 truncate">{{ item.label || item.gate_code }}</span>
<span class="shrink-0 text-muted">{{ statusLabel(String(item.status || '')) }}</span>
</li>
</ol>
<p
v-if="technicalOnly"
class="mt-2 text-[11px] text-muted"
data-testid="review-automation-technical-hint"
>
{{ t('chat.shippingOrderReview.automationStatus.technicalHint') }}
</p>
<p
v-else-if="processGate?.blocking_message"
class="mt-2 text-[11px] text-amber-900 dark:text-amber-100"
>
{{ processGate.blocking_message }}
</p>
</section>
</template>
@@ -0,0 +1,90 @@
/**
* features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.spec.ts
* 用途:锁定完整检查必须展示具体冲突字段、行号、来源和值。
* 依赖:vitest、@vue/test-utils、vue-i18n。
* 逻辑:field_conflict issue 不再输出笼统问题;专用冲突投影负责完整展示。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewBuildEligibilityDetailsDrawer from './ReviewBuildEligibilityDetailsDrawer.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: { shippingOrderReview: {
line: '第 {index} 行',
buildEligibility: {
overallResult: '整单结果', canBuildYes: '可建单', canBuildNo: '待处理',
manualConfirmOnly: '需人工确认', blockReasons: { unknown: '未知阻断' },
routingStatus: { unknown: '未知' },
},
workbench: {
fullChecksTitle: '完整订单检查', close: '关闭', issueDetails: '问题明细',
conflictFields: '字段冲突明细', conflictDetailsPending: '冲突明细尚未同步,请刷新后查看。',
requiredField: '字段', missingValue: '缺少值', noLineChecks: '暂无明细检查',
manualReview: { customer: '确认客户', lineInventory: '第 {line} 行库存', noCandidates: '无' },
},
} },
},
},
});
const eligibility = {
can_build: false,
status: 'qualified',
issues: [{ code: 'field_conflict', message: '同一字段存在不同来源值冲突' }],
line_projections: [],
};
describe('ReviewBuildEligibilityDetailsDrawer', () => {
it('lists the exact conflicting field, line, sources and values', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
open: true,
eligibility,
fieldLabels: { unit_price: '单价' },
fieldConflicts: [{
conflict_key: 'unit_price:0', field_code: 'unit_price', line_index: 0,
reason: 'field_conflict',
options: [
{ value_key: '50.43', display_value: '50.43', sources: ['PDF 表格'] },
{ value_key: '51.00', display_value: '51.00', sources: ['邮件正文'] },
],
}],
},
global: { plugins: [i18n] },
});
const details = wrapper.find('[data-testid="review-eligibility-conflict-details"]');
expect(details.text()).toContain('第 1 行');
expect(details.text()).toContain('单价');
expect(details.text()).toContain('PDF 表格:50.43');
expect(details.text()).toContain('邮件正文:51.00');
expect(wrapper.find('[data-testid="review-eligibility-blocking-reasons"]').exists()).toBe(false);
});
it('shows an explicit synchronization warning when conflict detail is absent', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: { open: true, eligibility, fieldConflicts: [] },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-eligibility-conflict-details-missing"]').text())
.toContain('冲突明细尚未同步');
});
it('filters a stale conflict issue after the current order is buildable', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
open: true,
eligibility: { ...eligibility, can_build: true },
fieldConflicts: [],
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-eligibility-conflict-details-missing"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('同一字段存在不同来源值冲突');
});
});
@@ -2,16 +2,22 @@
features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue
用途:完整建单检查项抽屉(逐行投影、阻断原因)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
逻辑:仅在用户主动展开时挂载;关闭不写服务端审计(敏感访问审计由阶段 5 统一补齐)。
逻辑:仅在用户主动展开时挂载;字段冲突必须展开 Case.field_conflicts 的字段、行号、
来源和值,资格 issue 只作为汇总,不得用笼统文案替代冲突明细。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
open: boolean;
eligibility: ShippingOrderReviewBuildEligibility | null;
fieldConflicts?: ShippingOrderReviewFieldConflict[] | null;
fieldLabels?: Record<string, string>;
/** 客户面板的权威确认事实;已确认时不得重放历史 customer_* issue。 */
customerResolved?: boolean;
}>();
const emit = defineEmits<{
@@ -41,6 +47,42 @@ function routingStatusLabel(status?: string | null): string {
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.routingStatus.unknown');
}
function issueLabel(issue: Record<string, unknown>): string {
const field = String(issue.field_code || issue.field_id || '').trim();
const code = String(issue.code || '').trim();
if (field) {
const label = props.fieldLabels?.[field] || field;
return `${t('chat.shippingOrderReview.workbench.requiredField')}: ${label}`;
}
const lineIndex = Number.isFinite(Number(issue.line_index)) ? Number(issue.line_index) : null;
const candidates = Array.isArray(issue.candidate_inventory_source_codes)
? issue.candidate_inventory_source_codes.map((item) => {
const sourceCode = String(item || '').trim();
return props.eligibility?.inventory_source_labels?.[sourceCode] || sourceCode;
}).filter(Boolean)
: [];
if (code === 'customer_unresolved') return t('chat.shippingOrderReview.workbench.manualReview.customer');
if (lineIndex !== null && (candidates.length || code === 'require_manual_review' || code.includes('inventory_source'))) {
return t('chat.shippingOrderReview.workbench.manualReview.lineInventory', {
line: lineIndex + 1,
candidates: candidates.length ? candidates.join('、') : t('chat.shippingOrderReview.workbench.manualReview.noCandidates'),
});
}
const key = `chat.shippingOrderReview.workbench.issueCodes.${code}`;
return code && te(key) ? t(key) : blockReasonLabel(code);
}
function missingFieldLabel(code: string): string {
const label = props.fieldLabels?.[String(code)] || code;
return `${label}:${t('chat.shippingOrderReview.workbench.missingValue')}`;
}
function conflictOptionLabel(option: { display_value?: unknown; value_key?: string; sources?: string[] }): string {
const value = String(option.display_value ?? option.value_key ?? '—').trim() || '—';
const sources = (option.sources || []).map((source) => String(source || '').trim()).filter(Boolean);
return sources.length ? `${sources.join('、')}:${value}` : value;
}
/** 异常行置顶,已通过行排后。 */
const orderedLines = computed(() => {
const lines = [...(props.eligibility?.line_projections || [])];
@@ -51,6 +93,47 @@ const orderedLines = computed(() => {
return (a.line_index ?? 0) - (b.line_index ?? 0);
});
});
/**
* 完整检查与摘要卡共用客户确认事实:服务端刷新前残留的客户 issue 不得误导用户。
*/
const effectiveIssues = computed(() => (props.eligibility?.issues || []).filter((issue) => {
if (props.customerResolved !== true) return true;
const code = String(issue.code || '').trim().toLowerCase();
const reason = String(issue.reason_code || '').trim().toLowerCase();
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
return !(
code.startsWith('customer_')
|| reason.startsWith('customer_')
|| gate === 'customer_resolution'
|| gate === 'customer_confirmed'
);
}));
/** 资格 issue 中是否声明了字段冲突。 */
const hasFieldConflictIssue = computed(() => props.eligibility?.can_build === false && effectiveIssues.value.some((issue) => {
const code = String(issue.code || issue.reason_code || '').trim().toLowerCase();
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
return code.includes('field_conflict') || gate === 'field_conflict_resolution';
}));
/** 字段冲突由专用明细区展示,避免问题列表重复输出一句笼统说明。 */
const nonConflictIssues = computed(() => effectiveIssues.value.filter((issue) => {
const code = String(issue.code || issue.reason_code || '').trim().toLowerCase();
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
const isConflict = code.includes('field_conflict') || gate === 'field_conflict_resolution';
if (!isConflict) return true;
// 当前资格已通过且专用冲突投影为空时,这是旧 validation snapshot 残留,禁止误报。
return false;
}));
const unexplainedBlocked = computed(() => Boolean(
props.eligibility
&& props.eligibility.can_build === false
&& !effectiveIssues.value.length
&& !props.eligibility.failed_gates?.length
&& !props.eligibility.assessment?.missing_required_fields?.length
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
));
</script>
<template>
@@ -69,10 +152,94 @@ const orderedLines = computed(() => {
data-testid="review-eligibility-details-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
</header>
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
<section
class="rounded-lg border px-3 py-2 text-xs"
:class="eligibility.can_build
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100'
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
data-testid="review-eligibility-details-overall"
>
<div class="flex items-center justify-between gap-2">
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</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
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}
</span>
</div>
<p v-if="eligibility.can_build && eligibility.can_auto_create === false" class="mt-1">
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
</p>
<div v-if="eligibility.can_build && eligibility.can_auto_create === false && (eligibility.auto_create_diagnostics?.reason_codes?.length || eligibility.auto_create_diagnostics?.failed_gates?.length)" class="mt-2">
<div class="font-medium">{{ t('chat.shippingOrderReview.buildEligibility.autoCreateFailureTitle') }}</div>
<ul class="mt-1 list-disc pl-4">
<li v-for="reason in (eligibility.auto_create_failure_reasons?.length ? eligibility.auto_create_failure_reasons.map((item) => item.message) : (eligibility.auto_create_diagnostics.reason_codes?.length ? eligibility.auto_create_diagnostics.reason_codes : eligibility.auto_create_diagnostics.failed_gates))" :key="reason">
{{ reason }}
</li>
</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">
<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">
<ul class="mt-1 list-disc pl-4">
<li v-for="code in eligibility.assessment.missing_required_fields" :key="String(code)">
{{ missingFieldLabel(String(code)) }}
</li>
</ul>
</div>
</div>
<div v-if="nonConflictIssues.length" class="mt-2" data-testid="review-eligibility-blocking-reasons">
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.issueDetails') }}</div>
<ul class="mt-1 list-disc pl-4">
<li v-for="(issue, index) in nonConflictIssues" :key="index">
{{ issueLabel(issue) }}
<span v-if="issue.explainability?.message || issue.message" class="text-slate-600 dark:text-slate-300">
— {{ issue.explainability?.message || issue.message }}
</span>
</li>
</ul>
</div>
<div v-if="unexplainedBlocked" class="mt-2 rounded border border-rose-200 bg-rose-50 px-2 py-1.5 text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100" data-testid="review-eligibility-details-unexplained-block">
{{ t('chat.shippingOrderReview.buildEligibility.unexplainedBlocked') }}
</div>
<div
v-if="props.fieldConflicts?.length"
class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-rose-950 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100"
data-testid="review-eligibility-conflict-details"
>
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}</div>
<ul class="mt-2 space-y-2">
<li
v-for="conflict in props.fieldConflicts"
:key="conflict.conflict_key"
class="rounded border border-rose-200 bg-white px-2 py-1.5 dark:border-rose-900 dark:bg-slate-900"
>
<div class="font-semibold">
<span v-if="conflict.line_index != null">{{ t('chat.shippingOrderReview.line', { index: conflict.line_index + 1 }) }} · </span>
{{ props.fieldLabels?.[String(conflict.field_code)] || conflict.field_code }}
</div>
<ul class="mt-1 space-y-1 font-normal">
<li v-for="(option, optionIndex) in conflict.options" :key="`${conflict.conflict_key}-${optionIndex}`">
{{ conflictOptionLabel(option) }}
</li>
</ul>
</li>
</ul>
</div>
<div
v-else-if="hasFieldConflictIssue"
class="mt-2 rounded border border-amber-300 bg-amber-50 px-2.5 py-2 text-amber-900 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-eligibility-conflict-details-missing"
>
{{ t('chat.shippingOrderReview.workbench.conflictDetailsPending') }}
</div>
</section>
<article
v-for="line in orderedLines"
:key="String(line.line_key || line.line_index)"
@@ -95,7 +262,9 @@ const orderedLines = computed(() => {
>
{{
line.can_build
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
? (eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
: t('chat.shippingOrderReview.buildEligibility.linePassesOrderBlocked'))
: t('chat.shippingOrderReview.buildEligibility.lineBlocked')
}}
</span>
@@ -13,7 +13,7 @@ import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/
/**
* 挂载摘要卡。
*/
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility, customerResolved = false) {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
@@ -32,6 +32,12 @@ function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
primaryBlock: '首要阻断原因',
blockCount: '阻断项 {count} 项',
viewFullChecks: '查看完整检查',
manualReview: {
customer: '请确认客户',
field: '请确认字段:{field}',
lineInventory: '第 {line} 行:请确认库存来源(候选:{candidates})',
noCandidates: '暂无候选',
},
},
},
},
@@ -39,7 +45,7 @@ function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
},
});
return mount(ReviewBuildEligibilitySummary, {
props: { eligibility },
props: { eligibility, customerResolved },
global: { plugins: [i18n] },
});
}
@@ -66,4 +72,72 @@ describe('ReviewBuildEligibilitySummary', () => {
await wrapper.find('[data-testid="review-open-eligibility-details"]').trigger('click');
expect(wrapper.emitted('open-details')).toBeTruthy();
});
it('does not keep a stale customer block after the customer is confirmed', () => {
const wrapper = mountSummary({
can_build: false,
status: 'blocked',
issues: [{
code: 'customer_unresolved',
severity: 'blocking',
explainability: { message: '未能识别客户' },
}],
line_projections: [{
line_key: 'L1',
line_index: 0,
can_build: false,
block_reason: 'customer_unresolved',
}],
gates: { customer_confirmed: false },
}, true);
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').text()).toContain('✓');
});
it('projects concrete manual review facts before falling back to generic copy', () => {
const wrapper = mountSummary({
can_build: false,
status: 'blocked',
issues: [{
code: 'require_manual_review',
severity: 'blocking',
line_index: 1,
candidate_inventory_source_codes: ['WH_A', 'WH_B'],
}],
line_projections: [],
inventory_source_labels: { WH_A: '华东仓', WH_B: '华南仓' },
});
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
.toContain('第 2 行:请确认库存来源(候选:华东仓、华南仓)');
});
it('explains a blocked order even when the API has no issue detail', () => {
const wrapper = mountSummary({
can_build: false,
status: 'blocked',
failed_gates: ['required_fields_complete'],
issues: [],
line_projections: [],
});
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
.toContain('未知问题');
expect(wrapper.text()).not.toContain('required_fields_complete');
});
it('does not expose internal build and auto-create layer names', () => {
const wrapper = mountSummary({
can_build: true,
can_auto_create: false,
status: 'qualified',
issues: [],
line_projections: [],
});
expect(wrapper.find('[data-testid="review-eligibility-layers"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('can_build');
expect(wrapper.text()).not.toContain('can_auto_create');
});
});
@@ -2,19 +2,34 @@
features/chat/components/shipping-review/ReviewBuildEligibilitySummary.vue
用途:复核摘要侧栏的建单资格压缩卡(可建单状态、门禁清单、首要阻断)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
逻辑:展示客户确认等关键门禁勾选;「查看完整检查」emit open-details;完整逐行结果不常驻。
逻辑:只展示业务结论、具体字段/明细问题与异常导航;隐藏 Gate code、
can_build/can_auto_create 等实现标识;「查看完整检查」emit open-details。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
eligibility: ShippingOrderReviewBuildEligibility | null;
fieldConflicts?: ShippingOrderReviewFieldConflict[] | null;
fieldLabels?: Record<string, string>;
customerResolved?: boolean;
/** 可定位异常总数;由工作台统一收集草稿与门禁问题。 */
exceptionCount?: number;
/** 当前定位异常序号;未定位时为 0。 */
exceptionOrdinal?: number;
/**
* 为 true 时只展示能否建单/自动建单与异常导航,隐藏门禁清单与首要阻断文案,
* 避免与 ProcessGateRecoveryCard 重复表达同一业务阻断。
*/
focusBuildability?: boolean;
}>();
const emit = defineEmits<{
'open-details': [];
'navigate-exception': [delta: -1 | 1];
}>();
const { t, te } = useI18n();
@@ -29,28 +44,84 @@ const CHECKLIST_GATES = [
] as const;
/** 阻断 issue 数量(优先 blocking severity)。 */
const blockingIssueCount = computed(() => {
const effectiveIssues = computed(() => {
const issues = props.eligibility?.issues || [];
if (props.customerResolved !== true) return issues;
return issues.filter((item) => {
const code = String(item.code || '').trim().toLowerCase();
const reason = String(item.reason_code || '').trim().toLowerCase();
const gate = String(item.owning_gate_code || '').trim().toLowerCase();
return !(
code.startsWith('customer_')
|| reason.startsWith('customer_')
|| gate === 'customer_resolution'
|| gate === 'customer_confirmed'
);
});
});
const blockingIssueCount = computed(() => {
const issues = effectiveIssues.value;
const blocking = issues.filter((item) => String(item.severity || '') === 'blocking');
return blocking.length || issues.length;
});
/** 首要阻断文案。 */
const primaryBlockMessage = computed(() => {
const issues = props.eligibility?.issues || [];
const issues = effectiveIssues.value;
const primary = issues.find((item) => String(item.severity || '') === 'blocking') || issues[0];
if (!primary) {
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => line.can_build === false);
if (!blockedLines.length) return '';
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => {
if (line.can_build !== false) return false;
if (props.customerResolved !== true) return true;
const reason = String(line.block_reason || '').trim().toLowerCase();
return !reason.startsWith('customer_');
});
if (!blockedLines.length) {
const failedGate = (props.eligibility?.failed_gates || [])[0];
if (!failedGate) return '';
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
}
const reason = String(blockedLines[0]?.block_reason || '').trim();
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${reason}`;
return reason && te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
const code = String(primary.code || '').trim().toLowerCase();
// Draft 基础校验按冻结 Schema 返回 field_id,资格评估返回 field_code;两者都要映射,
// 否则会丢失“究竟哪个字段没有值”的事实,只剩笼统的不可建单。
const field = String(primary.field_code || primary.field_id || '').trim();
const lineIndex = Number.isFinite(Number(primary.line_index)) ? Number(primary.line_index) : null;
const candidates = Array.isArray(primary.candidate_inventory_source_codes)
? primary.candidate_inventory_source_codes.map((item) => {
const sourceCode = String(item || '').trim();
return props.eligibility?.inventory_source_labels?.[sourceCode] || sourceCode;
}).filter(Boolean)
: [];
if (code === 'customer_unresolved') {
return t('chat.shippingOrderReview.workbench.manualReview.customer');
}
if (field) {
return t('chat.shippingOrderReview.workbench.manualReview.field', {
field: props.fieldLabels?.[field] || field,
});
}
if (lineIndex !== null && (candidates.length || code === 'require_manual_review' || code.includes('inventory_source'))) {
return t('chat.shippingOrderReview.workbench.manualReview.lineInventory', {
line: lineIndex + 1,
candidates: candidates.length ? candidates.join('、') : t('chat.shippingOrderReview.workbench.manualReview.noCandidates'),
});
}
const message = String(primary.explainability?.message || primary.message || '').trim();
if (message) return message;
const code = String(primary.code || '').trim();
const key = `chat.shippingOrderReview.issueCodes.${code}`;
return code && te(key) ? t(key) : t('chat.shippingOrderReview.issueCodes.unknown');
if (code && te(key)) return t(key);
const failedGate = (props.eligibility?.failed_gates || [])[0];
if (failedGate) {
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
}
return t('chat.shippingOrderReview.issueCodes.unknown');
});
/** 不可建单的行数。 */
@@ -58,6 +129,25 @@ const blockedLineCount = computed(() =>
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false).length,
);
const missingRequiredFields = computed(() => (props.eligibility?.assessment?.missing_required_fields || [])
.map((code) => props.fieldLabels?.[String(code)] || String(code)));
const conflictFields = computed(() => (props.fieldConflicts || []).map((item) => props.fieldLabels?.[String(item.field_code || '').trim()] || String(item.field_code || '').trim())
.filter(Boolean));
const lowConfidenceFields = computed(() => props.eligibility?.issues?.flatMap((issue) =>
(issue.low_confidence_fields || []).map((item) => ({
...item,
label: props.fieldLabels?.[item.field_code] || item.field_code,
})),
) || []);
const unexplainedBlocked = computed(() => Boolean(
props.eligibility
&& props.eligibility.can_build === false
&& !props.eligibility.issues?.length
&& !props.eligibility.failed_gates?.length
&& !props.eligibility.assessment?.missing_required_fields?.length
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
));
/**
* 门禁勾选列表:优先 gates 映射;客户未确认时强制展示失败项。
*/
@@ -66,17 +156,37 @@ const gateChecklist = computed(() => {
const failed = new Set((props.eligibility?.failed_gates || []).map(String));
const issues = props.eligibility?.issues || [];
const customerIssue = issues.some((item) => String(item.code || '').startsWith('customer_'));
return CHECKLIST_GATES.map((gate) => {
const checks = CHECKLIST_GATES.map((gate) => {
const known = Object.prototype.hasOwnProperty.call(gates, gate);
let passed = known ? Boolean(gates[gate]) : !failed.has(gate);
if (gate === 'customer_confirmed' && customerIssue) passed = false;
if (gate === 'customer_confirmed') {
passed = props.customerResolved === true ? true : (customerIssue ? false : passed);
}
if (gate === 'field_conflicts_resolved' && props.fieldConflicts) {
passed = props.fieldConflicts.length === 0;
}
if (gate === 'required_fields_complete' && props.eligibility?.assessment) {
const missing = props.eligibility.assessment.missing_required_fields || [];
const invalid = props.eligibility.assessment.invalid_lines || [];
passed = missing.length === 0 && invalid.length === 0;
}
const labelKey = `chat.shippingOrderReview.buildEligibility.gates.${gate}`;
return {
gate,
passed,
label: te(labelKey) ? t(labelKey) : gate,
label: te(labelKey) ? t(labelKey) : t('chat.shippingOrderReview.issueCodes.unknown'),
};
}).filter((item) => Object.keys(gates).length === 0 || Object.prototype.hasOwnProperty.call(gates, item.gate) || item.gate === 'customer_confirmed');
return [
{
gate: 'overall_build_result',
passed: props.eligibility?.can_build === true,
label: props.eligibility?.can_build === true
? t('chat.shippingOrderReview.buildEligibility.overallPass')
: t('chat.shippingOrderReview.buildEligibility.overallBlocked'),
},
...checks,
];
});
</script>
@@ -103,8 +213,15 @@ const gateChecklist = computed(() => {
</span>
</header>
<p
v-if="eligibility.can_build && eligibility.can_auto_create === false"
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-auto-create-blocked"
>
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
</p>
<ul
v-if="gateChecklist.length"
v-if="!focusBuildability && gateChecklist.length"
class="mt-2 space-y-1 text-xs"
data-testid="review-eligibility-gate-checklist"
>
@@ -119,9 +236,57 @@ const gateChecklist = computed(() => {
</span>
</li>
</ul>
<div
v-if="exceptionCount"
class="mt-2 flex flex-wrap items-center justify-between gap-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-exception-nav"
>
<span>
{{ t('chat.shippingOrderReview.issues') }}
<span class="ml-1 text-muted">
{{ exceptionOrdinal ? `${exceptionOrdinal}/${exceptionCount}` : `0/${exceptionCount}` }}
</span>
</span>
<div class="flex items-center gap-2">
<button
type="button"
class="rounded border border-amber-300 px-2 py-1 text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950"
data-testid="review-exception-prev"
:title="t('chat.shippingOrderReview.exceptionNav.prevHint')"
@click="emit('navigate-exception', -1)"
>
{{ t('chat.shippingOrderReview.exceptionNav.prev') }}
</button>
<button
type="button"
class="rounded border border-amber-300 px-2 py-1 text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950"
data-testid="review-exception-next"
:title="t('chat.shippingOrderReview.exceptionNav.nextHint')"
@click="emit('navigate-exception', 1)"
>
{{ t('chat.shippingOrderReview.exceptionNav.next') }}
</button>
</div>
</div>
<div v-if="missingRequiredFields.length || conflictFields.length" class="mt-2 space-y-1 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-xs text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100">
<p v-if="missingRequiredFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.missingRequiredFields') }}:</span>{{ missingRequiredFields.join('、') }}</p>
<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"
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"
>
<p class="font-semibold">{{ t('chat.shippingOrderReview.workbench.lowConfidenceFields') }}:</p>
<ul class="mt-1 list-disc pl-4">
<li v-for="item in lowConfidenceFields" :key="item.field_code">
{{ item.label }}({{ item.confidence == null ? '—' : `${Math.round(item.confidence * 100)}%` }},{{ t('chat.shippingOrderReview.workbench.confidenceThreshold', { threshold: Math.round(Number(item.minimum_confidence || 0) * 100) }) }})
</li>
</ul>
</div>
<div
v-if="!eligibility.can_build && primaryBlockMessage"
v-if="!focusBuildability && !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"
>
@@ -133,6 +298,13 @@ const gateChecklist = computed(() => {
}) }}
</p>
</div>
<div
v-if="unexplainedBlocked"
class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-xs text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100"
data-testid="review-eligibility-unexplained-block"
>
{{ t('chat.shippingOrderReview.buildEligibility.unexplainedBlocked') }}
</div>
<button
type="button"
@@ -0,0 +1,130 @@
<!--
features/chat/components/shipping-review/ReviewCloseFulfillmentDialog.vue
用途:关闭行级或剩余开放行的履约决定确认弹窗(原因必填)。
依赖:vue-i18n、closeWorkspaceShippingOrderReviewLineFulfillment、showReviewResumeOutcome。
逻辑:父级传入 lineKeys;空数组表示关闭全部剩余开放行;成功后 emit confirmed。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { closeWorkspaceShippingOrderReviewLineFulfillment } from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
const props = defineProps<{
open: boolean;
caseNo: string;
draftVersion: number | null | undefined;
lineKeys: string[];
closeAllRemaining?: boolean;
}>();
const emit = defineEmits<{
'update:open': [value: boolean];
confirmed: [];
}>();
const { t } = useI18n();
const msg = useMessage();
const reason = ref('');
const busy = ref(false);
const title = computed(() => (
props.closeAllRemaining || !props.lineKeys.length
? t('chat.shippingOrderReview.closeFulfillment.titleAll')
: t('chat.shippingOrderReview.closeFulfillment.titleSelected', { count: props.lineKeys.length })
));
watch(
() => props.open,
(isOpen) => {
if (!isOpen) {
reason.value = '';
busy.value = false;
}
},
);
/**
* 提交关闭履约行决定。
*/
async function onConfirm() {
const trimmed = reason.value.trim();
if (!trimmed || !props.caseNo || busy.value) return;
busy.value = true;
try {
const result = await closeWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
reason: trimmed,
line_keys: props.lineKeys.length ? props.lineKeys : undefined,
expected_draft_version: props.draftVersion ?? undefined,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.closeFulfillment.success'),
);
emit('update:open', false);
emit('confirmed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.closeFulfillment.failed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
/**
* 取消并关闭弹窗。
*/
function onCancel() {
emit('update:open', false);
}
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="review-close-fulfillment-dialog"
@click.self="onCancel"
>
<div class="w-full max-w-md rounded-xl border border-slate-200 bg-white p-4 shadow-xl dark:border-slate-800 dark:bg-slate-900">
<h2 class="text-sm font-semibold">{{ title }}</h2>
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.closeFulfillment.subtitle') }}</p>
<label class="mt-3 block text-xs font-medium text-secondary">
{{ t('chat.shippingOrderReview.closeFulfillment.reasonLabel') }}
<textarea
v-model="reason"
rows="3"
class="mt-1 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
data-testid="review-close-fulfillment-reason"
:placeholder="t('chat.shippingOrderReview.closeFulfillment.reasonPlaceholder')"
:disabled="busy"
/>
</label>
<div class="mt-4 flex justify-end gap-2">
<button
type="button"
class="rounded border border-default px-3 py-1.5 text-sm hover:bg-surface-soft disabled:opacity-50"
:disabled="busy"
@click="onCancel"
>
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
<button
type="button"
class="rounded bg-rose-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
data-testid="review-close-fulfillment-submit"
:disabled="busy || !reason.trim()"
@click="onConfirm"
>
{{ busy ? t('chat.shippingOrderReview.closeFulfillment.closing') : t('chat.shippingOrderReview.closeFulfillment.confirm') }}
</button>
</div>
</div>
</div>
</template>
@@ -2,7 +2,8 @@
features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue
用途:复核工作台固定「建单前客户确认」区域(与重新识别 PDF 分层)。
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别接口。
逻辑:始终展示客户识别状态;选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
逻辑:未解决时完整展开置顶;已解决且 compact 时缩为一行摘要;
选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -24,6 +25,8 @@ const props = defineProps<{
caseNo: string;
resolution: ShippingOrderReviewCustomerResolution | null | undefined;
editable: boolean;
/** 已解决时缩为一行摘要(放入「更多状态」) */
compact?: boolean;
}>();
const emit = defineEmits<{
@@ -56,6 +59,27 @@ const displayName = computed(() => {
return name || code || String(props.resolution?.raw_name || '').trim() || '—';
});
const inputValues = computed(() => props.resolution?.input_values || []);
const candidateRows = computed(() => props.resolution?.candidates || []);
function inputLabel(definitionCode: string | null | undefined): string {
const code = String(definitionCode || '').trim().toLowerCase();
if (code.includes('customer') && code.includes('code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
if (code.includes('customer') && code.includes('name')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerName');
if (code.includes('address')) return t('chat.shippingOrderReview.customerResolution.inputLabels.address');
if (code.endsWith('customer_code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
if (code.endsWith('customer_name')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerName');
if (code.endsWith('address')) return t('chat.shippingOrderReview.customerResolution.inputLabels.address');
if (code.includes('email')) return t('chat.shippingOrderReview.customerResolution.inputLabels.email');
if (code.includes('domain')) return t('chat.shippingOrderReview.customerResolution.inputLabels.domain');
return t('chat.shippingOrderReview.customerResolution.inputLabels.other');
}
function candidateValue(candidate: unknown, key: string): string {
const row = candidate && typeof candidate === 'object' ? candidate as Record<string, unknown> : {};
return String(row[key] ?? '').trim() || '—';
}
/**
* 打开标准客户选择弹窗并加载选项。
*/
@@ -94,12 +118,21 @@ async function onConfirm(customerId: number) {
if (!props.caseNo || busy.value) return;
busy.value = true;
try {
await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
const result = await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
customer_id: customerId,
reason: t('chat.shippingOrderReview.customerResolution.confirmReason'),
});
dialogOpen.value = false;
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
const resume = result.resume_outcome;
if (resume?.outcome === 'auto_created' || resume?.outcome === 'idempotent_replay') {
msg.success(t('chat.shippingOrderReview.resume.autoCreated', {
taskNo: resume.task_no || '',
}));
} else if (resume?.outcome === 'waiting_manual_confirm') {
msg.success(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
} else {
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
}
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -136,7 +169,28 @@ async function onRetry() {
<section
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-customer-resolution-panel"
:data-compact="compact && resolved ? 'true' : 'false'"
>
<!-- 已解决摘要:一行展示客户与状态,避免占满侧栏首位 -->
<div
v-if="compact && resolved"
class="flex flex-wrap items-center justify-between gap-2"
data-testid="review-customer-resolution-compact"
>
<p class="text-xs text-secondary">
<span class="font-medium text-primary">{{ t('chat.shippingOrderReview.customerResolution.title') }}</span>
<span class="mx-1 text-muted">·</span>
<span>{{ displayName }}</span>
</p>
<span
class="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
data-testid="review-customer-resolution-badge"
>
{{ statusLabel }}
</span>
</div>
<template v-else>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
@@ -155,12 +209,26 @@ async function onRetry() {
<dl class="mt-2 space-y-1 text-xs text-secondary">
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.recognizedAs') }}</dt>
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.standardCustomer') }}</dt>
<dd class="font-medium text-primary">{{ displayName }}</dd>
</div>
<div v-if="resolution?.raw_name && resolution.raw_name !== displayName" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.rawName') }}</dt>
<dd>{{ resolution.raw_name }}</dd>
<div v-if="resolution?.short_code" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.customerCode') }}</dt>
<dd class="font-mono font-medium text-primary">{{ resolution.short_code }}</dd>
</div>
<div v-if="inputValues.length" class="mt-2 border-t border-default pt-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.matchedInputs') }}</dt>
<dd v-for="item in inputValues" :key="`${item.definition_code}:${item.normalized_value}`" class="mt-1 flex flex-wrap gap-x-2">
<span class="text-muted">{{ inputLabel(item.definition_label || item.definition_code) }}</span>
<span class="font-mono text-primary">{{ item.raw_value || item.normalized_value || '—' }}</span>
</dd>
</div>
<div v-if="candidateRows.length > 1" class="mt-2 border-t border-default pt-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.candidates') }}</dt>
<dd v-for="candidate in candidateRows" :key="String(candidate.customer_id)" class="mt-1 flex flex-wrap gap-x-2">
<span class="text-primary">{{ candidateValue(candidate, 'standard_name') }}</span>
<span class="font-mono text-muted">{{ candidateValue(candidate, 'short_code') }}</span>
</dd>
</div>
</dl>
@@ -196,5 +264,6 @@ async function onRetry() {
@search="searchCustomers"
@confirm="onConfirm"
/>
</template>
</section>
</template>
@@ -13,6 +13,7 @@ import {
refreshWorkspaceShippingOrderReviewDuplicate,
resolveWorkspaceShippingOrderReviewDuplicate,
} from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type {
ShippingDuplicateAction,
ShippingOrderReviewDuplicate,
@@ -78,13 +79,13 @@ async function resolve(action: ShippingDuplicateAction) {
busy.value = true;
selectedAction.value = action;
try {
await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
const result = await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
action,
target_task_no: target,
reason: action === 'force_create' ? forceReason.value.trim() : undefined,
});
forceReason.value = '';
msg.success(t('chat.shippingOrderReview.duplicate.resolveSuccess'));
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.duplicate.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -104,8 +105,8 @@ async function onRefresh() {
if (!props.editable || !props.caseNo || busy.value) return;
busy.value = true;
try {
await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
msg.success(t('chat.shippingOrderReview.duplicate.refreshDone'));
const result = await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.duplicate.refreshDone'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -2,7 +2,8 @@
features/chat/components/shipping-review/ReviewFieldConflictPanel.vue
用途:复核工作台建单前字段冲突集中裁决区(采用候选值 / 手工值)。
依赖:vue-i18n、shipping.api.resolveWorkspaceShippingOrderReviewFieldConflict、useMessage。
逻辑:展示 Case.field_conflicts;裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
逻辑:展示 Case.field_conflicts;选项标注 evidence_role(主 PDF / 辅助 / 正文);
裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -10,6 +11,7 @@ import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { resolveWorkspaceShippingOrderReviewFieldConflict } from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
@@ -48,6 +50,16 @@ function reasonLabel(reason: string): string {
return te(key) ? t(key) : reason;
}
/**
* 证据角色本地化(主 PDF / 辅助 / 邮件正文)。
*/
function evidenceRoleLabel(role: string | undefined | null): string {
const code = String(role || '').trim();
if (!code) return '';
const key = `chat.shippingOrderReview.fieldConflict.evidenceRole.${code}`;
return te(key) ? t(key) : code;
}
/**
* 定位冲突字段到草稿/证据区。
*/
@@ -66,13 +78,13 @@ async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionInd
if (!props.editable || !props.caseNo || props.draftVersion == null || resolvingKey.value) return;
resolvingKey.value = conflict.conflict_key;
try {
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
const result = await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
resolution: 'adopt_option',
option_index: optionIndex,
expected_draft_version: props.draftVersion,
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
});
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -105,7 +117,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
if (!value || !props.editable || props.draftVersion == null || resolvingKey.value) return;
resolvingKey.value = conflict.conflict_key;
try {
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
const result = await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
resolution: 'custom',
custom_value: value,
expected_draft_version: props.draftVersion,
@@ -113,7 +125,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
});
customOpenKey.value = null;
customValue.value = '';
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -172,9 +184,22 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
:key="`${conflict.conflict_key}-${idx}`"
class="rounded border border-default bg-surface-soft px-2 py-1.5"
>
<div class="text-muted">
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
<div class="flex flex-wrap items-center gap-1 text-muted">
<span>
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
</span>
<span
v-if="evidenceRoleLabel(option.evidence_role)"
class="rounded px-1 py-0.5 text-[10px] font-medium"
:class="option.evidence_role === 'primary_pdf'
? 'bg-sky-100 text-sky-800 dark:bg-sky-950 dark:text-sky-200'
: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'"
:data-testid="`review-field-conflict-evidence-role-${idx}`"
:data-evidence-role="option.evidence_role"
>
{{ evidenceRoleLabel(option.evidence_role) }}
</span>
</div>
<div class="mt-0.5 font-mono text-primary">{{ option.display_value || option.value_key || '—' }}</div>
<button
@@ -0,0 +1,275 @@
<!--
features/chat/components/shipping-review/ReviewFulfillmentDecisionPanel.vue
用途:复核工作台行级履约决定(等待补货 / 完整行先行 / 关闭)。
依赖:vue-i18n、decide/wave line-fulfillment API、showReviewResumeOutcome。
逻辑:展示 qty/shortage;逐行决定;选中 fulfill 行可确认波次;关闭 emit open-close-dialog。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
decideWorkspaceShippingOrderReviewLineFulfillment,
waveWorkspaceShippingOrderReviewLineFulfillment,
} from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type {
ShippingOrderReviewLineFulfillment,
ShippingOrderReviewLineFulfillmentDecisionCode,
ShippingOrderReviewLineFulfillmentLine,
} from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
draftVersion: number | null | undefined;
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
'open-close-dialog': [lineKeys: string[]];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busyKey = ref<string | null>(null);
const selectedFulfillKeys = ref<string[]>([]);
const waveBusy = ref(false);
const TERMINAL_STATUSES = new Set(['task_created', 'fulfilled', 'closed_unfulfillable']);
const visible = computed(() => Boolean(
props.lineFulfillment?.has_open_lines
|| props.lineFulfillment?.has_shortage,
));
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter(
(line) => !TERMINAL_STATUSES.has(String(line.line_status || '')),
));
/**
* 行状态本地化。
*/
function lineStatusLabel(status: string | null | undefined): string {
const normalized = String(status || 'pending_decision').trim();
const key = `chat.shippingOrderReview.fulfillmentDecision.lineStatus.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 切换 fulfill 波次选中行。
*/
function toggleFulfillSelection(lineKey: string, checked: boolean) {
const set = new Set(selectedFulfillKeys.value);
if (checked) set.add(lineKey);
else set.delete(lineKey);
selectedFulfillKeys.value = [...set];
}
/**
* 行是否可选入 fulfill 波次。
*/
function canSelectForWave(line: ShippingOrderReviewLineFulfillmentLine): boolean {
if (TERMINAL_STATUSES.has(String(line.line_status || ''))) return false;
return Boolean(line.can_fulfill_complete_line);
}
/**
* 写入单行履约决定。
*/
async function onDecide(
line: ShippingOrderReviewLineFulfillmentLine,
decisionCode: ShippingOrderReviewLineFulfillmentDecisionCode,
) {
if (!props.caseNo || !props.editable || busyKey.value) return;
if (decisionCode === 'close_unfulfillable') {
emit('open-close-dialog', [line.line_key]);
return;
}
busyKey.value = line.line_key;
try {
const result = await decideWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
line_key: line.line_key,
decision_code: decisionCode,
expected_draft_version: props.draftVersion ?? undefined,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.fulfillmentDecision.decideSuccess'),
);
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.decideFailed'));
msg.warning(message);
} finally {
busyKey.value = null;
}
}
/**
* 为选中完整行创建履约波次 Task。
*/
async function onConfirmWave() {
if (!props.caseNo || props.draftVersion == null || waveBusy.value || !selectedFulfillKeys.value.length) return;
waveBusy.value = true;
try {
const idempotencyKey = `review-wave-${props.caseNo}-${Date.now()}-${selectedFulfillKeys.value.sort().join(',')}`;
const result = await waveWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
line_keys: [...selectedFulfillKeys.value],
expected_draft_version: props.draftVersion,
idempotency_key: idempotencyKey,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.fulfillmentDecision.waveSuccess', {
taskNo: result.task_no || '',
}),
);
selectedFulfillKeys.value = [];
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.waveFailed'));
msg.warning(message);
} finally {
waveBusy.value = false;
}
}
/**
* 打开关闭剩余行对话框(全部开放行)。
*/
function onCloseRemaining() {
const keys = openLines.value.map((line) => line.line_key);
emit('open-close-dialog', keys);
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
data-testid="review-fulfillment-decision-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
</h2>
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
{{ t('chat.shippingOrderReview.fulfillmentDecision.subtitle') }}
</p>
</div>
<span class="rounded-full bg-sky-100 px-2.5 py-1 text-xs font-medium text-sky-900 dark:bg-sky-950 dark:text-sky-100">
{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: lineFulfillment?.open_count ?? openLines.length }) }}
</span>
</header>
<div class="mt-2 overflow-x-auto">
<table class="min-w-full text-left text-xs">
<thead class="text-muted">
<tr>
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.waveSelect') }}</th>
<th class="px-1 py-1 font-medium">#</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.partNumber') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.qty') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.status') }}</th>
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in lineFulfillment?.lines || []"
:key="line.line_key"
class="border-t border-sky-100 dark:border-sky-900"
>
<td v-if="editable" class="px-1 py-1">
<input
v-if="canSelectForWave(line)"
type="checkbox"
class="rounded border-default"
:checked="selectedFulfillKeys.includes(line.line_key)"
:data-testid="`review-fulfill-select-${line.line_key}`"
@change="toggleFulfillSelection(line.line_key, ($event.target as HTMLInputElement).checked)"
>
</td>
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
<td class="px-1 py-1 font-mono">{{ line.part_number || line.reservation_id || '—' }}</td>
<td class="px-1 py-1">
{{ line.required_qty ?? '—' }}
<span v-if="line.available_qty" class="text-muted"> / {{ line.available_qty }}</span>
</td>
<td class="px-1 py-1" :class="line.shortage_qty ? 'font-medium text-rose-700 dark:text-rose-300' : ''">
{{ line.shortage_qty || '—' }}
</td>
<td class="px-1 py-1">{{ lineStatusLabel(line.line_status) }}</td>
<td v-if="editable && !TERMINAL_STATUSES.has(String(line.line_status || ''))" class="px-1 py-1">
<div class="flex flex-wrap gap-1">
<button
type="button"
class="rounded border border-sky-300 px-2 py-1 text-xs hover:bg-sky-100 disabled:opacity-50 dark:border-sky-800 dark:hover:bg-sky-950"
:disabled="busyKey != null"
@click="onDecide(line, 'wait_inventory')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.waitInventory') }}
</button>
<button
v-if="line.can_fulfill_complete_line"
type="button"
class="rounded border border-emerald-300 px-2 py-1 text-xs hover:bg-emerald-50 disabled:opacity-50 dark:border-emerald-800 dark:hover:bg-emerald-950"
:disabled="busyKey != null"
@click="onDecide(line, 'fulfill_complete_line_now')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.fulfillNow') }}
</button>
<button
type="button"
class="rounded border border-rose-300 px-2 py-1 text-xs text-rose-800 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-800 dark:text-rose-200 dark:hover:bg-rose-950"
:disabled="busyKey != null"
@click="onDecide(line, 'close_unfulfillable')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeLine') }}
</button>
</div>
</td>
<td v-else-if="editable" class="px-1 py-1 text-muted">—</td>
</tr>
</tbody>
</table>
</div>
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-60"
data-testid="review-fulfillment-confirm-wave"
:disabled="waveBusy || !selectedFulfillKeys.length || draftVersion == null"
@click="onConfirmWave"
>
{{ waveBusy
? t('chat.shippingOrderReview.fulfillmentDecision.waving')
: t('chat.shippingOrderReview.fulfillmentDecision.confirmWave', { count: selectedFulfillKeys.length }) }}
</button>
<button
v-if="openLines.length"
type="button"
class="rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 disabled:opacity-60 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200"
data-testid="review-fulfillment-close-remaining"
:disabled="waveBusy || busyKey != null"
@click="onCloseRemaining"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}
</button>
</div>
</section>
</template>
@@ -0,0 +1,65 @@
<!--
features/chat/components/shipping-review/ReviewFulfillmentSummaryCard.vue
用途:复核侧栏紧凑展示行级履约缺口摘要,完整表格在库存模式主区处理。
依赖:vue-i18n、ShippingOrderReviewLineFulfillment。
逻辑:仅显示开放行/缺口计数与进入库存处理入口;不渲染 7 列表格。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
}>();
const emit = defineEmits<{
'enter-inventory': [];
}>();
const { t } = useI18n();
const visible = computed(() => Boolean(
props.lineFulfillment?.has_open_lines
|| props.lineFulfillment?.has_shortage
|| (props.lineFulfillment?.open_count || 0) > 0,
));
const openCount = computed(() => Number(props.lineFulfillment?.open_count || 0));
const readyCount = computed(() => Number(props.lineFulfillment?.ready_count || 0));
const shortageCount = computed(() => (
props.lineFulfillment?.lines || []
).filter((line) => Boolean(line.shortage_qty)).length);
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
data-testid="review-fulfillment-summary-card"
>
<header class="mb-2">
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
</h2>
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
{{ t('chat.shippingOrderReview.fulfillmentDecision.railHint') }}
</p>
</header>
<ul class="space-y-1 text-xs text-secondary">
<li>{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: openCount }) }}</li>
<li>{{ t('chat.shippingOrderReview.fulfillmentDecision.readyCount', { count: readyCount }) }}</li>
<li v-if="shortageCount">
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortageCount', { count: shortageCount }) }}
</li>
</ul>
<button
type="button"
class="mt-3 w-full rounded-xl border border-sky-300 bg-white px-3 py-1.5 text-sm text-sky-950 hover:bg-sky-100 dark:border-sky-800 dark:bg-slate-900 dark:text-sky-50 dark:hover:bg-sky-950"
data-testid="review-fulfillment-enter-inventory"
@click="emit('enter-inventory')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.enterInventory') }}
</button>
</section>
</template>
@@ -11,6 +11,10 @@ import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/featur
defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
/**
* 仅展示「进入库存」入口,不列出行明细(Gate/履约摘要已表达缺口时使用)。
*/
summaryOnly?: boolean;
}>();
const emit = defineEmits<{
@@ -48,7 +52,7 @@ function blockReasonLabel(reason?: string | null): string {
{{ t('chat.shippingOrderReview.workbench.enterInventory') }}
</button>
</header>
<ul class="space-y-1.5">
<ul v-if="!summaryOnly" class="space-y-1.5">
<li
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
@@ -33,6 +33,8 @@ const messages = {
sourceEvidence: 'Evidence',
verbatimOk: 'OK',
verbatimFailed: 'Failed',
unavailableDisabled: 'AI suggestions are disabled in this environment.',
unavailableProvider: 'AI suggestion service is unavailable. Try again later.',
evidenceAtCell: 'page {page} {cell}',
noEvidenceCoords: 'no coords',
cancel: 'Cancel',
@@ -41,7 +43,13 @@ const messages = {
noteOptional: 'Note',
reasonRequired: 'Reason required',
evidenceLevel: { L1_field: 'Current field content', unknown: 'Relevant document content' },
status: { idle: 'Idle', pending: 'Pending', validated: 'Validated', unknown: 'Status pending confirmation' },
status: {
idle: 'Idle',
pending: 'Pending',
validated: 'Validated',
provider_unavailable: 'Unavailable',
unknown: 'Status pending confirmation',
},
decisions: { accept: 'Accept', modify: 'Modify', reject: 'Reject' },
},
},
@@ -195,4 +203,22 @@ describe('ReviewLlmSuggestionPanel', () => {
expect(wrapper.text()).not.toContain('internal_evidence_level');
wrapper.unmount();
});
it('shows a visible disabled message when Dify was not called', () => {
const unavailable: ShippingOrderReviewLlmSuggestion = {
suggestion_no: 'RSG-DISABLED',
field_id: 'fld-po',
scope: 'header',
evidence_level: 'L1_field',
status: 'provider_unavailable',
error_code: 'SHIPPING.REVIEW_LLM_DISABLED',
validation_issues: [],
};
const wrapper = mountPanel({ suggestions: [unavailable] });
expect(wrapper.get('[data-testid="review-llm-provider-unavailable"]').text())
.toContain('AI suggestions are disabled in this environment.');
expect(wrapper.text()).not.toContain('No suggestions');
wrapper.unmount();
});
});
@@ -3,7 +3,7 @@
用途:AI 建议列表与裁决内容(布局重构后作为抽屉内容组件,非常驻主区大卡片)。
依赖:vue-i18n、ReviewLlmSuggestionDialog、ShippingOrderReview* 类型。
逻辑:由 ReviewLlmSuggestionDrawer 挂载;请求须用户主动触发;仅 validated 可接受;
validation_failed 仅可拒绝;证据按 field_id + line_key/line_index 绑定。
validation_failed 仅可拒绝;provider_unavailable 明示原因;证据按 field_id + line_key/line_index 绑定。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -51,6 +51,19 @@ const failedSuggestions = computed(() =>
(props.suggestions || []).filter((item) => String(item.status || '') === 'validation_failed' && !item.decision),
);
/** Provider 未调用或调用失败的记录必须明确展示,避免用户把静默空态误认为 AI 已执行。 */
const unavailableSuggestions = computed(() =>
(props.suggestions || []).filter((item) => String(item.status || '') === 'provider_unavailable'),
);
/** 将 Provider 失败码转成可执行的业务提示,不向用户暴露底层地址或异常正文。 */
function unavailableMessage(item?: ShippingOrderReviewLlmSuggestion): string {
if (String(item?.error_code || '') === 'SHIPPING.REVIEW_LLM_DISABLED') {
return t('chat.shippingOrderReview.llmSuggestion.unavailableDisabled');
}
return t('chat.shippingOrderReview.llmSuggestion.unavailableProvider');
}
const statusLabel = computed(() => {
if (props.suggestionLoading) return t('chat.shippingOrderReview.llmSuggestion.status.pending');
const latest = (props.suggestions || [])[0];
@@ -197,7 +210,18 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s
</button>
</div>
<p v-if="!pendingSuggestions.length && !failedSuggestions.length" class="mt-3 text-xs text-slate-500">
<div
v-if="unavailableSuggestions.length"
class="mt-3 rounded border border-rose-200 bg-rose-50 px-2 py-2 text-xs text-rose-700 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-300"
data-testid="review-llm-provider-unavailable"
role="alert"
>
{{ unavailableMessage(unavailableSuggestions[0]) }}
</div>
<p
v-if="!pendingSuggestions.length && !failedSuggestions.length && !unavailableSuggestions.length"
class="mt-3 text-xs text-slate-500"
>
{{ t('chat.shippingOrderReview.llmSuggestion.empty') }}
</p>
<ul v-if="pendingSuggestions.length" class="mt-3 space-y-2">
@@ -0,0 +1,182 @@
<!--
features/chat/components/shipping-review/ReviewReservationPanel.vue
用途:复核工作台 Reservation 校验摘要;展示行级有效预约号与阻断 issue。
依赖:vue-i18n、revalidateWorkspaceShippingOrderReviewReservation、showReviewResumeOutcome。
逻辑:needs_attention 时展示;编辑聚焦明细行;重校验后 emit refreshed 并展示 resume 提示。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { revalidateWorkspaceShippingOrderReviewReservation } from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type { ShippingOrderReviewReservation } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
draftVersion: number | null | undefined;
reservation: ShippingOrderReviewReservation | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
'focus-line': [lineIndex: number];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busy = ref(false);
const visible = computed(() => Boolean(props.reservation?.needs_attention || props.reservation?.issues?.length));
const lines = computed(() => props.reservation?.lines || []);
const issues = computed(() => props.reservation?.issues || []);
/**
* Reservation 状态本地化。
*/
const statusLabel = computed(() => {
const status = String(props.reservation?.status || '').trim();
const key = `chat.shippingOrderReview.reservation.status.${status}`;
if (status && te(key)) return t(key);
return props.reservation?.needs_attention
? t('chat.shippingOrderReview.reservation.status.needs_attention')
: t('chat.shippingOrderReview.reservation.status.ok');
});
/**
* issue / block_reason 本地化文案。
*/
function issueLabel(code: string | null | undefined): string {
const normalized = String(code || '').trim();
if (!normalized) return t('chat.shippingOrderReview.reservation.unknownIssue');
const key = `chat.shippingOrderReview.reservation.issues.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 聚焦明细行以便编辑 reservation_id。
*/
function onFocusLine(lineIndex: number | null | undefined) {
if (lineIndex == null || !Number.isFinite(Number(lineIndex))) return;
emit('focus-line', Number(lineIndex));
}
/**
* 显式重校验 Reservation 并刷新 Case / 建单资格。
*/
async function onRevalidate() {
if (!props.caseNo || props.draftVersion == null || !props.editable || busy.value) return;
busy.value = true;
try {
const result = await revalidateWorkspaceShippingOrderReviewReservation(props.caseNo, {
expected_draft_version: props.draftVersion,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.reservation.revalidateDone'),
);
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.reservation.revalidateFailed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-violet-200 bg-violet-50/70 p-3 shadow-sm dark:border-violet-900 dark:bg-violet-950/40"
data-testid="review-reservation-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-violet-950 dark:text-violet-50">
{{ t('chat.shippingOrderReview.reservation.title') }}
</h2>
<p class="mt-0.5 text-xs text-violet-900 dark:text-violet-200">
{{ t('chat.shippingOrderReview.reservation.subtitle') }}
</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="reservation?.needs_attention
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'"
data-testid="review-reservation-badge"
>
{{ statusLabel }}
</span>
</header>
<ul v-if="issues.length" class="mt-2 space-y-1 text-xs text-violet-950 dark:text-violet-100">
<li
v-for="(issue, idx) in issues"
:key="`${issue.code}-${issue.line_index}-${idx}`"
class="rounded border border-violet-200 bg-white/90 px-2 py-1 dark:border-violet-900 dark:bg-slate-900"
>
<span v-if="issue.line_index != null">#{{ issue.line_index + 1 }} · </span>
{{ issue.message || issueLabel(issue.code) }}
</li>
</ul>
<div v-if="lines.length" class="mt-2 overflow-x-auto">
<table class="min-w-full text-left text-xs">
<thead class="text-muted">
<tr>
<th class="px-1 py-1 font-medium">#</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.reservationId') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.action') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
class="border-t border-violet-100 dark:border-violet-900"
:class="line.needs_attention ? 'bg-amber-50/80 dark:bg-amber-950/20' : ''"
>
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
<td class="px-1 py-1 font-mono">
{{ line.effective_reservation_id || '—' }}
<span v-if="line.block_reason" class="ml-1 text-[10px] text-rose-600 dark:text-rose-400">
{{ issueLabel(line.block_reason) }}
</span>
</td>
<td class="px-1 py-1">
<button
v-if="editable && line.line_index != null"
type="button"
class="text-[11px] text-primary underline-offset-2 hover:underline"
data-testid="review-reservation-focus-line"
@click="onFocusLine(line.line_index)"
>
{{ t('chat.shippingOrderReview.reservation.editLine') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl border border-violet-300 bg-white px-3 py-1.5 text-sm text-violet-950 hover:bg-violet-100 disabled:opacity-60 dark:border-violet-800 dark:bg-slate-900 dark:text-violet-100 dark:hover:bg-violet-950"
data-testid="review-reservation-revalidate"
:disabled="busy || draftVersion == null"
@click="onRevalidate"
>
{{ busy ? t('chat.shippingOrderReview.reservation.revalidating') : t('chat.shippingOrderReview.reservation.revalidate') }}
</button>
</div>
</section>
</template>
@@ -41,7 +41,7 @@ const { t } = useI18n();
data-testid="review-version-history-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
@@ -65,10 +65,10 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
</div>
</header>
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingWorkflow.loading') }}</div>
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingProcessing.loading') }}</div>
<template v-else>
<p class="mb-2 text-xs text-slate-500 dark:text-slate-400">
{{ t('chat.shippingWorkflow.versionHistoryNote') }}
{{ t('chat.shippingProcessing.versionHistoryNote') }}
</p>
<p v-if="!versions.length" class="py-4 text-sm text-slate-500">
{{ t('chat.shippingSessionWorkItem.noVersions') }}
@@ -88,7 +88,7 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<span class="font-medium">
{{ version.version_label || t('chat.shippingWorkflow.versionLabel', { version: version.version_no || '?' }) }}
{{ version.version_label || t('chat.shippingProcessing.versionLabel', { version: version.version_no || '?' }) }}
</span>
<span
v-if="version.is_current"
@@ -14,6 +14,8 @@ const props = defineProps<{
saving: boolean;
isReadOnly: boolean;
hasDraft: boolean;
/** can_build && can_auto_create 时隐藏确认按钮并展示自动推进提示 */
hideConfirmBecauseAutoGate?: boolean;
}>();
const emit = defineEmits<{
@@ -84,6 +86,13 @@ function hasAction(action: string): boolean {
</label>
</div>
<div class="order-2 flex flex-wrap items-center justify-end gap-2 sm:order-2">
<p
v-if="hideConfirmBecauseAutoGate"
class="text-xs text-muted"
data-testid="review-auto-gate-hint"
>
{{ t('chat.shippingOrderReview.buildEligibility.autoGateProgressHint') }}
</p>
<button
v-if="hasAction('validate')"
type="button"
@@ -94,7 +103,7 @@ function hasAction(action: string): boolean {
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
</button>
<button
v-if="hasAction('confirm')"
v-if="hasAction('confirm') && !hideConfirmBecauseAutoGate"
type="button"
:disabled="saving || !canConfirmBuild"
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
@@ -2,7 +2,7 @@
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
用途:订单复核工作台顶栏,展示标题上下文与保存状态。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 run/workItem 上下文;emit back 与 open-version-history;不含对话上下文切换。
逻辑:ShippingOrderReviewView 传入 run/reviewProgressContext 上下文;emit back 与 open-version-history;不含对话上下文切换。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -18,11 +18,13 @@ const props = defineProps<{
draftConflict: boolean;
isReadOnly: boolean;
showVersionHistory?: boolean;
showAuditTrail?: boolean;
}>();
const emit = defineEmits<{
back: [];
'open-version-history': [];
'open-audit-trail': [];
}>();
const { t } = useI18n();
@@ -55,6 +57,15 @@ const subtitle = computed(() => {
<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>
</div>
<button
v-if="showAuditTrail"
type="button"
class="rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-open-audit-trail"
@click="emit('open-audit-trail')"
>
{{ t('chat.shippingOrderReview.auditTrail.open') }}
</button>
<button
v-if="showVersionHistory"
type="button"
@@ -36,6 +36,7 @@ function setMode(next: ReviewWorkbenchMode) {
</script>
<template>
<!-- 产品契约:工作台模式条始终可见,便于发现库存/证据模式入口。 -->
<div
class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-900"
data-testid="review-workbench-mode"
@@ -1,14 +1,17 @@
/**
* features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts
* 用途:确认后自动进度面板节点状态与无货代上传按钮契约。
* 用途:复核统一进度面板——UnifiedProgressTrack 挂载;人工入口仅 Gate 动作。
* 依赖:vitest、@vue/test-utils、vue-i18n stub、RouterLink stub。
* 逻辑:按 lifecycle_status 断言 done/active/pending;待登记时展示下一步说明与任务处理台入口。
* 逻辑:有 processingProjection 才渲染轨道节点;manual upload 入口需 nextActionCode;RPA 不展示人工 CTA。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewWorkflowProgressPanel from './ReviewWorkflowProgressPanel.vue';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
import type {
ShippingProcessingProjection,
ShippingReviewProgressContext,
} from '@/features/chat/types/shipping.api.types';
const messages = {
en: {
@@ -16,19 +19,25 @@ const messages = {
shippingOrderReview: {
workflowProgress: {
title: 'Auto progress',
subtitle: 'Stops at waiting for manual upload registration',
subtitle: 'Advances through freight upload',
polling: 'Refreshing…',
taskNo: 'Task {taskNo}',
progressUnavailable: 'Progress unavailable — refresh the page.',
openTaskWorkbench: 'Open task workbench to register',
noUploadHint: 'Register credentials in the task workbench',
nextStepsManualUpload:
'Next: download Excel → upload on freight platform → submit evidence and receipt',
nodes: {
building_order: 'Create task',
inventory_matching: 'Match inventory',
generating_excel: 'Generate Excel',
manual_upload_pending: 'Awaiting upload registration',
},
nextStepsGeneric: 'Manual action required — follow the system prompt.',
},
},
shippingProcessing: {
panelTitle: 'Shipping processing',
status: {
automating: 'Automating',
blocked: 'Blocked',
processing: 'Processing',
},
stage: {
freight_uploading: 'Uploading to freight',
excel_generating: 'Generating Excel',
},
},
},
@@ -38,13 +47,18 @@ const messages = {
/**
* 挂载进度面板。
*/
function mountPanel(item: Partial<ShippingWorkflowItem> | null, extras?: { taskNo?: string; polling?: boolean }) {
function mountPanel(extras?: {
taskNo?: string;
polling?: boolean;
processingProjection?: Partial<ShippingProcessingProjection> | null;
}) {
const i18n = createI18n({ legacy: false, locale: 'en', messages });
return mount(ReviewWorkflowProgressPanel, {
props: {
item: item as ShippingWorkflowItem | null,
item: null as ShippingReviewProgressContext | null,
taskNo: extras?.taskNo ?? 'SN-1',
polling: extras?.polling ?? true,
processingProjection: (extras?.processingProjection || null) as ShippingProcessingProjection | null,
},
global: {
plugins: [i18n],
@@ -59,25 +73,82 @@ function mountPanel(item: Partial<ShippingWorkflowItem> | null, extras?: { taskN
}
describe('ReviewWorkflowProgressPanel', () => {
it('marks earlier nodes done and current active', () => {
const wrapper = mountPanel({ lifecycle_status: 'generating_excel', current_stage: 'generating_excel' });
expect(wrapper.get('[data-testid="review-workflow-progress-node-building_order"]').attributes('data-state')).toBe('done');
expect(wrapper.get('[data-testid="review-workflow-progress-node-inventory_matching"]').attributes('data-state')).toBe('done');
expect(wrapper.get('[data-testid="review-workflow-progress-node-generating_excel"]').attributes('data-state')).toBe('active');
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('pending');
it('shows unavailable state without projection', () => {
const wrapper = mountPanel({ polling: false, processingProjection: null });
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="unified-progress-track"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
});
it('renders unified track nodes from projection stage', () => {
const wrapper = mountPanel({
polling: false,
processingProjection: {
status: 'processing',
stage: 'excel_generating',
sourceType: 'eml',
},
});
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(false);
const current = wrapper.findAll('[data-testid="unified-progress-node"]')
.find((node) => node.attributes('data-stage') === 'excel_generating');
expect(current?.attributes('data-current')).toBe('true');
expect(current?.attributes('data-state')).toBe('running');
});
it('lights freight_uploading and hides manual CTA while automating', () => {
const wrapper = mountPanel({
polling: false,
processingProjection: {
status: 'automating',
stage: 'freight_uploading',
sourceType: 'eml',
},
});
const freight = wrapper.findAll('[data-testid="unified-progress-node"]')
.find((node) => node.attributes('data-stage') === 'freight_uploading');
expect(freight?.attributes('data-current')).toBe('true');
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
});
it('shows manual_upload_pending next steps and task workbench link', () => {
const wrapper = mountPanel({ lifecycle_status: 'manual_upload_pending' }, { polling: false });
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('active');
it('shows task workbench link when gate next_action is manual upload', () => {
const wrapper = mountPanel({
polling: false,
processingProjection: {
status: 'blocked',
stage: 'excel_generating',
sourceType: 'eml',
currentGate: {
gateCode: 'manual_upload',
status: 'blocked',
nextActionCode: 'wait_manual_upload',
},
availableActions: ['wait_manual_upload', 'mark_manual_uploaded'],
},
});
expect(wrapper.get('[data-testid="review-manual-upload-next-steps"]').text()).toContain('download Excel');
const link = wrapper.get('[data-testid="review-open-task-workbench"]');
expect(link.text()).toContain('Open task workbench to register');
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
expect(link.attributes('href')).toContain('SN-1');
expect(wrapper.find('[data-testid="review-upload-freight"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-workflow-progress-polling"]').exists()).toBe(false);
});
it('does not show manual upload tip for blocked retry_freight_upload_rpa', () => {
const wrapper = mountPanel({
polling: false,
processingProjection: {
status: 'blocked',
stage: 'freight_uploading',
sourceType: 'eml',
currentGate: {
gateCode: 'freight_upload',
status: 'blocked',
nextActionCode: 'retry_freight_upload_rpa',
},
},
});
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
});
});
@@ -1,150 +1,147 @@
<!--
features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue
用途:复核确认后展示自动进度节点:创建任务 → 库存匹配 → 生成 Excel → 待人工上传登记。
依赖:vue-i18n、vue-router、ShippingWorkflowItem。
逻辑:ShippingOrderReviewView 在确认后挂载;按 lifecycle_status / current_stage 点亮节点;
无货代上传按钮;待登记时说明下一步并提供跳转任务处理台入口;
轮询由父级 composable 负责。
用途:复核工作台统一进度轨道(完整 15 阶密度窗口)+ Gate 下一步提示。
依赖:vue-i18n、ShippingProcessingProjection、UnifiedProgressTrack、shippingProcessingFulfillment。
逻辑:节点高亮仅读统一投影;任务台入口仅当 currentGate.nextActionCode 指人工上传。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { RouterLink } from 'vue-router';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
import type {
ShippingProcessingProjection,
ShippingReviewProgressContext,
} from '@/features/chat/types/shipping.api.types';
import {
projectionRequiresManualUploadWorkbench,
} from '@/features/chat/shipping/shippingProcessingFulfillment';
import {
resolveShippingProcessingStatusLabel,
shippingProcessingStageKey,
} from '@/features/chat/shipping/shippingProcessingLabels';
import UnifiedProgressTrack from '@/features/shipping-progress/components/UnifiedProgressTrack.vue';
const props = defineProps<{
item: ShippingWorkflowItem | null;
item: ShippingReviewProgressContext | null;
taskNo?: string | null;
polling?: boolean;
/** 统一进度投影:节点与文案的权威来源。 */
processingProjection?: ShippingProcessingProjection | null;
}>();
const { t } = useI18n();
const { t, te } = useI18n();
/** 进度节点稳定键;与 WorkflowItem lifecycle 对齐。 */
type ReviewProgressNodeKey =
| 'building_order'
| 'inventory_matching'
| 'generating_excel'
| 'manual_upload_pending';
const hasProjection = computed(() => Boolean(props.processingProjection));
const NODES: ReviewProgressNodeKey[] = [
'building_order',
'inventory_matching',
'generating_excel',
'manual_upload_pending',
];
const unifiedStatusLabel = computed(() => {
const status = props.processingProjection?.status;
if (!status) return '';
return resolveShippingProcessingStatusLabel(status, te, t);
});
/**
* 将 Item 生命周期映射到进度节点索引(0..3);未知时按建单中。
*/
function nodeIndex(status?: string | null): number {
const normalized = String(status || '').trim();
const idx = NODES.indexOf(normalized as ReviewProgressNodeKey);
if (idx >= 0) return idx;
if (['closed', 'cancelled'].includes(normalized)) return NODES.length - 1;
if (['pending_review', 'queued', 'layout_parsing', 'extracting'].includes(normalized)) return -1;
return 0;
}
const activeIndex = computed(() =>
nodeIndex(props.item?.lifecycle_status || props.item?.current_stage),
);
const showTaskWorkbenchLink = computed(() => {
const status = String(props.item?.lifecycle_status || props.item?.current_stage || '').trim();
return status === 'manual_upload_pending' && Boolean(String(props.taskNo || '').trim());
const unifiedStageLabel = computed(() => {
const stage = props.processingProjection?.stage;
if (!stage) return '';
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
});
/**
* 任务处理台路由:带 task_no,便于直接定位待登记任务。
* 仅当 Gate next_action 明确指人工上传且非 RPA 阶段时展示任务台入口。
*/
const taskWorkbenchTo = computed(() => ({
name: 'workspace-shipping-my-tasks',
query: {
task_no: String(props.taskNo || '').trim(),
},
}));
const showTaskWorkbenchLink = computed(() => {
if (!props.processingProjection) return false;
if (!projectionRequiresManualUploadWorkbench(props.processingProjection)) return false;
return Boolean(String(props.taskNo || '').trim());
});
/**
* 节点展示态:done / active / pending。
* blocked 且非人工上传时展示通用下一步提示(来自 Gate 动作 i18n)。
*/
function nodeState(index: number): 'done' | 'active' | 'pending' {
const current = activeIndex.value;
if (current < 0) return 'pending';
if (index < current) return 'done';
if (index === current) return 'active';
return 'pending';
}
const showGenericNextSteps = computed(() => {
const projection = props.processingProjection;
if (!projection || showTaskWorkbenchLink.value) return false;
const nextAction = String(projection.currentGate?.nextActionCode || '').trim();
if (!nextAction) return false;
const status = String(projection.status || '').trim().toLowerCase();
return status === 'blocked' || status === 'needs_action';
});
const genericNextStepMessage = computed(() => {
const code = String(props.processingProjection?.currentGate?.nextActionCode || '').trim();
if (code) {
const gateKey = `workspace.shippingNotice.processGate.actions.${code}`;
if (te(gateKey)) return t(gateKey);
}
return t('chat.shippingOrderReview.workflowProgress.nextStepsGeneric');
});
</script>
<template>
<section
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface-soft/60 p-3"
data-testid="review-workflow-progress-panel"
>
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workflowProgress.title') }}</h2>
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingOrderReview.workflowProgress.title') }}
</div>
<div
v-if="hasProjection && (unifiedStatusLabel || unifiedStageLabel)"
class="mt-0.5 text-[11px] text-secondary"
data-testid="review-progress-unified-label"
>
<span v-if="unifiedStatusLabel">{{ unifiedStatusLabel }}</span>
<span v-if="unifiedStageLabel"> · {{ unifiedStageLabel }}</span>
</div>
<div
v-else-if="!hasProjection"
class="mt-0.5 text-[11px] text-amber-700 dark:text-amber-300"
data-testid="review-progress-unavailable"
>
{{ t('chat.shippingOrderReview.workflowProgress.progressUnavailable') }}
</div>
<div v-else class="mt-0.5 text-[11px] text-secondary">
{{ t('chat.shippingOrderReview.workflowProgress.subtitle') }}
</p>
</div>
</div>
<span
v-if="polling"
class="text-xs text-sky-700 dark:text-sky-300"
class="shrink-0 text-[11px] text-muted"
data-testid="review-workflow-progress-polling"
>
{{ t('chat.shippingOrderReview.workflowProgress.polling') }}
</span>
</header>
</div>
<div class="mt-3" data-testid="review-progress-nodes">
<UnifiedProgressTrack
:projection="processingProjection"
density="review"
/>
</div>
<div
v-if="taskNo"
class="mb-3 flex flex-wrap items-center gap-2 text-xs text-slate-600 dark:text-slate-400"
v-if="showTaskWorkbenchLink"
class="mt-3 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-manual-upload-next-steps"
>
<span>{{ t('chat.shippingOrderReview.workflowProgress.taskNo', { taskNo }) }}</span>
<p>{{ t('chat.shippingOrderReview.workflowProgress.nextStepsManualUpload') }}</p>
<RouterLink
v-if="showTaskWorkbenchLink"
:to="taskWorkbenchTo"
class="inline-flex items-center rounded-lg bg-brand-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-brand-700"
class="mt-1 inline-flex font-medium text-brand-700 underline dark:text-brand-300"
:to="{ name: 'workspace-shipping-my-tasks', query: { task_no: taskNo || undefined } }"
data-testid="review-open-task-workbench"
>
{{ t('chat.shippingOrderReview.workflowProgress.openTaskWorkbench') }}
</RouterLink>
</div>
<ol class="space-y-2" data-testid="review-workflow-progress-nodes">
<li
v-for="(key, index) in NODES"
:key="key"
class="flex items-center gap-3 rounded-lg border px-3 py-2 text-sm"
:class="{
'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100': nodeState(index) === 'done',
'border-sky-200 bg-sky-50 text-sky-950 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-100': nodeState(index) === 'active',
'border-slate-200 bg-slate-50 text-slate-500 dark:border-slate-800 dark:bg-slate-950/40 dark:text-slate-400': nodeState(index) === 'pending',
}"
:data-testid="`review-workflow-progress-node-${key}`"
:data-state="nodeState(index)"
>
<span class="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-semibold">
{{ index + 1 }}
</span>
<span>{{ t(`chat.shippingOrderReview.workflowProgress.nodes.${key}`) }}</span>
</li>
</ol>
<p
v-if="showTaskWorkbenchLink"
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-manual-upload-next-steps"
<div
v-else-if="showGenericNextSteps"
class="mt-3 rounded-md border border-default bg-surface-soft px-2.5 py-2 text-[11px] text-secondary"
data-testid="review-generic-next-steps"
>
{{ t('chat.shippingOrderReview.workflowProgress.nextStepsManualUpload') }}
</p>
<p
v-else
class="mt-3 text-xs text-slate-500 dark:text-slate-400"
>
{{ t('chat.shippingOrderReview.workflowProgress.noUploadHint') }}
</p>
<p>{{ genericNextStepMessage }}</p>
</div>
</section>
</template>
@@ -0,0 +1,318 @@
/**
* features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts
* 用途:验收右侧任务分组卡——needs_action/processing 与短时反馈标签。
* 依赖:Vitest、Vue Test Utils、vue-i18n、ShippingConversationProcessingCard。
* 逻辑:构造 ConversationProcessingProjection;断言分组、焦点 emit;右侧不渲染 history。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import chatZhCn from '@/locales/zh-CN/chat.json';
import type { ConversationProcessingProjection } from '@/features/chat/types/shipping.api.types';
import ShippingConversationProcessingCard from './ShippingConversationProcessingCard.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn } },
});
function buildProjection(): ConversationProcessingProjection {
return {
summary: { total_tasks: 3, processing: 1, needs_action: 1, completed: 1, history: 0 },
focused_task_no: 'OT-PROC',
recent_task_no: 'OT-PROC',
needs_action: [{
user_task_no: 'OT-NEED',
group: 'needs_action',
status_label: 'pending_review',
file_count: 2,
run_no: 'RUN-NEED',
can_append: false,
recently_created: false,
}],
processing: [{
user_task_no: 'OT-PROC',
submission_ordinal: 2,
group: 'processing',
status_label: 'extracting',
file_count: 1,
run_no: 'RUN-PROC',
can_append: true,
recently_created: true,
focused: true,
}],
completed: [{
user_task_no: 'OT-DONE',
group: 'completed',
status_label: 'completed',
title: 'done.pdf',
file_count: 1,
run_no: 'RUN-DONE',
can_append: false,
available_actions: ['view_details'],
}],
history: [{
user_task_no: 'OT-HIST',
group: 'history',
status_label: 'completed',
file_count: 1,
run_no: 'RUN-HIST',
can_append: false,
viewed: true,
}],
};
}
describe('ShippingConversationProcessingCard', () => {
it('renders needs_action / processing / completed groups, hides history on the right panel', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection: buildProjection() },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-needs_action"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-completed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').exists()).toBe(true);
expect(wrapper.text()).toContain('刚刚创建');
expect(wrapper.text()).toContain('已完成');
// UI-04:右侧不展示处理记录分组。
expect(wrapper.find('[data-testid="shipping-processing-group-history"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-HIST"]').exists()).toBe(false);
});
it('renders multi-PDF task title instead of first filename', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
summary: { total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
needs_action: [{
user_task_no: 'OT-MULTI',
group: 'needs_action',
status_label: 'pending_review',
title: null,
display_kind: 'multi_document_task',
document_names: ['4518838152.pdf', '4518838154.pdf'],
file_count: 2,
run_no: 'RUN-MULTI',
can_append: false,
available_actions: ['view_details', 'cancel_task'],
}],
processing: [],
completed: [],
history: [],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('2 个 PDF');
expect(wrapper.text()).toContain('4518838152.pdf、4518838154.pdf');
expect(wrapper.text()).toContain('取消整个任务');
// 主标题不得单独伪装成首个 PDF 文件名任务。
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
expect(titleEl.text()).toContain('订单识别任务');
expect(titleEl.text()).not.toContain('4518838152.pdf');
});
it('shows multi-document title from authoritative projection without workflow fallback', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
summary: { total_tasks: 1, total_files: 2, processing: 0, needs_action: 1, completed: 0, history: 0 },
needs_action: [{
user_task_no: 'OT-MULTI',
group: 'needs_action',
status_label: 'pending_review',
title: null,
display_kind: 'multi_document_task',
document_names: ['4518838152.pdf', '4518838154.pdf'],
file_count: 2,
run_no: 'RUN-MULTI',
can_append: false,
available_actions: ['view_details', 'cancel_task'],
objects: [],
}],
processing: [],
completed: [],
history: [],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('2 个 PDF');
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
expect(titleEl.text()).toContain('订单识别任务');
expect(titleEl.text()).not.toContain('4518838152.pdf');
});
it('falls back to unnamed PDF instead of internal OT number', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
summary: { total_tasks: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
needs_action: [],
processing: [{
user_task_no: 'OT-20260803-A13F95D2',
group: 'processing',
status_label: 'processing',
title: null,
file_count: 1,
run_no: 'SNER-X',
can_append: false,
}],
completed: [],
history: [],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('未命名 PDF');
expect(wrapper.text()).not.toContain('20260803-A13F95D2');
});
it('emits focus only when selecting a task (not viewed)', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection: buildProjection() },
global: { plugins: [i18n] },
});
await flushPromises();
await wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] button').trigger('click');
expect(wrapper.emitted('focus')?.[0]).toEqual(['OT-NEED']);
expect(wrapper.emitted('viewed')).toBeUndefined();
expect(wrapper.emitted('expandFiles')).toBeUndefined();
});
it('applies visible focus ring on needs_action card when focused', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
...buildProjection(),
focused_task_no: 'OT-NEED',
},
},
global: { plugins: [i18n] },
});
await flushPromises();
const needCard = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
// 关键断言:待操作聚焦卡必须有用户可见 ring,不能只写 data-focused。
expect(needCard.attributes('data-focused')).toBe('1');
expect(needCard.classes().join(' ')).toContain('ring-brand-400');
const other = wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]');
expect(other.attributes('data-focused')).toBe('0');
expect(other.classes().join(' ')).not.toContain('ring-brand-400');
});
it('emits expandFiles / collapseFiles when toggling file details', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
...buildProjection(),
needs_action: [{
...buildProjection().needs_action[0],
available_actions: ['view_details', 'open_review', 'cancel_task'],
}],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
const taskRoot = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
const buttons = taskRoot.findAll('button');
// 最后一个按钮是展开/收起文件详情
await buttons[buttons.length - 1].trigger('click');
expect(wrapper.emitted('expandFiles')?.[0]?.[0]).toMatchObject({ user_task_no: 'OT-NEED' });
await buttons[buttons.length - 1].trigger('click');
expect(wrapper.emitted('collapseFiles')).toBeTruthy();
});
it('renders twenty processing tasks in one top-level container', async () => {
const processing = Array.from({ length: 20 }, (_, index) => ({
user_task_no: `OT-${index}`,
group: 'processing' as const,
status_label: 'extracting',
file_count: 1,
run_no: `RUN-${index}`,
can_append: false,
}));
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
summary: { total_tasks: 20, processing: 20, needs_action: 0, history: 0 },
needs_action: [],
processing,
history: [],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.findAll('[data-testid^="shipping-processing-task-"]')).toHaveLength(20);
expect(wrapper.findAll('[data-testid="shipping-conversation-processing-card"]')).toHaveLength(1);
});
it('renders pending order_intake work items above task groups', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: null,
workItems: [{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'failed',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-04T12:00:00Z',
currentGate: {
gateCode: 'intake_document_parse',
status: 'blocked',
nextActionCode: 'retry_parse',
blockingReasonCode: 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
attemptNo: 2,
},
availableActions: ['view_details', 'retry_parse'],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 1,
parsedDocumentCount: 0,
candidateCount: 0,
customerName: null,
poNumber: null,
failureReasonCode: 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
parseAttemptCount: 2,
assetStatus: 'ready',
},
childOrderTasks: [],
}],
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-intake-SNI-1"]').exists()).toBe(true);
expect(wrapper.text()).toContain('po.pdf');
// 关键断言:失败恢复元信息(原因 / Attempt / 资产)出现在材料卡。
expect(wrapper.find('[data-testid="shipping-processing-intake-recovery"]').exists()).toBe(true);
expect(wrapper.text()).toContain('SHIPPING_NOTICE.INTAKE_PARSE_FAILED');
await wrapper.find('[data-testid="shipping-processing-intake-action-retry_parse"]').trigger('click');
expect(wrapper.emitted('intakeAction')?.[0]?.[0]).toMatchObject({
action: 'retry_parse',
item: { workItemNo: 'SNI-1' },
});
});
});
@@ -0,0 +1,686 @@
/**
* features/chat/components/shipping/ShippingConversationProcessingCard.vue
* 用途:右侧「本次处理中」顶层任务卡——按 needs_action / processing / completed 展示。
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
* shippingProcessingLabels。
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems,禁止 Workflow fallback;
* 单 PDF 主标题用文件名,多 PDF 用「订单识别任务」;右侧不渲染 history;
* 任务级操作只消费后端 available_actions;另渲染尚未建 OT 的 order_intake 材料卡。
*/
<script setup lang="ts">
import { computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight } from 'lucide-vue-next';
import type {
ConversationProcessingProjection,
ConversationProcessingUserTask,
ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import {
createConversationProcessingUiState,
focusTaskManually,
markTaskViewed,
resetConversationProcessingUiState,
resolveFocusedTask,
shouldExpandTaskDetails,
toggleTaskDetails,
} from '@/features/chat/shipping/conversationProcessingState';
import {
resolveShippingProcessingMessage,
resolveShippingProcessingStatusLabel,
shippingProcessingSourceTypeKey,
shippingProcessingStageKey,
} from '@/features/chat/shipping/shippingProcessingLabels';
const props = defineProps<{
projection: ConversationProcessingProjection | null;
/** 统一 ShippingProcessing work_items(含 order_intake) */
workItems?: ShippingProcessingProjection[] | null;
/** 当前会话 ID;切换时重置本地焦点/展开状态 */
conversationId?: string | null;
}>();
const emit = defineEmits<{
focus: [taskNo: string];
viewed: [taskNo: string];
/** 请求展开某任务下的文件列表(由 Timeline 按 OT objects 合成) */
expandFiles: [task: ConversationProcessingUserTask];
/** 收起文件详情:父级应清空过滤并隐藏文件列表 */
collapseFiles: [];
/** 任务级权威操作(后端 available_actions) */
taskAction: [payload: { task: ConversationProcessingUserTask; action: string }];
/** Intake 级统一投影动作(如 retry_parse) */
intakeAction: [payload: { item: ShippingProcessingProjection; action: string }];
}>();
const { t, te } = useI18n();
const uiState = createConversationProcessingUiState();
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
const activeProjection = computed((): ConversationProcessingProjection | null => (
props.projection || null
));
/** 尚未建 OT、仍应展示在「待处理材料」的 Intake 工作项。 */
const pendingIntakeItems = computed((): ShippingProcessingProjection[] => {
const items = Array.isArray(props.workItems) ? props.workItems : [];
return items.filter((item) => {
if (item.workItemType !== 'order_intake') return false;
return !['completed', 'cancelled'].includes(String(item.status || ''));
});
});
const hasContent = computed(() => Boolean(
activeProjection.value
|| pendingIntakeItems.value.length,
));
const completedTasks = computed(() => activeProjection.value?.completed || []);
const focusedTaskNo = computed(() => resolveFocusedTask(uiState, {
serverFocusedTaskNo: activeProjection.value?.focused_task_no,
recentTaskNo: activeProjection.value?.recent_task_no,
}));
/**
* 切会话时重置本地焦点/展开,避免跨会话残留。
*/
watch(
() => String(props.conversationId || '').trim(),
(next, prev) => {
if (next === prev) return;
resetConversationProcessingUiState(uiState);
},
);
/**
* 点击任务卡:只聚焦,不标记正式 viewed、不强制展开文件。
* 非权威任务号仅更新本地 UI 焦点,不向后端 focus 写接口。
*/
function onSelectTask(task: ConversationProcessingUserTask) {
const taskNo = String(task.user_task_no || '').trim();
if (!taskNo) return;
focusTaskManually(uiState, taskNo, { expandDetails: false });
if (task.user_task_authoritative === false) return;
emit('focus', taskNo);
}
/**
* 切换文件详情展开;展开时通知父级过滤,收起时清空过滤。
*/
function onToggleDetails(task: ConversationProcessingUserTask) {
const taskNo = String(task.user_task_no || '').trim();
if (!taskNo) return;
toggleTaskDetails(uiState, taskNo);
if (uiState.expandedDetailTaskNo === taskNo) {
markTaskViewed(uiState, taskNo);
emit('expandFiles', task);
} else {
emit('collapseFiles');
}
}
/**
* 是否为多 PDF 任务卡(禁止用首个文件名伪装单文件任务)。
*/
function isMultiDocumentTask(task: ConversationProcessingUserTask): boolean {
if (String(task.display_kind || '').trim() === 'multi_document_task') return true;
if (Number(task.file_count || 0) > 1) return true;
return Array.isArray(task.document_names) && task.document_names.length > 1;
}
/**
* 任务主标题:单 PDF 用文件名;多 PDF 用 i18n「订单识别任务」;禁止 OT/Run 编号。
*/
function taskLabel(task: ConversationProcessingUserTask): string {
if (isMultiDocumentTask(task)) {
return t('chat.shippingProcessing.multiPdfTaskTitle');
}
const title = String(task.title || '').trim();
if (title) return title;
return t('chat.shippingProcessing.unnamedPdf');
}
/**
* 多 PDF 副标题:前两个文件名;超过两个时追加「等 N 个 PDF」。
*/
function documentNamesPreview(task: ConversationProcessingUserTask): string {
const names = (Array.isArray(task.document_names) ? task.document_names : [])
.map((name) => String(name || '').trim())
.filter(Boolean);
if (names.length <= 1) return '';
const head = names.slice(0, 2).join(t('chat.shippingProcessing.multiPdfNameSeparator'));
if (names.length === 2) return head;
return t('chat.shippingProcessing.multiPdfNamesMore', {
names: head,
count: names.length,
});
}
/**
* 文件数量文案:多 PDF 用「N 个 PDF」,单文件仍用「N 个文件」。
*/
function fileCountLabel(task: ConversationProcessingUserTask): string {
const count = Number(task.file_count || 0);
if (count <= 0) return '';
if (isMultiDocumentTask(task)) {
return t('chat.shippingProcessing.taskPdfCount', { count });
}
return t('chat.shippingProcessing.taskFiles', { count });
}
/**
* 任务状态文案:优先统一 shippingProcessing,回退 shippingWorkflow。
*/
function statusLabel(task: ConversationProcessingUserTask): string {
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
}
/**
* 最近活动时间:当天仅时分;昨天带「昨天」;更早带月日。
*/
function activityLabel(task: ConversationProcessingUserTask): string {
const raw = String(task.last_activity_at || '').trim();
if (!raw) return '';
const date = new Date(raw);
if (Number.isNaN(date.getTime())) return '';
const hh = String(date.getHours()).padStart(2, '0');
const mm = String(date.getMinutes()).padStart(2, '0');
const time = `${hh}:${mm}`;
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const startOfTarget = new Date(date.getFullYear(), date.getMonth(), date.getDate());
const dayDiff = Math.round((startOfToday.getTime() - startOfTarget.getTime()) / 86400000);
if (dayDiff === 0) {
return t('chat.shippingProcessing.updatedAt', { time });
}
if (dayDiff === 1) {
return t('chat.shippingProcessing.updatedYesterday', { time });
}
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return t('chat.shippingProcessing.updatedOnDate', { date: `${month}-${day}`, time });
}
/**
* 是否高亮 needs_action 任务。
*/
function isNeedsActionHighlight(task: ConversationProcessingUserTask): boolean {
return task.group === 'needs_action';
}
/**
* 是否展开该任务的文件详情区。
*/
function isDetailsExpanded(task: ConversationProcessingUserTask): boolean {
return shouldExpandTaskDetails(uiState, task.user_task_no, {
focusedTaskNo: focusedTaskNo.value,
forceExpand: false,
});
}
/**
* 任务级可见操作:只展示后端权威动作中的业务入口。
*/
function visibleTaskActions(task: ConversationProcessingUserTask): string[] {
const actions = Array.isArray(task.available_actions) ? task.available_actions : [];
const preferred = [
'view_details',
'open_review',
'enter_manual_review',
'retry_failed_documents',
'retry_failed_attachments',
'cancel_task',
'cancel_run',
];
const seen = new Set<string>();
const result: string[] = [];
for (const code of preferred) {
if (!actions.includes(code) || seen.has(code)) continue;
// 别名去重:只保留一套展示
if (code === 'open_review' && seen.has('enter_manual_review')) continue;
if (code === 'enter_manual_review' && seen.has('open_review')) continue;
if (code === 'retry_failed_documents' && seen.has('retry_failed_attachments')) continue;
if (code === 'retry_failed_attachments' && seen.has('retry_failed_documents')) continue;
if (code === 'cancel_task' && seen.has('cancel_run')) continue;
if (code === 'cancel_run' && seen.has('cancel_task')) continue;
seen.add(code);
result.push(code);
}
return result;
}
/**
* 动作按钮文案:任务级取消在多 PDF 时明确为「取消整个任务」。
*/
function actionLabel(task: ConversationProcessingUserTask, action: string): string {
const code = String(action || '').trim();
if (
(code === 'cancel_task' || code === 'cancel_run')
&& isMultiDocumentTask(task)
) {
return t('chat.shippingProcessing.cancelEntireTask');
}
if (code === 'cancel_task' || code === 'cancel_run') {
return t('chat.shippingProcessing.cancelEntireTaskSingle');
}
const extractionKey = `chat.shippingOrderExtractionAction.${code}`;
if (te(extractionKey)) return t(extractionKey);
const aliases: Record<string, string> = {
open_review: 'chat.shippingOrderExtractionAction.enter_manual_review',
retry_failed_documents: 'chat.shippingOrderExtractionAction.retry_failed_attachments',
};
const alias = aliases[code];
if (alias && te(alias)) return t(alias);
return code;
}
/**
* 执行任务级动作:view_details 展开文件;其余交给父级。
* 非权威任务号禁止向后端 focus/viewed 写接口。
*/
function onTaskAction(task: ConversationProcessingUserTask, action: string) {
const code = String(action || '').trim();
if (!code) return;
if (code === 'view_details') {
focusTaskManually(uiState, task.user_task_no, { expandDetails: true });
markTaskViewed(uiState, task.user_task_no);
emit('expandFiles', task);
if (task.user_task_authoritative !== false) {
emit('focus', task.user_task_no);
emit('viewed', task.user_task_no);
}
return;
}
emit('taskAction', { task, action: code });
}
/**
* Intake 材料标题:文件名 / 邮件主题 / Intake 编号。
*/
function intakeTitle(item: ShippingProcessingProjection): string {
return String(
item.sourceSummary?.filename
|| item.sourceSummary?.emailSubject
|| item.workItemNo
|| '',
).trim() || item.workItemNo;
}
/**
* Intake 状态文案。
*/
function intakeStatusLabel(item: ShippingProcessingProjection): string {
return resolveShippingProcessingStatusLabel(item.status, te, t);
}
/**
* Intake 阶段文案。
*/
function intakeStageLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingStageKey(item.stage);
return te(key) ? t(key) : String(item.stage || '');
}
/**
* Intake 来源类型文案。
*/
function intakeSourceLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingSourceTypeKey(item.sourceType);
return te(key) ? t(key) : String(item.sourceType || '');
}
/**
* Intake / OT 门禁与失败恢复元信息(Gate / Attempt / 资产状态)。
*/
function intakeRecoveryMeta(item: ShippingProcessingProjection): string[] {
const parts: string[] = [];
const gate = item.currentGate;
const reason = String(
gate?.blockingReasonCode
|| item.sourceSummary?.failureReasonCode
|| '',
).trim();
if (reason) {
parts.push(t('chat.shippingProcessing.failureReason', { code: reason }));
}
const attempt = gate?.attemptNo ?? item.sourceSummary?.parseAttemptCount;
if (attempt != null && Number(attempt) > 0) {
parts.push(t('chat.shippingProcessing.parseAttempt', { count: Number(attempt) }));
}
const assetStatus = String(item.sourceSummary?.assetStatus || '').trim();
if (assetStatus) {
const key = `chat.shippingProcessing.assetStatus.${assetStatus}`;
parts.push(te(key) ? t(key) : t('chat.shippingProcessing.assetStatusLabel', { status: assetStatus }));
}
if (gate?.gateCode) {
parts.push(t('chat.shippingProcessing.gateCode', { code: gate.gateCode }));
}
return parts;
}
/**
* Intake 可见动作(仅展示 retry_parse)。
*/
function visibleIntakeActions(item: ShippingProcessingProjection): string[] {
const actions = Array.isArray(item.availableActions) ? item.availableActions : [];
return actions.filter((code) => code === 'retry_parse');
}
/**
* Intake 动作文案。
*/
function intakeActionLabel(action: string): string {
if (action === 'retry_parse') return t('chat.shippingProcessing.retryFromFailure');
return action;
}
/**
* 触发 Intake 级动作。
*/
function onIntakeAction(item: ShippingProcessingProjection, action: string) {
const code = String(action || '').trim();
if (!code) return;
emit('intakeAction', { item, action: code });
}
</script>
<template>
<div
v-if="hasContent"
class="space-y-3"
data-testid="shipping-conversation-processing-card"
>
<section
v-if="pendingIntakeItems.length"
data-testid="shipping-processing-group-order-intake"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300">
{{ t('chat.shippingProcessing.pendingMaterials') }}
· {{ pendingIntakeItems.length }}
</div>
<div class="space-y-2">
<article
v-for="item in pendingIntakeItems"
:key="item.workItemNo"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:data-testid="`shipping-processing-intake-${item.workItemNo}`"
:data-source-type="item.sourceType"
:data-status="item.status"
>
<div class="text-sm font-semibold text-primary">
{{ intakeTitle(item) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span>{{ intakeSourceLabel(item) }}</span>
<span>{{ intakeStatusLabel(item) }}</span>
<span v-if="intakeStageLabel(item)">{{ intakeStageLabel(item) }}</span>
</div>
<div
v-if="intakeRecoveryMeta(item).length"
class="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-rose-700 dark:text-rose-300"
data-testid="shipping-processing-intake-recovery"
>
<span
v-for="(meta, idx) in intakeRecoveryMeta(item)"
:key="`${item.workItemNo}-meta-${idx}`"
>{{ meta }}</span>
</div>
<div
v-if="visibleIntakeActions(item).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-intake-actions"
>
<button
v-for="action in visibleIntakeActions(item)"
:key="`${item.workItemNo}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-intake-action-${action}`"
@click="onIntakeAction(item, action)"
>
{{ intakeActionLabel(action) }}
</button>
</div>
</article>
</div>
</section>
<section
v-if="activeProjection?.needs_action.length"
data-testid="shipping-processing-group-needs_action"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: activeProjection.needs_action.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in activeProjection.needs_action"
:key="task.user_task_no"
class="rounded-lg border px-2.5 py-2 transition"
:class="[
isNeedsActionHighlight(task)
? 'border-amber-400 bg-amber-50/80 dark:border-amber-700 dark:bg-amber-950/30'
: 'border-default bg-surface',
focusedTaskNo === task.user_task_no ? 'ring-1 ring-brand-400' : '',
]"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button
type="button"
class="w-full text-left"
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
</div>
<div
v-if="documentNamesPreview(task)"
class="mt-0.5 truncate text-[11px] text-muted"
data-testid="shipping-processing-task-document-names"
>
{{ documentNamesPreview(task) }}
</div>
<div
v-if="task.recent_append_count"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
>
{{ resolveShippingProcessingMessage('justAppended', te, t, { count: task.recent_append_count }) }}
</div>
<div
v-else-if="task.recently_created"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
>
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
</div>
</button>
<div
v-if="visibleTaskActions(task).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-task-actions"
>
<button
v-for="action in visibleTaskActions(task)"
:key="`${task.user_task_no}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-action-${action}`"
@click="onTaskAction(task, action)"
>
{{ actionLabel(task, action) }}
</button>
</div>
<button
type="button"
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
@click="onToggleDetails(task)"
>
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
<ChevronRight v-else class="h-3 w-3" />
{{ isDetailsExpanded(task)
? t('chat.shippingProcessing.collapseFileDetails')
: t('chat.shippingProcessing.expandFileDetails') }}
</button>
</article>
</div>
</section>
<section
v-if="activeProjection?.processing.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">
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: activeProjection.processing.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in activeProjection.processing"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:class="focusedTaskNo === task.user_task_no
? 'ring-1 ring-brand-400'
: ''"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button
type="button"
class="w-full text-left"
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
</div>
<div
v-if="documentNamesPreview(task)"
class="mt-0.5 truncate text-[11px] text-muted"
data-testid="shipping-processing-task-document-names"
>
{{ documentNamesPreview(task) }}
</div>
<div
v-if="task.recent_append_count"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
>
{{ resolveShippingProcessingMessage('justAppended', te, t, { count: task.recent_append_count }) }}
</div>
<div
v-else-if="task.recently_created"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
>
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
</div>
</button>
<div
v-if="visibleTaskActions(task).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-task-actions"
>
<button
v-for="action in visibleTaskActions(task)"
:key="`${task.user_task_no}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-action-${action}`"
@click="onTaskAction(task, action)"
>
{{ actionLabel(task, action) }}
</button>
</div>
<button
type="button"
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
@click="onToggleDetails(task)"
>
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
<ChevronRight v-else class="h-3 w-3" />
{{ isDetailsExpanded(task)
? t('chat.shippingProcessing.collapseFileDetails')
: t('chat.shippingProcessing.expandFileDetails') }}
</button>
</article>
</div>
</section>
<section
v-if="completedTasks.length"
data-testid="shipping-processing-group-completed"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-emerald-700 dark:text-emerald-300">
{{ resolveShippingProcessingMessage('groupCompleted', te, t, { count: completedTasks.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in completedTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:class="focusedTaskNo === task.user_task_no
? 'ring-1 ring-brand-400'
: ''"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button
type="button"
class="w-full text-left"
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
</div>
<div
v-if="documentNamesPreview(task)"
class="mt-0.5 truncate text-[11px] text-muted"
data-testid="shipping-processing-task-document-names"
>
{{ documentNamesPreview(task) }}
</div>
</button>
<div
v-if="visibleTaskActions(task).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-task-actions"
>
<button
v-for="action in visibleTaskActions(task)"
:key="`${task.user_task_no}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-action-${action}`"
@click="onTaskAction(task, action)"
>
{{ actionLabel(task, action) }}
</button>
</div>
<button
type="button"
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
@click="onToggleDetails(task)"
>
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
<ChevronRight v-else class="h-3 w-3" />
{{ isDetailsExpanded(task)
? t('chat.shippingProcessing.collapseFileDetails')
: t('chat.shippingProcessing.expandFileDetails') }}
</button>
</article>
</div>
</section>
</div>
</template>
@@ -2,12 +2,10 @@
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
* 用途:聊天主区批次进度卡——摘要计数、Run 级处理事项、当前文件阶段、健康提醒与动作。
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、
* orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
* Run 失败优先展示 errorExplainability.message(含 request_id 提示),禁止只展示技术错误码;
* 「查看处理详情」挂载详情抽屉;抽屉内证据/复核入口携带 focus+document_id 打开复核页;
* 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细;
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗。
* orderExtractionProgressDisplay、vue-router、vue-i18n、ProcessGateRecoveryCard。
* 逻辑:回退 handling_items / primary_notice / Run summary;
* Run 失败优先展示 errorExplainability.message;详情抽屉证据入口携带 focus+document_id;
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗;不再读取 Workflow 空壳 counts。
*/
<script setup lang="ts">
import { computed, inject, ref } from 'vue';
@@ -23,7 +21,6 @@ import type {
ShippingOrderExtractionDocumentResult,
ShippingOrderExtractionProgressEvent,
ShippingProcessGateUserSummary,
ShippingWorkflowItemCounts,
} from '../../types/shipping.api.types';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import {
@@ -39,7 +36,6 @@ import {
type ShippingHandlingAffectedRef,
type ShippingHandlingRefTarget,
} from '../../shipping/orderExtractionHandlingRefs';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
const props = defineProps<{
@@ -48,8 +44,9 @@ const props = defineProps<{
retrying?: boolean;
refreshing?: boolean;
cancelling?: boolean;
/** 可选:父级传入的 Workflow 计数;优先于 Run summary。 */
workflowSummary?: ShippingWorkflowItemCounts | null;
/** 新版 Run 已替代旧版时,历史卡仅允许查看详情。 */
readonly?: boolean;
readonlyReason?: string | null;
}>();
const emit = defineEmits<{
@@ -64,7 +61,6 @@ const router = useRouter();
const chatPage = inject(CHAT_PAGE_KEY, null);
const confirmCancelOpen = ref(false);
const cancelReason = ref('');
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
/**
* Gate 恢复卡「确认客户」:打开对话叠层客户选择弹窗。
@@ -74,15 +70,9 @@ async function onGateConfirmCustomer(taskNo: string) {
}
/**
* 从 Workflow Items 中取首个阻断 Gate 摘要,供 Run 级卡片展示。
* Run 级阻断 Gate:co8 后不再从 Workflow items 读取;由复核/Gate 主路径承接。
*/
const runLevelProcessGate = computed((): ShippingProcessGateUserSummary | null => {
const items = injectedWorkflow?.items.value || [];
for (const item of items) {
if (item.process_gate?.current_blocking_gate) return item.process_gate;
}
return null;
});
const runLevelProcessGate = computed((): ShippingProcessGateUserSummary | null => null);
const gateNavigationContext = computed(() => ({
agentId: String(route.params.agentId || ''),
@@ -97,47 +87,10 @@ const progressLoading = ref(false);
const progressLoadFailed = ref(false);
const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
/**
* 统一计数:优先 props.workflowSummary,其次 inject 的 Workflow.counts,最后回退 Run summary。
*/
const unifiedCounts = computed(() => {
const fromProp = props.workflowSummary;
if (fromProp && Number(fromProp.total || 0) > 0) return fromProp;
const fromInject = injectedWorkflow?.workflow.value?.counts;
if (fromInject && Number(fromInject.total || 0) > 0) return fromInject;
return null;
});
const displaySummary = computed(() => props.state.summary);
const displaySummary = computed(() => {
const counts = unifiedCounts.value;
if (!counts) return props.state.summary;
return {
totalDocuments: counts.total,
processingDocuments: counts.processing,
pendingDocuments: 0,
completedDocuments: counts.completed,
reviewRequiredDocuments: counts.pending_review,
failedDocuments: counts.failed,
cancelledDocuments: 0,
candidateCount: props.state.summary.candidateCount,
openedExistingCount: props.state.summary.openedExistingCount,
};
});
const workflowStageLabel = computed(() => {
const stage = String(injectedWorkflow?.workflow.value?.current_stage || '').trim();
if (!stage) return '';
const key = `chat.shippingWorkflow.itemStatus.${stage}`;
return te(key) ? t(key) : stage;
});
const workflowLastActivityLabel = computed(() => {
const raw = injectedWorkflow?.workflow.value?.last_activity_at;
if (!raw) return '';
const date = new Date(String(raw));
if (Number.isNaN(date.getTime())) return '';
return date.toLocaleString();
});
const workflowStageLabel = computed(() => '');
const workflowLastActivityLabel = computed(() => '');
const handlingItems = computed(() => props.state.handlingItems || []);
@@ -261,11 +214,15 @@ const activityKey = computed(() => {
});
const showRetry = computed(() => (
!props.readonly && (
props.state.availableActions.includes('retry_failed_attachments')
|| displaySummary.value.failedDocuments > 0
)
));
const showRefresh = computed(() => props.state.availableActions.includes('refresh_status'));
const showRefresh = computed(() => !props.readonly && props.state.availableActions.includes('refresh_status'));
const showCancel = computed(() => (
!props.readonly
&&
props.state.availableActions.includes('cancel_run')
&& !(props.state.cancellation?.requested && !props.state.cancellation?.completedAt)
));
@@ -404,6 +361,7 @@ function closeDetailsDrawer() {
* 从详情抽屉进入复核/证据页。
*/
async function enterReviewFromDetails(payload?: { focus?: 'evidence' | 'draft'; documentId?: number }) {
if (props.readonly) return;
await openOrderReview({
documentId: payload?.documentId,
focus: payload?.focus === 'evidence' ? 'evidence' : 'draft',
@@ -458,6 +416,7 @@ function affectedRows(item: ShippingOrderExtractionHandlingItemState) {
* @param item - 处理事项
*/
async function handleHandlingAction(item: ShippingOrderExtractionHandlingItemState) {
if (props.readonly) return;
const action = String(item.primaryAction || '').trim();
if (action === 'retry_failed_attachments') {
emit('retry');
@@ -489,6 +448,7 @@ function confirmCancel() {
/** 打开取消确认并清空上次填写的原因。 */
function openCancelConfirm() {
if (props.readonly) return;
cancelReason.value = '';
confirmCancelOpen.value = true;
}
@@ -516,6 +476,13 @@ function openCancelConfirm() {
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
<div class="min-w-0 flex-1">
<div
v-if="readonly"
class="mb-1 text-xs font-medium opacity-80"
data-testid="shipping-order-extraction-readonly"
>
{{ t('chat.shippingOrderExtractionHistory.superseded') }}
</div>
<div class="text-sm font-medium">{{ compactLine }}</div>
<p
v-if="state.errorExplainability?.request_id"
@@ -564,7 +531,7 @@ function openCancelConfirm() {
v-if="runLevelProcessGate?.current_blocking_gate"
class="mt-2"
:summary="runLevelProcessGate"
:can-handle="true"
:can-handle="!readonly"
:navigation-context="gateNavigationContext"
@refreshed="emit('refresh')"
@refresh-needed="emit('refresh')"
@@ -591,13 +558,15 @@ function openCancelConfirm() {
<span class="ml-1 opacity-80">{{ t('chat.shippingOrderExtractionHandling.count', { count: item.count }) }}</span>
</div>
<button
v-if="item.primaryAction"
v-if="item.primaryAction && !readonly && (item.primaryAction !== 'review_candidate' || !handlingItems.some((other) => other.primaryAction === 'enter_manual_review'))"
type="button"
class="shrink-0 rounded-md border border-current/20 px-2 py-0.5 text-[11px] font-medium hover:bg-black/5 dark:hover:bg-white/5"
@click="handleHandlingAction(item)"
>
{{ te(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
? t(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
{{ (item.primaryAction === 'review_candidate' || item.primaryAction === 'enter_manual_review')
? t('chat.shippingOrderExtractionAction.enter_manual_review')
: te(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
? t(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
: t('chat.shippingOrderExtractionAction.view_details') }}
</button>
</div>
@@ -616,6 +585,7 @@ function openCancelConfirm() {
:key="row.key"
type="button"
class="rounded border border-current/20 px-1.5 py-0.5 text-[11px] font-medium underline-offset-2 hover:underline"
:disabled="readonly"
@click="openAffectedRef(row.target)"
>
{{ row.label }}
@@ -65,21 +65,21 @@ const canReparse = computed(() => {
const reparseActionLabel = computed(() => {
if (props.item?.reparse_kind === 'failed_run_retry') {
return t('chat.shippingWorkflow.actions.retryFailedRun');
return t('chat.shippingProcessing.actions.retryFailedRun');
}
return t('chat.shippingWorkflow.actions.reparse');
return t('chat.shippingProcessing.actions.reparse');
});
const filename = computed(() => {
const name = String(props.item?.current_document_filename || '').trim();
if (name) return name;
if (!props.item) return '';
return t('chat.shippingWorkflow.filenameFallback', {
return t('chat.shippingProcessing.filenameFallback', {
docId: props.item.current_document_id,
});
});
const title = computed(() => t('chat.shippingWorkflow.detail.title'));
const title = computed(() => t('chat.shippingProcessing.detail.title'));
/**
* 解析生命周期 / 阶段文案。
@@ -87,8 +87,8 @@ const title = computed(() => t('chat.shippingWorkflow.detail.title'));
function statusLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '';
const key = `chat.shippingWorkflow.itemStatus.${normalized}`;
return te(key) ? t(key) : t('chat.shippingWorkflow.itemStatus.unknown');
const key = `chat.shippingProcessing.itemStatus.${normalized}`;
return te(key) ? t(key) : t('chat.shippingProcessing.itemStatus.unknown');
}
/**
@@ -97,8 +97,8 @@ function statusLabel(status?: string | null): string {
function eventLabel(event: ShippingWorkflowEvent): string {
const code = String(event.message_code || event.event_code || '').trim();
if (!code) return '—';
const key = `chat.shippingWorkflow.event.${code}`;
return te(key) ? t(key) : t('chat.shippingWorkflow.event.unknown');
const key = `chat.shippingProcessing.event.${code}`;
return te(key) ? t(key) : t('chat.shippingProcessing.event.unknown');
}
/**
@@ -226,7 +226,7 @@ onBeforeUnmount(() => {
ref="closeButtonRef"
type="button"
class="rounded-md p-1 text-muted hover:bg-surface-muted"
:aria-label="t('chat.shippingWorkflow.detail.close')"
:aria-label="t('chat.shippingProcessing.detail.close')"
data-testid="shipping-workflow-item-drawer-close"
@click="handleClose"
>
@@ -236,41 +236,41 @@ onBeforeUnmount(() => {
<div class="min-h-0 flex-1 overflow-auto p-4">
<div v-if="loading" class="text-xs text-muted">
{{ t('chat.shippingWorkflow.loading') }}
{{ t('chat.shippingProcessing.loading') }}
</div>
<template v-else-if="item">
<dl class="space-y-2 text-xs">
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.filename') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.filename') }}</dt>
<dd class="max-w-[60%] truncate font-medium text-primary" :title="filename">{{ filename }}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.status') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.status') }}</dt>
<dd class="font-medium text-primary">{{
statusLabel(item.display_lifecycle_status || item.lifecycle_status)
}}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.stage') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.stage') }}</dt>
<dd class="font-medium text-primary">{{ statusLabel(item.current_stage) || item.current_stage }}</dd>
</div>
<div v-if="item.current_run_no" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.runNo') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.runNo') }}</dt>
<dd class="font-medium text-primary">{{ item.current_run_no }}</dd>
</div>
<div v-if="item.current_case_no" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.caseNo') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.caseNo') }}</dt>
<dd class="font-medium text-primary">{{ item.current_case_no }}</dd>
</div>
<div v-if="item.last_activity_at" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.lastActivity') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.lastActivity') }}</dt>
<dd class="font-medium text-primary">{{ formatTime(item.last_activity_at) }}</dd>
</div>
<div v-if="item.closed_reason" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.closedReason') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.closedReason') }}</dt>
<dd class="font-medium text-primary">
{{ te(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
? t(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
{{ te(`chat.shippingProcessing.closedReason.${item.closed_reason}`)
? t(`chat.shippingProcessing.closedReason.${item.closed_reason}`)
: item.closed_reason }}
</dd>
</div>
@@ -289,7 +289,7 @@ onBeforeUnmount(() => {
<section class="mt-4">
<h3 class="text-xs font-semibold text-secondary">
{{ t('chat.shippingWorkflow.detail.eventsTitle') }}
{{ t('chat.shippingProcessing.detail.eventsTitle') }}
</h3>
<ul v-if="events.length" class="mt-2 space-y-2" data-testid="shipping-workflow-item-events">
<li
@@ -306,11 +306,11 @@ onBeforeUnmount(() => {
</li>
</ul>
<p v-else class="mt-2 text-xs text-muted">
{{ t('chat.shippingWorkflow.detail.eventsEmpty') }}
{{ t('chat.shippingProcessing.detail.eventsEmpty') }}
</p>
</section>
</template>
<p v-else class="text-xs text-muted">{{ t('chat.shippingWorkflow.detail.empty') }}</p>
<p v-else class="text-xs text-muted">{{ t('chat.shippingProcessing.detail.empty') }}</p>
</div>
<footer v-if="item && (canCancel || canReparse)" class="space-y-2 border-t border-default p-3">
@@ -332,7 +332,7 @@ onBeforeUnmount(() => {
data-testid="shipping-workflow-item-drawer-cancel"
@click="emit('cancel', item)"
>
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
{{ t('chat.shippingProcessing.actions.cancelFile') }}
</button>
</footer>
</aside>
@@ -32,18 +32,18 @@ const reasonInputRef = ref<HTMLTextAreaElement | null>(null);
const title = computed(() => (
props.action === 'reparse'
? t('chat.shippingWorkflow.reasonDialog.reparseTitle')
: t('chat.shippingWorkflow.reasonDialog.cancelTitle')
? t('chat.shippingProcessing.reasonDialog.reparseTitle')
: t('chat.shippingProcessing.reasonDialog.cancelTitle')
));
const confirmLabel = computed(() => (
props.action === 'reparse'
? t('chat.shippingWorkflow.reasonDialog.reparseConfirm')
: t('chat.shippingWorkflow.reasonDialog.cancelConfirm')
? t('chat.shippingProcessing.reasonDialog.reparseConfirm')
: t('chat.shippingProcessing.reasonDialog.cancelConfirm')
));
const reasonLabel = computed(() => t('chat.shippingWorkflow.reasonDialog.reasonLabel'));
const reasonRequiredHint = computed(() => t('chat.shippingWorkflow.reasonRequired'));
const reasonLabel = computed(() => t('chat.shippingProcessing.reasonDialog.reasonLabel'));
const reasonRequiredHint = computed(() => t('chat.shippingProcessing.reasonRequired'));
/**
* 关闭弹窗并重置本地表单。
@@ -128,7 +128,7 @@ onBeforeUnmount(() => {
>
<h3 class="text-sm font-semibold text-primary">{{ title }}</h3>
<p class="mt-1 text-xs text-secondary">
{{ t('chat.shippingWorkflow.reasonDialog.impact') }}
{{ t('chat.shippingProcessing.reasonDialog.impact') }}
</p>
<label class="mt-3 block text-xs text-secondary">
@@ -141,7 +141,7 @@ onBeforeUnmount(() => {
class="input-field mt-1 w-full py-1.5 text-xs"
:aria-invalid="reasonMissing"
data-testid="shipping-workflow-reason-input"
:placeholder="t('chat.shippingWorkflow.reasonDialog.reasonPlaceholder')"
:placeholder="t('chat.shippingProcessing.reasonDialog.reasonPlaceholder')"
/>
</label>
<p v-if="reasonMissing" class="mt-1 text-[11px] text-rose-600" data-testid="shipping-workflow-reason-missing">
@@ -152,7 +152,7 @@ onBeforeUnmount(() => {
v-if="action === 'reparse'"
class="mt-2 block text-xs text-secondary"
>
{{ t('chat.shippingWorkflow.reasonDialog.commentOptional') }}
{{ t('chat.shippingProcessing.reasonDialog.commentOptional') }}
<textarea
v-model="comment"
rows="2"
@@ -169,7 +169,7 @@ onBeforeUnmount(() => {
data-testid="shipping-workflow-reason-cancel"
@click="handleCancel"
>
{{ t('chat.shippingWorkflow.reasonDialog.dismiss') }}
{{ t('chat.shippingProcessing.reasonDialog.dismiss') }}
</button>
<button
type="button"
@@ -179,7 +179,7 @@ onBeforeUnmount(() => {
@click="handleConfirm"
>
{{ confirmLoading
? t('chat.shippingWorkflow.reasonDialog.submitting')
? t('chat.shippingProcessing.reasonDialog.submitting')
: confirmLabel }}
</button>
</div>
@@ -1,330 +1,464 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
* 用途:验证右侧 Workflow 时间线分组、文件名、批次切换、过滤与取消/重识别弹窗。
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。
* 逻辑:先展开侧栏并打开详情抽屉;断言 layout_parsing 可见;文件名优先;过滤与 cancel。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { createI18n } from 'vue-i18n';
import { ref } from 'vue';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';
import type { ShippingWorkflow, ShippingWorkflowItem } from '../../types/shipping.api.types';
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';
const routerPush = vi.fn(async () => undefined);
vi.mock('vue-router', () => ({
useRoute: () => ({ params: { agentId: 'agent-1' }, query: {} }),
useRouter: () => ({ push: routerPush }),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
getWorkspaceShippingWorkflowItem: vi.fn(async (itemNo: string) => ({
item_no: itemNo,
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_document_filename: 'detail.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
events: [],
})),
listWorkspaceShippingWorkflows: vi.fn(),
cancelWorkspaceShippingWorkflowItem: vi.fn(),
reparseWorkspaceShippingWorkflowItem: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
}),
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },
});
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
return {
item_no: 'SWI-1',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 10,
current_document_id: 10,
current_document_filename: 'shipping-notice.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
...patch,
};
}
function buildController(
items: ShippingWorkflowItem[],
extras?: { workflows?: ShippingWorkflow[] },
): UseShippingNoticeWorkflowReturn {
const workflowList = extras?.workflows ?? [{
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: {
total: items.length,
processing: items.filter((i) => i.lifecycle_status === 'layout_parsing' || i.lifecycle_status === 'extracting').length,
pending_review: items.filter((i) => i.lifecycle_status === 'pending_review').length,
failed: items.filter((i) => i.lifecycle_status === 'failed' || i.lifecycle_status === 'reparse_failed').length,
completed: items.filter((i) => i.lifecycle_status === 'closed').length,
},
items,
}];
const selectedWorkflowNo = ref(workflowList[0]?.workflow_no || null);
const workflows = ref(workflowList);
const workflow = ref(workflowList[0] || null);
const itemRef = ref(items);
return {
workflows,
selectedWorkflowNo,
selectWorkflow: vi.fn((no: string) => {
selectedWorkflowNo.value = no;
workflow.value = workflows.value.find((row) => row.workflow_no === no) || null;
itemRef.value = workflow.value?.items || [];
}),
workflow,
items: itemRef,
loading: ref(false),
error: ref(null),
refresh: vi.fn(async () => undefined),
cancelItem: vi.fn(async () => null),
reparseItem: vi.fn(async () => null),
stop: vi.fn(),
};
}
/**
* 展开窄侧栏并打开详情抽屉(完整列表仅在抽屉内)。
*/
async function openDetailsDrawer(wrapper: ReturnType<typeof mount>) {
const toggleCollapse = wrapper.find('[data-testid="shipping-workflow-timeline"] button');
if (toggleCollapse.exists()) {
await toggleCollapse.trigger('click');
await flushPromises();
}
const openDetails = wrapper.find('[data-testid="shipping-workflow-toggle-details"]');
expect(openDetails.exists()).toBe(true);
await openDetails.trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);
}
const mountOptions = {
global: {
plugins: [i18n],
stubs: {
// 抽屉/原因框经 Teleport;单测就地渲染便于查询。
teleport: true,
},
},
};
describe('ShippingWorkflowTimeline', () => {
beforeEach(() => {
document.body.innerHTML = '';
routerPush.mockClear();
});
it('shows layout_parsing items with filename before review case exists', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-LAYOUT',
lifecycle_status: 'layout_parsing',
current_case_no: null,
current_document_filename: 'layout.pdf',
}),
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');
expect(wrapper.text()).toContain('尚无复核单');
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);
});
it('filters to actionable items when pending-only is checked', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(false);
});
it('opens the review workspace directly for pending review items', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-REVIEW-OPEN',
lifecycle_status: 'pending_review',
current_run_no: 'RUN-REVIEW-1',
current_case_no: 'CASE-REVIEW-1',
current_document_id: 42,
}),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({
name: 'Chat',
params: { agentId: 'agent-1' },
query: expect.objectContaining({
mode: 'order-review',
run_no: 'RUN-REVIEW-1',
case_no: 'CASE-REVIEW-1',
document_id: '42',
focus: 'draft',
}),
}));
});
it('cancels an item via in-app reason dialog', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-CANCEL', lifecycle_status: 'extracting', lock_version: 3 }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
await flushPromises();
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
expect(reasonInput.exists()).toBe(true);
await reasonInput.setValue('cancel reason');
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');
await flushPromises();
expect(controller.cancelItem).toHaveBeenCalledWith('SWI-CANCEL', {
reason: 'cancel reason',
expected_lock_version: 3,
});
});
it('shows batch switcher for multiple workflows', async () => {
const itemsA = [buildItem({ item_no: 'SWI-A', workflow_no: 'SNWF-A' })];
const itemsB = [buildItem({ item_no: 'SWI-B', workflow_no: 'SNWF-B', lifecycle_status: 'failed' })];
const workflows = [
{
workflow_no: 'SNWF-A',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: { total: 1, processing: 1, pending_review: 0, failed: 0, completed: 0 },
items: itemsA,
},
{
workflow_no: 'SNWF-B',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'failed',
lock_version: 1,
counts: { total: 1, processing: 0, pending_review: 0, failed: 1, completed: 0 },
items: itemsB,
},
];
const controller = buildController(itemsA, { workflows });
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(true);
await wrapper.find('[data-testid="shipping-workflow-batch-SNWF-B"]').trigger('click');
expect(controller.selectWorkflow).toHaveBeenCalledWith('SNWF-B');
});
it('shows reparse action for failed items', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-FAIL',
lifecycle_status: 'failed',
current_document_filename: 'bad.pdf',
available_actions: ['cancel', 'reparse'],
reparse_kind: 'failed_run_retry',
}),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
expect(wrapper.text()).toContain('重试失败识别');
});
it('hides reparse for pending_review without available_actions.reparse', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-PR',
lifecycle_status: 'pending_review',
current_case_no: null,
available_actions: ['cancel'],
reparse_kind: null,
}),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(false);
});
it('keeps sidebar width when opening details dialog overlay', async () => {
const controller = buildController([buildItem()]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');
// 关键断言:弹层打开后侧栏仍固定窄宽,对话区不被列表撑开。
expect(aside.classes().join(' ')).toContain('md:w-60');
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');
expect(overlay.exists()).toBe(true);
expect(overlay.classes().join(' ')).toContain('fixed');
expect(overlay.find('[role="dialog"]').exists()).toBe(true);
});
});
/**␍
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts␍
* 用途:验证右侧「本次处理中」OT 任务卡、展开后文件明细、过滤与取消/重识别弹窗。␍
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。␍
* 逻辑:文件明细由 expandedTask.objects 经 mapUserTaskObjectsToFileRows 合成;␍
* 须先展开 processing 任务才出现文件抽屉;WF 批次切换器恒隐藏。␍
*/␍
import { mount, flushPromises } from '@vue/test-utils';␍
import { describe, expect, it, vi, beforeEach } from 'vitest';␍
import { createI18n } from 'vue-i18n';␍
import { ref } from 'vue';␍
import chatZhCn from '@/locales/zh-CN/chat.json';␍
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';␍
import type {␍
ConversationProcessingObject,␍
ConversationProcessingProjection,␍
ConversationProcessingUserTask,␍
ShippingWorkflowItem,␍
} from '../../types/shipping.api.types';␍
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';␍
␍
const routerPush = vi.fn(async () => undefined);␍
vi.mock('vue-router', () => ({␍
useRoute: () => ({ params: { agentId: 'agent-1' }, query: {} }),␍
useRouter: () => ({ push: routerPush }),␍
}));␍
␍
const api = vi.hoisted(() => ({␍
cancelRun: vi.fn(async () => ({})),␍
reparseRun: vi.fn(async () => ({})),␍
retryRun: vi.fn(async () => ({})),␍
retryIntake: vi.fn(async () => ({})),␍
}));␍
␍
vi.mock('@/features/chat/api/shipping.api', () => ({␍
cancelWorkspaceShippingOrderExtractionRun: api.cancelRun,␍
reparseWorkspaceShippingOrderExtractionRun: api.reparseRun,␍
retryWorkspaceShippingOrderExtractionRun: api.retryRun,␍
retryShippingNoticeIntake: api.retryIntake,␍
}));␍
␍
vi.mock('@/shared/composables/useMessage', () => ({␍
useMessage: () => ({␍
success: vi.fn(),␍
error: vi.fn(),␍
warning: vi.fn(),␍
info: vi.fn(),␍
}),␍
}));␍
␍
const i18n = createI18n({␍
legacy: false,␍
locale: 'zh-CN',␍
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },␍
});␍
␍
const DEFAULT_TASK_NO = 'OT-TEST';␍
␍
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {␍
return {␍
item_no: 'SWI-1',␍
workflow_no: 'SNWF-1',␍
conversation_id: 'conv-1',␍
root_document_id: 10,␍
current_document_id: 10,␍
current_document_filename: 'shipping-notice.pdf',␍
current_version_no: 1,␍
lifecycle_status: 'layout_parsing',␍
current_stage: 'layout_parsing',␍
lock_version: 1,␍
current_run_no: 'RUN-1',␍
...patch,␍
};␍
}␍
␍
type DocumentObject = ConversationProcessingObject & {␍
available_actions?: string[];␍
reparse_kind?: string | null;␍
lock_version?: number;␍
};␍
␍
/**␍
* 将 buildItem 文档行映射为 OT document object(供 processingFromDocuments 使用)。␍
*/␍
function documentObjectFromItem(doc: ShippingWorkflowItem): DocumentObject {␍
return {␍
kind: 'document',␍
object_key: doc.item_no,␍
workflow_item_no: doc.item_no,␍
label: String(doc.current_document_filename || doc.item_no),␍
filename: doc.current_document_filename ?? null,␍
status_label: doc.lifecycle_status,␍
document_id: doc.current_document_id,␍
root_document_id: doc.root_document_id,␍
content_hash: doc.content_hash ?? null,␍
current_run_no: doc.current_run_no ?? null,␍
case_no: doc.current_case_no ?? null,␍
available_actions: doc.available_actions,␍
reparse_kind: doc.reparse_kind ?? null,␍
lock_version: doc.lock_version,␍
};␍
}␍
␍
/**␍
* 构造含单个 processing 任务与 document objects 的会话投影。␍
* 核心逻辑:objects 默认由 docs 映射;taskOverrides 可覆盖任务卡字段或整组 objects。␍
*/␍
function processingFromDocuments(␍
docs: ShippingWorkflowItem[],␍
taskOverrides?: Partial<ConversationProcessingUserTask>,␍
): ConversationProcessingProjection {␍
const userTaskNo = taskOverrides?.user_task_no ?? DEFAULT_TASK_NO;␍
const objects = taskOverrides?.objects ?? docs.map(documentObjectFromItem);␍
const filenames = docs␍
.map((doc) => String(doc.current_document_filename || '').trim())␍
.filter(Boolean);␍
const task: ConversationProcessingUserTask = {␍
user_task_no: userTaskNo,␍
group: 'processing',␍
status_label: docs[0]?.lifecycle_status ?? 'extracting',␍
title: docs.length === 1 ? (docs[0]?.current_document_filename ?? null) : null,␍
display_kind: docs.length > 1 ? 'multi_document_task' : 'single_document_task',␍
document_names: filenames.length ? filenames : null,␍
file_count: docs.length,␍
run_no: docs[0]?.current_run_no ?? null,␍
can_append: false,␍
objects,␍
...taskOverrides,␍
};␍
␍
return {␍
summary: {␍
total_tasks: 1,␍
total_files: docs.length,␍
processing: 1,␍
needs_action: 0,␍
completed: 0,␍
history: 0,␍
},␍
focused_task_no: null,␍
recent_task_no: null,␍
needs_action: [],␍
processing: [task],␍
completed: [],␍
history: [],␍
};␍
}␍
␍
function buildController(␍
extras?: {␍
processing?: UseShippingNoticeWorkflowReturn['processing']['value'];␍
},␍
): UseShippingNoticeWorkflowReturn {␍
return {␍
processing: ref(extras?.processing ?? null),␍
processingWorkItems: ref([]),␍
loading: ref(false),␍
error: ref(null),␍
refresh: vi.fn(async () => undefined),␍
focusConversationTask: vi.fn(async () => undefined),␍
markConversationTaskViewed: vi.fn(async () => undefined),␍
stop: vi.fn(),␍
};␍
}␍
␍
/**␍
* 展开 processing 任务卡,使文件明细抽屉可见。␍
*/␍
async function expandProcessingTask(␍
wrapper: ReturnType<typeof mount>,␍
taskNo = DEFAULT_TASK_NO,␍
) {␍
if (wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()) {␍
return;␍
}␍
const task = wrapper.find(`[data-testid="shipping-processing-task-${taskNo}"]`);␍
expect(task.exists()).toBe(true);␍
await task.findAll('button').at(-1)!.trigger('click');␍
await flushPromises();␍
}␍
␍
async function openDetailsDrawer(␍
wrapper: ReturnType<typeof mount>,␍
taskNo = DEFAULT_TASK_NO,␍
) {␍
await flushPromises();␍
await expandProcessingTask(wrapper, taskNo);␍
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);␍
}␍
␍
const mountOptions = {␍
global: {␍
plugins: [i18n],␍
stubs: {␍
teleport: true,␍
},␍
},␍
};␍
␍
describe('ShippingWorkflowTimeline', () => {␍
beforeEach(() => {␍
document.body.innerHTML = '';␍
routerPush.mockClear();␍
});␍
␍
it('shows layout_parsing items with filename before review case exists', async () => {␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-LAYOUT',␍
lifecycle_status: 'layout_parsing',␍
current_case_no: null,␍
current_document_filename: 'layout.pdf',␍
}),␍
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:layout 文件行展示文件名␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');␍
// 断言:无复核单时展示占位文案␍
expect(wrapper.text()).toContain('尚无复核单');␍
// 断言:有 OT 任务投影时隐藏独立「当前阶段」卡(UI-F04)␍
expect(wrapper.find('[data-testid="shipping-workflow-current-stage"]').exists()).toBe(false);␍
// 断言:processing / pending_review 分组均可见␍
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);␍
});␍
␍
it('shows processing and pending-review files together by default', async () => {␍
const processing = processingFromDocuments([␍
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),␍
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:默认同时展示处理中与待复核文件␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(true);␍
});␍
␍
it('opens the review workspace directly for pending review items', async () => {␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-REVIEW-OPEN',␍
lifecycle_status: 'pending_review',␍
current_run_no: 'RUN-REVIEW-1',␍
current_case_no: 'CASE-REVIEW-1',␍
current_document_id: 42,␍
}),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');␍
// 断言:跳转 order-review 并携带 run / case / document 上下文␍
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({␍
name: 'Chat',␍
params: { agentId: 'agent-1' },␍
query: expect.objectContaining({␍
mode: 'order-review',␍
run_no: 'RUN-REVIEW-1',␍
case_no: 'CASE-REVIEW-1',␍
document_id: '42',␍
focus: 'draft',␍
}),␍
}));␍
});␍
␍
it('cancels an item via Run API from in-app reason dialog', async () => {␍
api.cancelRun.mockClear();␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-CANCEL',␍
lifecycle_status: 'extracting',␍
lock_version: 3,␍
current_run_no: 'RUN-CANCEL',␍
available_actions: ['cancel'],␍
}),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');␍
await flushPromises();␍
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');␍
// 断言:应用内原因弹窗出现␍
expect(reasonInput.exists()).toBe(true);␍
await reasonInput.setValue('cancel reason');␍
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');␍
await flushPromises();␍
// 断言:调用 Run 取消 API␍
expect(api.cancelRun).toHaveBeenCalledWith('RUN-CANCEL', { reason: 'cancel reason' });␍
});␍
␍
it('hides WF batch switcher as primary path', async () => {␍
const processing = processingFromDocuments([buildItem({ item_no: 'SWI-A' })]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: {␍
conversationId: 'conv-1',␍
controller: buildController({ processing }),␍
},␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:批次切换器不再作为主路径展示␍
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(false);␍
});␍
␍
it('shows reparse action for failed items', async () => {␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-FAIL',␍
lifecycle_status: 'failed',␍
current_document_filename: 'bad.pdf',␍
current_run_no: 'RUN-FAIL',␍
available_actions: ['cancel', 'reparse'],␍
reparse_kind: 'failed_run_retry',␍
}),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:失败项展示重识别按钮与文案␍
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);␍
expect(wrapper.text()).toContain('重试失败识别');␍
});␍
␍
it('hides reparse for pending_review without available_actions.reparse', async () => {␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-PR',␍
lifecycle_status: 'pending_review',␍
current_case_no: null,␍
available_actions: ['cancel'],␍
reparse_kind: null,␍
}),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:无 reparse 契约时不展示重识别␍
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(false);␍
});␍
␍
it('keeps sidebar width while showing inline workflow details', async () => {␍
const processing = processingFromDocuments([buildItem()]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: {␍
conversationId: 'conv-1',␍
controller: buildController({ processing }),␍
},␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');␍
// 断言:侧栏宽度不变␍
expect(aside.classes().join(' ')).toContain('md:w-[clamp(20rem,28vw,30rem)]');␍
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');␍
// 断言:文件明细内联展示,非 modal␍
expect(overlay.exists()).toBe(true);␍
expect(overlay.classes().join(' ')).toContain('rounded-xl');␍
expect(overlay.find('[role="dialog"]').exists()).toBe(false);␍
});␍
␍
it('keeps panel expanded while processing tasks exist', async () => {␍
const processing = processingFromDocuments([buildItem()], {␍
user_task_no: 'OT-PIN',␍
status_label: 'extracting',␍
title: 'order.pdf',␍
file_count: 1,␍
run_no: 'RUN-PIN',␍
});␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await flushPromises();␍
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');␍
const toggle = wrapper.find('[data-testid="shipping-workflow-panel-toggle"]');␍
// 断言:有 processing 任务时侧栏默认展开␍
expect(aside.classes().join(' ')).not.toContain('!w-14');␍
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PIN"]').exists()).toBe(true);␍
await toggle.trigger('click');␍
await flushPromises();␍
// 断言:点击收起仍保持展开(pinned)␍
expect(aside.classes().join(' ')).not.toContain('!w-14');␍
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PIN"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-panel-pinned"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-panel-summary"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-processing-summary"]').exists()).toBe(false);␍
});␍
␍
it('expands all effective PDFs for one task even when they belong to different runs', async () => {␍
const docs = [␍
buildItem({␍
item_no: 'SWI-PDF-91',␍
current_run_no: 'RUN-NEW',␍
root_document_id: 91,␍
current_document_id: 191,␍
content_hash: 'hash-a',␍
current_document_filename: '4518838152.pdf',␍
}),␍
buildItem({␍
item_no: 'SWI-PDF-92',␍
current_run_no: 'RUN-OLD',␍
root_document_id: 92,␍
current_document_id: 92,␍
content_hash: 'hash-b',␍
current_document_filename: '4518838154.pdf',␍
}),␍
];␍
const processing = processingFromDocuments(docs, {␍
user_task_no: 'OT-MULTI-RUN',␍
status_label: 'extracting',␍
title: null,␍
display_kind: 'multi_document_task',␍
document_names: ['4518838152.pdf', '4518838154.pdf'],␍
file_count: 2,␍
run_no: 'RUN-NEW',␍
objects: [␍
{␍
kind: 'document', object_key: 'DOC-191', workflow_item_no: 'SWI-PDF-91', label: '4518838152.pdf',␍
status_label: 'extracting', document_id: 191, root_document_id: 91,␍
content_hash: 'hash-a', current_run_no: 'RUN-NEW',␍
},␍
{␍
kind: 'document', object_key: 'DOC-92', workflow_item_no: 'SWI-PDF-92', label: '4518838154.pdf',␍
status_label: 'pending_review', document_id: 92, root_document_id: 92,␍
content_hash: 'hash-b', current_run_no: 'RUN-OLD',␍
},␍
],␍
});␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await flushPromises();␍
␍
const task = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI-RUN"]');␍
expect(task.exists()).toBe(true);␍
await task.findAll('button').at(-1)!.trigger('click');␍
await flushPromises();␍
␍
// 断言:任务内两 PDF 均展示,无关 PDF 被过滤␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-PDF-91"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-PDF-92"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-OTHER"]').exists()).toBe(false);␍
});␍
});␍
File diff suppressed because it is too large. Load diff